forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB552edc4Tahinli2 months ago2048 commits

decode.rs23343 lines, 1.5 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
279thread_local! {
280 /// This frame's superres state: `(upscaled_width, superres_denom)`, or
281 /// `(0, 8)` when the frame is not scaled. Spec 7.16's upscale runs
282 /// between CDEF and loop restoration, so LOOP RESTORATION -- unit grid,
283 /// `read_lr`'s unit corners and the pixel filters themselves -- works in
284 /// UPSCALED coordinates while deblock and CDEF work in downscaled ones
285 /// (libaom `av1_superres_upscale` in `decodeframe.c`, and
286 /// `av1_loop_restoration_corners_in_sb`'s own `mi_to_num_x`/`denom_x`
287 /// superres arms). Set once per frame from [`crate::stream`]'s decode
288 /// loop, like [`BIT_DEPTH`], and reset to `(0, 8)` on an unscaled frame
289 /// so a later frame never inherits it.
290 static SUPERRES: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 8)) };
291}
292
293/// Sets [`SUPERRES`] for the current thread. `upscaled_width` is 0 (and
294/// `denom` 8) for a frame that is not superres-scaled.
295pub(crate) fn set_superres(upscaled_width: u32, denom: u32) {
296 SUPERRES.with(|c| c.set((upscaled_width, denom)));
297}
298
299/// `(upscaled_width, superres_denom)` when this frame is superres-scaled
300/// (libaom `av1_superres_scaled`), else `None`.
301pub(crate) fn superres() -> Option<(u32, u32)> {
302 let (w, d) = SUPERRES.with(std::cell::Cell::get);
303 (w > 0 && d != 8).then_some((w, d))
304}
305// Whether this superblock's single CDEF unit (this decoder has no 128x128
306// SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal
307// read -- reset to `false` at the top of each superblock in the two tile
308// loops, spec `read_cdef`'s `cdef_transmitted[index]`.
309thread_local! {
310 static CDEF_TRANSMITTED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
311}
312// Number of superblock columns in the current tile's grid, so
313// [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into
314// [`CDEF_IDX_GRID`].
315thread_local! {
316 static CDEF_SB_COLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
317}
318// One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select
319// which of the header's `1 << cdef.bits` strength pairs applies to that
320// superblock's samples.
321thread_local! {
322 static CDEF_IDX_GRID: std::cell::RefCell<Vec<u8>> = std::cell::RefCell::new(Vec::new());
323}
324// How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`]
325// has read, across every call on the current thread -- the gate's proof that a
326// `cdef_bits > 0` stream actually reached the new reader rather than every
327// superblock coincidentally being all-skip.
328thread_local! {
329 static CDEF_IDX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
330}
331
332// How many times a warp was suppressed for one PLANE because that plane's own
333// block is narrower or shorter than 8 (`av1_init_warp_params`'s own bail-out,
334// reconinter.c) -- the gate's proof that a stream really carries the shape,
335// since the square `side`/`chroma_side` can be 8 or more while the plane's
336// true block is 4 wide (an 8x16 luma block's 4x8 chroma).
337thread_local! {
338 static WARP_PLANE_SUPPRESS_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
339}
340
341/// Current value of [`WARP_PLANE_SUPPRESS_HITS`].
342pub(crate) fn warp_plane_suppress_hits() -> usize {
343 WARP_PLANE_SUPPRESS_HITS.with(|c| c.get())
344}
345
346/// `av1_init_warp_params` (libaom reconinter.c): warp is decided per PLANE and
347/// bails out at `block_width < 8 || block_height < 8`, so the plane's OWN
348/// block dimensions decide it -- never the square `side`/`chroma_side`, which
349/// for a rectangular luma block (8x16, 16x8) or a PARTITION_HORZ/VERT strip is
350/// bigger than the real block in one axis.
351fn warp_plane_allowed(w: usize, h: usize) -> bool {
352 if w >= 8 && h >= 8 {
353 return true;
354 }
355 WARP_PLANE_SUPPRESS_HITS.with(|c| c.set(c.get() + 1));
356 false
357}
358
359/// Current value of [`CDEF_IDX_HITS`].
360pub(crate) fn cdef_idx_hits() -> usize {
361 CDEF_IDX_HITS.with(|c| c.get())
362}
363
364// lane-t900 r6: gate proof for the three r2-r4 root causes that shipped with no
365// counter -- the in-inter tx-depth context (`tx_size_context_txfm_rect`), the
366// non-chroma-reference block that must LEAVE its neighbours' chroma coefficient
367// contexts alone, and the intra-edge filter neighbour pair taken mi-exact
368// instead of from the coarse 16x16 cell.
369thread_local! {
370 static INTRA_IN_INTER_TXCTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
371 static NON_CHROMA_REF_CTX_SKIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
372 static EDGE_FILTER_MI_FIX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
373}
374
375/// Current value of [`INTRA_IN_INTER_TXCTX_HITS`].
376pub(crate) fn intra_in_inter_txctx_hits() -> usize {
377 INTRA_IN_INTER_TXCTX_HITS.with(|c| c.get())
378}
379
380/// Current value of [`NON_CHROMA_REF_CTX_SKIP_HITS`].
381pub(crate) fn non_chroma_ref_ctx_skip_hits() -> usize {
382 NON_CHROMA_REF_CTX_SKIP_HITS.with(|c| c.get())
383}
384
385/// Current value of [`EDGE_FILTER_MI_FIX_HITS`].
386pub(crate) fn edge_filter_mi_fix_hits() -> usize {
387 EDGE_FILTER_MI_FIX_HITS.with(|c| c.get())
388}
389
390// lane-realworld r4: this frame's `delta.q_present` (spec 5.9.17) and its
391// actual step (`1 << delta.q_res`, already the real multiplier, not the raw
392// 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a
393// true no-op, matching every existing gate stream's `delta_q_present == 0`
394// behaviour exactly, the same corner-cut [`CDEF_BITS`] takes above.
395thread_local! {
396 static DELTA_Q_PRESENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
397 static DELTA_Q_RES: std::cell::Cell<i32> = const { std::cell::Cell::new(1) };
398}
399// The running quantizer index (spec `CurrentQIndex`, libaom
400// `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the
401// top of every tile (spec `decode_tile`), carried across superblocks within
402// that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the
403// dequantization call sites instead of the frame-constant `base_q_idx`.
404thread_local! {
405 static CURRENT_Q_IDX: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };
406}
407// This frame's own per-plane DC/AC quantizer-index deltas (lane-sbpart r11,
408// spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- frame-constant (not
409// per-superblock like [`CURRENT_Q_IDX`]), set once per frame decode and read
410// back at every dequantization call site keyed on which plane it is doing.
411thread_local! {
412 static QUANT_DELTAS: std::cell::Cell<crate::quant::QuantDeltas> = const {
413 std::cell::Cell::new(crate::quant::QuantDeltas {
414 y_dc: 0,
415 u_dc: 0,
416 u_ac: 0,
417 v_dc: 0,
418 v_ac: 0,
419 })
420 };
421}
422// How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has
423// read, across every call on the current thread -- the gate's proof that a
424// `delta_q_present` stream actually reached the new reader.
425thread_local! {
426 static DELTA_Q_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
427}
428
429/// Current value of [`DELTA_Q_HITS`].
430pub(crate) fn delta_q_hits() -> usize {
431 DELTA_Q_HITS.with(|c| c.get())
432}
433
434/// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 =
435/// Y, 1 = U, 2 = V) -- luma has no coded `ac` delta (spec 5.9.12 never reads
436/// one), so it is always `0` here.
437fn plane_q_delta(plane_idx: usize) -> (i32, i32) {
438 let d = QUANT_DELTAS.with(|c| c.get());
439 match plane_idx {
440 0 => (d.y_dc, 0),
441 1 => (d.u_dc, d.u_ac),
442 _ => (d.v_dc, d.v_ac),
443 }
444}
445
446/// `read_delta_qindex`/`read_delta_q_params` (spec 5.11.10, libaom
447/// `decodemv.c:85-146,735-770`), called right after [`maybe_read_cdef_idx`]
448/// at every block-decode call site (spec order `skip -> cdef -> delta_q`).
449/// A no-op when `delta_q_present` is unset, or when this block is not at the
450/// superblock's own top-left MI position (`b_row == 0 && b_col == 0` in
451/// libaom, collapsed here to a position check since a partition tree's
452/// top-left leaf is the only block that can ever land there), or when that
453/// leaf both *is* the whole superblock and is `skip` (the one case libaom
454/// itself skips the read, state carrying over unchanged).
455fn maybe_read_delta_q(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool) {
456 if !DELTA_Q_PRESENT.with(|c| c.get()) {
457 return;
458 }
459 let sb_mi = sb_mi_cur() as usize;
460 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
461 return;
462 }
463 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
464 // computed against the sequence's own superblock size (lane-sb128b r1:
465 // it used to be hardcoded against 64 and disabled under `sb128`, which a
466 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
467 // wrong).
468 if is_whole_sb && skip {
469 return;
470 }
471 let mut abs = dec.symbol(&mut cdfs.delta_q) as i32;
472 const DELTA_Q_SMALL: i32 = 3;
473 if abs >= DELTA_Q_SMALL {
474 let rem_bits = dec.literal(3) + 1;
475 let thr = (1i32 << rem_bits) + 1;
476 abs = dec.literal(rem_bits) as i32 + thr;
477 }
478 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
479 let reduced = if sign_negative { -abs } else { abs };
480 DELTA_Q_HITS.with(|c| c.set(c.get() + 1));
481 let res = DELTA_Q_RES.with(|c| c.get());
482 CURRENT_Q_IDX.with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));
483}
484
485// lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi`
486// (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`.
487thread_local! {
488 static DELTA_LF_PRESENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
489 static DELTA_LF_RES: std::cell::Cell<i32> = const { std::cell::Cell::new(1) };
490 static DELTA_LF_MULTI: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
491}
492// The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`,
493// `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile,
494// mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever
495// updates index 0 and every reader treats that as the value for all 4
496// indices (spec `read_delta_lf_params`'s own single-cdf branch).
497thread_local! {
498 static CURRENT_DELTA_LF: std::cell::Cell<[i32; 4]> = const { std::cell::Cell::new([0; 4]) };
499}
500// How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has
501// read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`].
502thread_local! {
503 static DELTA_LF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
504}
505
506/// Current value of [`DELTA_LF_HITS`].
507pub(crate) fn delta_lf_hits() -> usize {
508 DELTA_LF_HITS.with(|c| c.get())
509}
510
511/// `read_delta_lflevel`/`read_delta_lf_params` (spec 5.11.11, libaom
512/// `decodemv.c:99-146,735-770`) -- same shape and same call-site gating as
513/// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over
514/// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or
515/// read once into index 0 otherwise.
516fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool) {
517 if !DELTA_LF_PRESENT.with(|c| c.get()) {
518 return;
519 }
520 let sb_mi = sb_mi_cur() as usize;
521 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
522 return;
523 }
524 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
525 // computed against the sequence's own superblock size (lane-sb128b r1:
526 // it used to be hardcoded against 64 and disabled under `sb128`, which a
527 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
528 // wrong).
529 if is_whole_sb && skip {
530 return;
531 }
532 let multi = DELTA_LF_MULTI.with(|c| c.get());
533 let res = DELTA_LF_RES.with(|c| c.get());
534 let count = if multi { 4 } else { 1 };
535 let mut cur = CURRENT_DELTA_LF.with(|c| c.get());
536 for i in 0..count {
537 let mut abs = if multi {
538 dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32
539 } else {
540 dec.symbol(&mut cdfs.delta_lf) as i32
541 };
542 const DELTA_LF_SMALL: i32 = 3;
543 if abs >= DELTA_LF_SMALL {
544 let rem_bits = dec.literal(3) + 1;
545 let thr = (1i32 << rem_bits) + 1;
546 abs = dec.literal(rem_bits) as i32 + thr;
547 }
548 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
549 let reduced = if sign_negative { -abs } else { abs };
550 cur[i] = (cur[i] + reduced * res).clamp(-63, 63);
551 DELTA_LF_HITS.with(|c| c.set(c.get() + 1));
552 }
553 CURRENT_DELTA_LF.with(|c| c.set(cur));
554}
555
556/// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
557/// after `skip` is known at every block-decode call site. A no-op at
558/// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and
559/// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
560/// `allow_intrabc`, so neither needs a separate check here. Reads once per
561/// superblock, at the first non-skip block.
562fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: bool) {
563 let bits = CDEF_BITS.with(|c| c.get());
564 if bits == 0 || skip || CDEF_TRANSMITTED.with(|c| c.get()) {
565 return;
566 }
567 let idx = dec.literal(u32::from(bits)) as u8;
568 CDEF_TRANSMITTED.with(|c| c.set(true));
569 CDEF_IDX_HITS.with(|c| c.set(c.get() + 1));
570 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
571 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
572 if sb_cols > 0 {
573 CDEF_IDX_GRID.with(|g| {
574 let mut g = g.borrow_mut();
575 let i = sb_r * sb_cols + sb_c;
576 if i < g.len() {
577 g[i] = idx;
578 }
579 });
580 }
581}
582
583// ---------------------------------------------------------------------------
584// lane-seg: segmentation. Header (spec 5.9.14) is parsed by `ec-av1-syntax`;
585// this block is the per-block `segment_id` reader (spec 5.11.7-5.11.9) plus
586// the two consumers a real stream exercises: the per-segment quantizer index
587// (spec 7.12.2 `get_qindex`) and the per-segment loop-filter level
588// (spec 7.14.4). Shapes follow libaom `decodemv.c:read_segment_id`/
589// `read_intra_segment_id`/`read_inter_segment_id` and
590// `pred_common.h:av1_get_spatial_seg_pred` -- note libaom returns the SPATIAL
591// PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which
592// is what the oracle every gate here compares against actually does.
593thread_local! {
594 static SEG: std::cell::RefCell<SegmentationParams> =
595 std::cell::RefCell::new(SegmentationParams::default());
596 /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries
597 /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride).
598 static SEG_IDS: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
599 /// `PrevSegmentIds`: the primary reference frame's saved map, empty when
600 /// this frame has no primary reference (spec `load_previous_segment_ids`).
601 static PREV_SEG_IDS: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
602 /// `(mi_rows, mi_cols)` for both maps above.
603 static SEG_MI_DIMS: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
604 /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi
605 /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which
606 /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead.
607 static ABOVE_SEG_PRED: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
608 static LEFT_SEG_PRED: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
609 /// The block currently being decoded -- read back by [`block_q_idx`].
610 static CUR_SEGMENT_ID: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
611 /// The tile's own top-left mi position, for `AvailU`/`AvailL`.
612 static SEG_TILE_ORIGIN: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
613 /// How many real `segment_id` symbols were read, and the set of segment
614 /// ids any block ended up with -- the gate's proof the feature fired.
615 static SEG_ID_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
616 static SEG_IDS_SEEN: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
617 /// How many `seg_id_predicted` symbols were read (temporal update).
618 static SEG_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
619}
620
621/// Installs this frame's segmentation parameters and allocates its map, with
622/// `prev` the primary reference frame's saved map (spec
623/// `load_previous_segment_ids`; `None` for `PRIMARY_REF_NONE` or an empty
624/// slot). Called once per frame, whether or not segmentation is enabled.
625pub(crate) fn set_segmentation(
626 seg: SegmentationParams,
627 mi_rows: usize,
628 mi_cols: usize,
629 prev: Option<&[u8]>,
630) {
631 SEG.with(|s| *s.borrow_mut() = seg);
632 SEG_MI_DIMS.with(|c| c.set((mi_rows, mi_cols)));
633 SEG_IDS.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]);
634 PREV_SEG_IDS.with(|m| {
635 let mut m = m.borrow_mut();
636 m.clear();
637 if let Some(p) = prev {
638 if p.len() == mi_rows * mi_cols {
639 m.extend_from_slice(p);
640 }
641 }
642 });
643 ABOVE_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_cols]);
644 LEFT_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_rows]);
645 CUR_SEGMENT_ID.with(|c| c.set(0));
646}
647
648/// This frame's decoded segment map, to be stored into whichever reference
649/// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`).
650pub(crate) fn take_segment_ids() -> Vec<u8> {
651 SEG_IDS.with(|m| m.borrow().clone())
652}
653
654/// How many `segment_id` symbols have been read (never reset per frame).
655pub(crate) fn segment_id_hits() -> usize {
656 SEG_ID_HITS.with(|c| c.get())
657}
658
659/// How many distinct segment ids any decoded block has carried.
660pub(crate) fn segment_ids_seen() -> usize {
661 SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize)
662}
663
664/// How many `seg_id_predicted` symbols have been read (temporal update).
665pub(crate) fn segment_pred_hits() -> usize {
666 SEG_PRED_HITS.with(|c| c.get())
667}
668
669/// Resets the segmentation hit counters (gate setup).
670pub(crate) fn reset_segment_hits() {
671 SEG_ID_HITS.with(|c| c.set(0));
672 SEG_IDS_SEEN.with(|c| c.set(0));
673 SEG_PRED_HITS.with(|c| c.set(0));
674}
675
676/// `seg_feature_active_idx(segment_id, feature)` for the frame currently
677/// being decoded, with its `FeatureData` value.
678fn seg_feature(segment_id: usize, feature: usize) -> Option<i32> {
679 SEG.with(|s| {
680 let s = s.borrow();
681 s.feature_active(segment_id, feature)
682 .then(|| i32::from(s.feature_data[segment_id][feature]))
683 })
684}
685
686/// `get_qindex(ignoreDeltaQ = 0, segment_id)` (spec 7.12.2, libaom
687/// `av1_get_qindex`) for the block currently being decoded: the running
688/// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data.
689/// Every dequant call site reads the block's quantizer through here.
690fn block_q_idx() -> i32 {
691 let base = CURRENT_Q_IDX.with(|c| c.get());
692 let seg_id = CUR_SEGMENT_ID.with(|c| c.get()) as usize;
693 match seg_feature(seg_id, SEG_LVL_ALT_Q) {
694 Some(data) => (base + data).clamp(0, 255),
695 None => base,
696 }
697}
698
699/// The segment id recorded for one mi cell of the current frame's map.
700fn segment_id_at(mi_r: usize, mi_c: usize) -> u8 {
701 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
702 if mi_r >= mi_rows || mi_c >= mi_cols {
703 return 0;
704 }
705 SEG_IDS.with(|m| m.borrow()[mi_r * mi_cols + mi_c])
706}
707
708/// `set_segment_id`: stamps `id` over every mi cell this block covers.
709fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8) {
710 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
711 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
712 SEG_IDS.with(|m| {
713 let mut m = m.borrow_mut();
714 for y in 0..y_mis {
715 for x in 0..x_mis {
716 m[(mi_r + y) * mi_cols + mi_c + x] = id;
717 }
718 }
719 });
720 CUR_SEGMENT_ID.with(|c| c.set(id));
721 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
722}
723
724/// `get_predicted_segment_id` (libaom `dec_get_segment_id` over
725/// `last_frame_seg_map`): the minimum previous-frame segment id over the
726/// block's own mi footprint. `0` when there is no previous map.
727fn predicted_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize) -> u8 {
728 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
729 PREV_SEG_IDS.with(|m| {
730 let m = m.borrow();
731 if m.is_empty() {
732 return 0;
733 }
734 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
735 let mut id = u8::MAX;
736 for y in 0..y_mis {
737 for x in 0..x_mis {
738 id = id.min(m[(mi_r + y) * mi_cols + mi_c + x]);
739 }
740 }
741 if id == u8::MAX { 0 } else { id }
742 })
743}
744
745/// `av1_neg_deinterleave` (libaom `decodemv.c:258`).
746fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 {
747 if reference == 0 {
748 return diff;
749 }
750 if reference >= max - 1 {
751 return max - diff - 1;
752 }
753 let half = if 2 * reference < max {
754 diff <= 2 * reference
755 } else {
756 diff <= 2 * (max - reference - 1)
757 };
758 if half {
759 return if diff & 1 != 0 {
760 reference + ((diff + 1) >> 1)
761 } else {
762 reference - (diff >> 1)
763 };
764 }
765 if 2 * reference < max { diff } else { max - (diff + 1) }
766}
767
768/// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current
769/// frame's already-decoded above/left/above-left neighbours.
770fn spatial_seg_pred(mi_r: usize, mi_c: usize) -> (i32, usize) {
771 let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());
772 let (avail_u, avail_l) = (mi_r > row0, mi_c > col0);
773 let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1)));
774 let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c)));
775 let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1)));
776 let ctx = match prev_ul {
777 None => 0,
778 Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2,
779 Some(ul) if Some(ul) == prev_u || Some(ul) == prev_l || prev_u == prev_l => 1,
780 Some(_) => 0,
781 };
782 let pred = match (prev_u, prev_l) {
783 (None, l) => l.unwrap_or(0),
784 (Some(u), None) => u,
785 (Some(u), Some(l)) => {
786 if prev_ul == Some(u) {
787 u
788 } else {
789 l
790 }
791 }
792 };
793 (pred, ctx)
794}
795
796/// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id
797/// when `skip`, otherwise one `segment_id` symbol de-interleaved against
798/// that prediction. Does NOT write the map -- callers do.
799fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, skip: bool) -> u8 {
800 let (pred, ctx) = spatial_seg_pred(mi_r, mi_c);
801 if skip {
802 return pred as u8;
803 }
804 let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32;
805 SEG_ID_HITS.with(|c| c.set(c.get() + 1));
806 let last_active = SEG.with(|s| i32::from(s.borrow().last_active_seg_id));
807 neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active) as u8
808}
809
810/// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block
811/// -- once before `skip` when `SegIdPreSkip`, once after it otherwise (the
812/// caller decides which by passing `pre_skip`).
813fn intra_segment_id(
814 dec: &mut SymbolDecoder,
815 cdfs: &mut Cdfs,
816 mi_r: usize,
817 mi_c: usize,
818 w_mi: usize,
819 h_mi: usize,
820 skip: bool,
821) {
822 if !SEG.with(|s| s.borrow().enabled) {
823 return;
824 }
825 let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip);
826 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
827}
828
829/// Whether this frame's intra blocks read their `segment_id` before `skip`
830/// (`SegIdPreSkip`); `false` also when segmentation is off.
831fn seg_id_pre_skip() -> bool {
832 SEG.with(|s| {
833 let s = s.borrow();
834 s.enabled && s.seg_id_pre_skip
835 })
836}
837
838/// `read_inter_segment_id(preskip)` (spec 5.11.9, libaom `decodemv.c:352`).
839/// Called at both spec positions of an inter frame's block: `pre_skip = true`
840/// before `skip_mode`/`skip`, and `pre_skip = false` after them.
841fn inter_segment_id(
842 dec: &mut SymbolDecoder,
843 cdfs: &mut Cdfs,
844 mi_r: usize,
845 mi_c: usize,
846 w_mi: usize,
847 h_mi: usize,
848 skip: bool,
849 pre_skip: bool,
850) {
851 let (enabled, update_map, temporal_update, pre_skip_frame) = SEG.with(|s| {
852 let s = s.borrow();
853 (s.enabled, s.update_map, s.temporal_update, s.seg_id_pre_skip)
854 });
855 if !enabled {
856 return;
857 }
858 if !update_map {
859 // The map is inherited wholesale from the previous frame.
860 let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi);
861 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
862 return;
863 }
864 if pre_skip && !pre_skip_frame {
865 return;
866 }
867 if !pre_skip && skip {
868 // libaom: a skipped block never codes `seg_id_predicted`, and its
869 // segment id is the spatial prediction.
870 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0);
871 let id = read_segment_id(dec, cdfs, mi_r, mi_c, true);
872 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
873 return;
874 }
875 let id = if temporal_update {
876 let ctx = seg_pred_ctx(mi_r, mi_c);
877 let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0;
878 SEG_PRED_HITS.with(|c| c.set(c.get() + 1));
879 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted));
880 if predicted {
881 predicted_segment_id(mi_r, mi_c, w_mi, h_mi)
882 } else {
883 read_segment_id(dec, cdfs, mi_r, mi_c, false)
884 }
885 } else {
886 read_segment_id(dec, cdfs, mi_r, mi_c, false)
887 };
888 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
889}
890
891/// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags.
892fn seg_pred_ctx(mi_r: usize, mi_c: usize) -> usize {
893 // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and
894 // so contribute 0) outside the tile -- the availability check here is
895 // what keeps a previous tile's stamps out of this tile's context.
896 let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());
897 let above = if mi_r > row0 {
898 ABOVE_SEG_PRED.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))
899 } else {
900 0
901 };
902 let left = if mi_c > col0 {
903 LEFT_SEG_PRED.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))
904 } else {
905 0
906 };
907 usize::from(above + left)
908}
909
910/// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update.
911fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8) {
912 ABOVE_SEG_PRED.with(|m| {
913 let mut m = m.borrow_mut();
914 for i in 0..w_mi {
915 if let Some(cell) = m.get_mut(mi_c + i) {
916 *cell = value;
917 }
918 }
919 });
920 LEFT_SEG_PRED.with(|m| {
921 let mut m = m.borrow_mut();
922 for i in 0..h_mi {
923 if let Some(cell) = m.get_mut(mi_r + i) {
924 *cell = value;
925 }
926 }
927 });
928}
929
930// How many key-frame luma blocks resolved `smooth_neighbor` (spec
931// `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after
932// counter, proving a stream actually put a directional block next to a
933// smooth-predicted neighbour rather than every block reading the (previously
934// hardcoded `false`) edge-filter strength bucket unchanged.
935thread_local! {
936 static SMOOTH_LUMA_HITS: std::cell::Cell<usize> =
937 const { std::cell::Cell::new(0) };
938}
939
940/// Current value of [`SMOOTH_LUMA_HITS`].
941pub(crate) fn smooth_luma_hits() -> usize {
942 SMOOTH_LUMA_HITS.with(|c| c.get())
943}
944
945thread_local! {
946 /// lane-band46 r1: how many split-transform units answered their intra
947 /// reach DIFFERENTLY under libaom's per-unit rules ([`Reach::of_tu`], the
948 /// palette2 r12 fix) than the standalone-block lookup this decoder used to
949 /// apply to them (class reach-is-per-transform-unit). Every hit is a
950 /// transform unit whose above-right / below-left reference samples would
951 /// be wrong without that fix.
952 static SPLIT_TU_REACH_FIX_HITS: std::cell::Cell<usize> =
953 const { std::cell::Cell::new(0) };
954}
955
956/// Current value of [`SPLIT_TU_REACH_FIX_HITS`].
957pub(crate) fn split_tu_reach_fix_hits() -> usize {
958 SPLIT_TU_REACH_FIX_HITS.with(|c| c.get())
959}
960
961/// [`Reach::of_tu`] for one transform unit, counting how often that per-unit
962/// answer differs from the standalone-block answer the call sites used before
963/// lane-palette2 r12 -- the counter a gate asserts on to prove a stream really
964/// exercised the fix. `col_off`/`row_off` are in SAMPLES from the parent
965/// block's top-left `(px, py)`.
966#[allow(clippy::too_many_arguments)]
967fn tu_reach(
968 bw: usize,
969 bh: usize,
970 col_off: usize,
971 row_off: usize,
972 tx: usize,
973 block: Reach,
974 px: usize,
975 py: usize,
976 width: usize,
977 height: usize,
978) -> Reach {
979 let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block);
980 let standalone = Reach::of(tx, px + col_off, py + row_off, width, height);
981 if fixed != standalone {
982 SPLIT_TU_REACH_FIX_HITS.with(|c| c.set(c.get() + 1));
983 }
984 fixed
985}
986
987// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12),
988// across every call on the current thread -- lane-chroma r3's own before/after
989// counter, proving a stream actually exercised chroma's smooth/paeth
990// predictor (the previously-refused round-2 gap) rather than every block
991// landing on DC/CFL/directional.
992thread_local! {
993 static SMOOTH_UV_HITS: std::cell::Cell<usize> =
994 const { std::cell::Cell::new(0) };
995}
996
997/// Current value of [`SMOOTH_UV_HITS`].
998pub(crate) fn smooth_uv_hits() -> usize {
999 SMOOTH_UV_HITS.with(|c| c.get())
1000}
1001
1002// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a
1003// full superblock walk over, across every call on the current thread --
1004// lane-tiles r2's own gate-blind-to-feature guard: a gate over a
1005// multi-tile stream must prove more than one tile actually fired, not just
1006// that the stream carried tile_info.cols > 1.
1007thread_local! {
1008 static TILE_HITS: std::cell::Cell<usize> =
1009 const { std::cell::Cell::new(0) };
1010}
1011/// Current value of [`TILE_HITS`].
1012pub(crate) fn tile_hits() -> usize {
1013 TILE_HITS.with(|c| c.get())
1014}
1015
1016// How many 4-pixel deblocking edge groups [`edge_params`] has actually
1017// selected for filtering, across every call on the current thread -- the same
1018// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1019// exercised `apply_deblock` rather than every edge landing on level 0.
1020thread_local! {
1021 static DEBLOCK_HITS: std::cell::Cell<usize> =
1022 const { std::cell::Cell::new(0) };
1023}
1024/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
1025/// mirroring stream.rs's `pictures_decoded` so the two dumps index
1026/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
1027static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize =
1028 std::sync::atomic::AtomicUsize::new(0);
1029
1030/// Current value of [`DEBLOCK_HITS`].
1031pub(crate) fn deblock_hits() -> usize {
1032 DEBLOCK_HITS.with(|c| c.get())
1033}
1034
1035// lane-defon r1: how many COMPOUND_REFERENCE blocks read a
1036// `UNIDIR_COMP_REFERENCE` pair (both references on the same temporal side,
1037// spec 5.11.25 `comp_reference_type == 0`) -- the gate's proof that a
1038// stream built with `--enable-onesided-comp=1` really exercised the
1039// `uni_comp_ref` alphabet rather than only bidirectional pairs.
1040thread_local! {
1041 static UNI_COMP_HITS: std::cell::Cell<usize> =
1042 const { std::cell::Cell::new(0) };
1043}
1044
1045/// Current value of [`UNI_COMP_HITS`].
1046pub(crate) fn uni_comp_hits() -> usize {
1047 UNI_COMP_HITS.with(|c| c.get())
1048}
1049
1050// lane-defon r1: how many blocks blended through a `COMPOUND_DIFFWTD` mask
1051// (`mc::diffwtd_mask`) -- the narrower half of `MASKED_COMPOUND_HITS`, the
1052// gate's proof that `--enable-diff-wtd-comp=1` reached the difference-weighted
1053// blend and not only the wedge arm.
1054thread_local! {
1055 static DIFFWTD_HITS: std::cell::Cell<usize> =
1056 const { std::cell::Cell::new(0) };
1057}
1058
1059/// Current value of [`DIFFWTD_HITS`].
1060pub(crate) fn diffwtd_hits() -> usize {
1061 DIFFWTD_HITS.with(|c| c.get())
1062}
1063
1064// lane-mcomp64 r1: how many blocks took the INFERRED `COMPOUND_DIFFWTD` arm --
1065// a block size where `av1_is_wedge_used` is false (64x64 is the only such size
1066// this decoder's square inter path reaches), so no `compound_type` symbol is
1067// coded at all. Strictly narrower than `DIFFWTD_HITS`, which also counts the
1068// coded-symbol DIFFWTD blocks at 8x8/16x16/32x32.
1069thread_local! {
1070 static DIFFWTD_INFERRED_HITS: std::cell::Cell<usize> =
1071 const { std::cell::Cell::new(0) };
1072}
1073
1074/// Current value of [`DIFFWTD_INFERRED_HITS`].
1075pub(crate) fn diffwtd_inferred_hits() -> usize {
1076 DIFFWTD_INFERRED_HITS.with(|c| c.get())
1077}
1078
1079// lane-defon r1: how many FORWARD KEYFRAMES were decoded -- a KEY frame coded
1080// with `show_frame == 0`, output later by a `show_existing_frame` header
1081// (aomenc `--enable-fwd-kf=1 --fwd-kf-dist=N`). Counted from
1082// `stream::decode_stream`, which is where the frame header is consumed; the
1083// gate's proof that the on-value really reached the bitstream rather than
1084// being dropped by the rate control.
1085thread_local! {
1086 static FWD_KF_HITS: std::cell::Cell<usize> =
1087 const { std::cell::Cell::new(0) };
1088}
1089
1090/// Current value of [`FWD_KF_HITS`].
1091pub(crate) fn fwd_kf_hits() -> usize {
1092 FWD_KF_HITS.with(|c| c.get())
1093}
1094
1095/// Records one decoded forward keyframe (see [`FWD_KF_HITS`]).
1096pub(crate) fn note_fwd_kf() {
1097 FWD_KF_HITS.with(|c| c.set(c.get() + 1));
1098}
1099
1100// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
1101// the block's own side, across every call on the current thread -- the same
1102// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1103// actually exercised a *split* transform under `TxMode::Select` rather than
1104// every block coincidentally resolving `depth=0` (indistinguishable from
1105// `TxMode::Largest` pixel-wise).
1106thread_local! {
1107 static TX_DEPTH_HITS: std::cell::Cell<usize> =
1108 const { std::cell::Cell::new(0) };
1109}
1110
1111// How many plain SQUARE intra blocks (lane-sqchroma r1) resolved a luma
1112// transform smaller than their own side (`tx_depth != 0`) while coding a
1113// chroma prediction other than `DC_PRED` -- the pair the square path's chroma
1114// only exercises with aomenc's tx-size search left ON (its default), which
1115// every older recipe in this file pins off. Counted at the block, so a stream
1116// where RD happened to give every split-transform block a DC chroma mode
1117// reads as zero rather than silently passing for free.
1118thread_local! {
1119 static SQ_CHROMA_TX_HITS: std::cell::Cell<usize> =
1120 const { std::cell::Cell::new(0) };
1121}
1122
1123/// Current value of [`SQ_CHROMA_TX_HITS`].
1124pub(crate) fn sq_chroma_tx_hits() -> usize {
1125 SQ_CHROMA_TX_HITS.with(|c| c.get())
1126}
1127
1128/// Current value of [`TX_DEPTH_HITS`].
1129pub(crate) fn tx_depth_hits() -> usize {
1130 TX_DEPTH_HITS.with(|c| c.get())
1131}
1132
1133// lane-txselect: how many `txfm_split` symbols an inter frame's var-tx tree
1134// read, and how many of those actually took the split, on the current thread
1135// -- the same before/after counter pattern as [`TX_DEPTH_HITS`], proving a
1136// stream exercised spec 5.11.17's `read_var_tx_size` rather than every block
1137// coincidentally coding one whole-block transform.
1138thread_local! {
1139 static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1140 static TXFM_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1141 // lane-inter4 r2: rectangular INTER residual coding -- how many rect
1142 // strips coded one whole-block rect transform unit, and how many split
1143 // their rect max transform into square sub-transforms.
1144 static RECT_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1145 static RECT_INTER_TXSPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1146 // lane-r14 r2: luma transform units of an inter strip with a 64-px axis
1147 // (64x32/32x64/64x16/16x64), whose coefficients are coded as the
1148 // truncated low-32 corner.
1149 static RECT64_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1150 // lane-rectres r1: whole-block luma transform units of a 32x32-level 1:4
1151 // inter strip, `[32x8, 8x32]`.
1152 static RECT32X8_INTER_TU_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1153 // lane-r14 r3: rectangular var-tx LEAVES, [32x16, 16x32].
1154 static VARTX_RECT_LEAF_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1155 // lane-inter16ab r4: rectangular var-tx leaves with a 4-px axis, [8x4, 4x8]
1156 // -- the `sub_tx_size_map[TX_16X4]` split leaves of a 16x16-level 1:4 strip.
1157 static VARTX_RECT_LEAF4_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1158 // lane-inter4 r3: 16x16-level PARTITION_HORZ / PARTITION_VERT on an inter
1159 // frame -- 16x8 and 8x16 inter leaves.
1160 static INTER_LEAF16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1161 static INTER_LEAF16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1162 // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits,
1163 // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] --
1164 // `decode_inter_block` already carries forty parameters and both are
1165 // frame-constant.
1166 static TX_SELECT_INTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1167 static REDUCED_TX_SET_INTER: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
1168 // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit,
1169 // frame-constant like the two above and stashed the same way -- an intra
1170 // block inside an inter frame reads `use_filter_intra` under it.
1171 static ENABLE_FILTER_INTRA_INTER: std::cell::Cell<bool> =
1172 const { std::cell::Cell::new(false) };
1173}
1174
1175/// Current value of [`TXFM_SPLIT_READS`].
1176pub(crate) fn txfm_split_reads() -> usize {
1177 TXFM_SPLIT_READS.with(|c| c.get())
1178}
1179
1180/// Current value of [`TXFM_SPLIT_HITS`].
1181pub(crate) fn txfm_split_hits() -> usize {
1182 TXFM_SPLIT_HITS.with(|c| c.get())
1183}
1184
1185/// Current value of [`INTER_LEAF16_HORZ_HITS`] (lane-inter4 r3).
1186pub(crate) fn inter_leaf16_horz_hits() -> usize {
1187 INTER_LEAF16_HORZ_HITS.with(|c| c.get())
1188}
1189
1190/// Current value of [`INTER_LEAF16_VERT_HITS`] (lane-inter4 r3).
1191pub(crate) fn inter_leaf16_vert_hits() -> usize {
1192 INTER_LEAF16_VERT_HITS.with(|c| c.get())
1193}
1194
1195/// Current value of [`RECT_INTER_TU_HITS`] (lane-inter4 r2).
1196pub(crate) fn rect_inter_tu_hits() -> usize {
1197 RECT_INTER_TU_HITS.with(|c| c.get())
1198}
1199
1200/// Current value of [`RECT_INTER_TXSPLIT_HITS`] (lane-inter4 r2).
1201pub(crate) fn rect_inter_txsplit_hits() -> usize {
1202 RECT_INTER_TXSPLIT_HITS.with(|c| c.get())
1203}
1204
1205/// Current value of [`RECT64_INTER_TU_HITS`] (lane-r14 r2).
1206pub(crate) fn rect64_inter_tu_hits() -> usize {
1207 RECT64_INTER_TU_HITS.with(|c| c.get())
1208}
1209
1210/// Current value of [`RECT32X8_INTER_TU_HITS`] (lane-rectres r1): `[32x8, 8x32]`
1211/// whole-block luma units of a 32x32-level 1:4 inter strip.
1212pub(crate) fn rect32x8_inter_tu_hits() -> [usize; 2] {
1213 RECT32X8_INTER_TU_HITS.with(|c| c.get())
1214}
1215
1216/// Current value of [`VARTX_RECT_LEAF_HITS`] (lane-r14 r3): how many
1217/// rectangular var-tx leaf transform units were coded, `[32x16, 16x32]`.
1218pub(crate) fn vartx_rect_leaf_hits() -> [usize; 2] {
1219 VARTX_RECT_LEAF_HITS.with(|c| c.get())
1220}
1221
1222/// Current value of [`VARTX_RECT_LEAF4_HITS`] (lane-inter16ab r4): 8x4/4x8
1223/// split leaves of a 16x4/4x16 strip, `[8x4, 4x8]`.
1224pub(crate) fn vartx_rect_leaf4_hits() -> [usize; 2] {
1225 VARTX_RECT_LEAF4_HITS.with(|c| c.get())
1226}
1227
1228/// Records one rectangular var-tx leaf.
1229fn vartx_rect_leaf_hit(tw: usize, th: usize) {
1230 if crate::envflags::env_flag!("EC_VARTXLEAF") {
1231 eprintln!("EC_VARTXLEAF tw={tw} th={th}");
1232 }
1233 let cell = if tw.min(th) == 4 { &VARTX_RECT_LEAF4_HITS } else { &VARTX_RECT_LEAF_HITS };
1234 cell.with(|c| {
1235 let mut h = c.get();
1236 h[usize::from(th > tw)] += 1;
1237 c.set(h);
1238 });
1239}
1240
1241/// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/
1242/// [`ENABLE_FILTER_INTRA_INTER`].
1243pub(crate) fn set_inter_tx_mode(
1244 tx_select: bool,
1245 reduced_tx_set: bool,
1246 enable_filter_intra: bool,
1247) {
1248 TX_SELECT_INTER.with(|c| c.set(tx_select));
1249 REDUCED_TX_SET_INTER.with(|c| c.set(reduced_tx_set));
1250 ENABLE_FILTER_INTRA_INTER.with(|c| c.set(enable_filter_intra));
1251}
1252
1253// How many `partition_w16` reads (a 16x16 block's own partition symbol, key
1254// intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a
1255// plain default-settings aomenc run over lavfi mandelbrot hits this arm on
1256// frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not
1257// the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real
1258// `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`,
1259// chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8
1260// path above).
1261thread_local! {
1262 static VERT_B_INTRA_HITS: std::cell::Cell<usize> =
1263 const { std::cell::Cell::new(0) };
1264}
1265
1266/// Current value of [`VERT_B_INTRA_HITS`].
1267pub(crate) fn vert_b_intra_hits() -> usize {
1268 VERT_B_INTRA_HITS.with(|c| c.get())
1269}
1270
1271// lane-ab16 r1: how many 16x16-level AB partitions fired, per arm, in
1272// `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order. Each arm is two
1273// 8x8 squares (`decode_leaf8`) plus one 16x8/8x16 strip (`decode_leaf_rect`,
1274// the non-skip coefficient path lane-rectx proved); the gate hard-asserts
1275// every arm separately so a run where aomenc's RD only picked one cannot
1276// pass as proof of four.
1277thread_local! {
1278 static AB16_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
1279}
1280
1281/// [`AB16_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16).
1282thread_local! {
1283 /// 4x4 transform units decoded inside an 8x8 square of a
1284 /// `PARTITION_VERT_A`/`_B` -- the exact call that panicked before
1285 /// [`crate::encode::Reach::of_tu`] (lane-ab16 r2), so the gate can prove
1286 /// a real `--enable-tx-size-search=1` stream reaches it.
1287 static VERT_AB_TX4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1288}
1289
1290pub(crate) fn vert_ab_tx4_hits() -> usize {
1291 VERT_AB_TX4_HITS.with(std::cell::Cell::get)
1292}
1293
1294pub(crate) fn ab16_hits_by_arm() -> [usize; 4] {
1295 AB16_HITS.with(std::cell::Cell::get)
1296}
1297
1298fn bump_ab16(arm: usize) {
1299 AB16_HITS.with(|c| {
1300 let mut v = c.get();
1301 v[arm] += 1;
1302 c.set(v);
1303 });
1304}
1305
1306// How many `partition_w16` reads resolved to a plain `PARTITION_HORZ`/
1307// `PARTITION_VERT` (lane-rect16 r2): re-measuring after the VERT_B fix above
1308// showed mandelbrot's real first-hit blocker is this plain arm at mi=(0,7),
1309// not VERT_B (`refusal-names-a-correlate`; the VERT_B write-up's "frame 0's
1310// very first non-NONE/SPLIT symbol" claim was about decode ORDER within one
1311// superblock's z-order recursion, not raster mi position).
1312thread_local! {
1313 static HORZ_VERT_INTRA_HITS: std::cell::Cell<usize> =
1314 const { std::cell::Cell::new(0) };
1315}
1316
1317/// Current value of [`HORZ_VERT_INTRA_HITS`].
1318pub(crate) fn horz_vert_intra_hits() -> usize {
1319 HORZ_VERT_INTRA_HITS.with(|c| c.get())
1320}
1321
1322// How many blocks were decoded as a frame-edge rect strip -- the single
1323// coded half of a `PARTITION_HORZ`/`PARTITION_VERT` at the true frame edge
1324// (lane-oddh r1), i.e. a block living inside the 8px band of a frame whose
1325// height or width is 8 mod 16 (the user's 3840x1608 film). Intra and inter
1326// paths share the counter.
1327thread_local! {
1328 static EDGE_RECT_STRIP_HITS: std::cell::Cell<usize> =
1329 const { std::cell::Cell::new(0) };
1330}
1331
1332/// Current value of [`EDGE_RECT_STRIP_HITS`].
1333pub(crate) fn edge_rect_strip_hits() -> usize {
1334 EDGE_RECT_STRIP_HITS.with(|c| c.get())
1335}
1336
1337// lane-interedge r1: frame-edge half strips on the INTER path, per partition
1338// level (64/32/16) x axis (HORZ at a bottom edge, VERT at a right edge). The
1339// index is `level_idx * 2 + axis` with `level_idx` 0=64, 1=32, 2=16 and
1340// `axis` 0=HORZ (`!has_rows`), 1=VERT (`!has_cols`). Both of the user's films
1341// are height mod 16 == 8, so every inter frame crosses these nodes.
1342thread_local! {
1343 static INTER_EDGE_STRIP_HITS: std::cell::Cell<[usize; 6]> =
1344 const { std::cell::Cell::new([0; 6]) };
1345}
1346
1347/// Bumps one bucket of [`INTER_EDGE_STRIP_HITS`].
1348pub(crate) fn bump_inter_edge_strip(idx: usize) {
1349 INTER_EDGE_STRIP_HITS.with(|c| {
1350 let mut v = c.get();
1351 v[idx] += 1;
1352 c.set(v);
1353 });
1354}
1355
1356// lane-edgeboth r1: how many partition nodes were coded as the BOTH-AXES-CUT
1357// forced split -- libaom `decode_partition` (decodeframe.c):
1358// `else if (!has_rows && !has_cols) partition = PARTITION_SPLIT;`, the one
1359// straddle case that reads NO symbol at all. Indexed by level:
1360// 0 = 16x16, 1 = 32x32, 2 = 64x64, 3 = 128x128; intra and inter share it.
1361thread_local! {
1362 static EDGE_BOTH_CUT_HITS: std::cell::Cell<[usize; 4]> =
1363 const { std::cell::Cell::new([0; 4]) };
1364}
1365
1366fn bump_edge_both_cut(level: usize) {
1367 EDGE_BOTH_CUT_HITS.with(|c| {
1368 let mut v = c.get();
1369 v[level] += 1;
1370 c.set(v);
1371 });
1372}
1373
1374/// Current value of [`INTER_EDGE_STRIP_HITS`] (`[h64, v64, h32, v32, h16, v16]`).
1375pub fn inter_edge_strip_hits() -> [usize; 6] {
1376 INTER_EDGE_STRIP_HITS.with(|c| c.get())
1377}
1378
1379/// Resets [`INTER_EDGE_STRIP_HITS`] -- a refused attempt must not carry hits
1380/// into the next one (class `counter-from-refused-stream`).
1381pub fn reset_inter_edge_strip_hits() {
1382 INTER_EDGE_STRIP_HITS.with(|c| c.set([0; 6]));
1383}
1384
1385/// Current value of [`EDGE_BOTH_CUT_HITS`] (`[16, 32, 64, 128]` levels).
1386pub(crate) fn edge_both_cut_hits() -> [usize; 4] {
1387 EDGE_BOTH_CUT_HITS.with(|c| c.get())
1388}
1389
1390/// Zeroes [`EDGE_BOTH_CUT_HITS`] so a gate can measure a per-attempt delta.
1391pub(crate) fn reset_edge_both_cut_hits() {
1392 EDGE_BOTH_CUT_HITS.with(|c| c.set([0; 4]));
1393}
1394
1395// How many HORZ/VERT intra strips resolved a SPLIT luma transform
1396// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) --
1397// the case every rect path here refused by name before, and the first
1398// refusal the user's ReelB extract (600s in) stops at.
1399thread_local! {
1400 static RECT_SPLIT_TX_HITS: std::cell::Cell<usize> =
1401 const { std::cell::Cell::new(0) };
1402}
1403
1404/// Current value of [`RECT_SPLIT_TX_HITS`].
1405pub(crate) fn rect_split_tx_hits() -> usize {
1406 RECT_SPLIT_TX_HITS.with(|c| c.get())
1407}
1408
1409// The subset of [`RECT_SPLIT_TX_HITS`] that is BOTH superblock-level (one
1410// side 64) AND split past the first depth, i.e. tiled more than one unit in
1411// each axis -- the only shape with a transform unit that has neighbours on
1412// two sides inside its own strip (`row_off > 0 && col_off > 0`), and the one
1413// no gate fired before lane-rectsplit r2 (the shared counter above also
1414// counts 32x32-level and depth-1 strips, so it cannot prove this case).
1415thread_local! {
1416 static RECT_SPLIT_SB_INTERIOR_TU_HITS: std::cell::Cell<usize> =
1417 const { std::cell::Cell::new(0) };
1418}
1419
1420/// Current value of [`RECT_SPLIT_SB_INTERIOR_TU_HITS`].
1421pub(crate) fn rect_split_sb_interior_tu_hits() -> usize {
1422 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.get())
1423}
1424
1425// Per-shape hit counts for the rect chroma transforms lane-rectchroma r1
1426// wired into [`decode_rect_split`] -- the shapes a split-transform strip's
1427// chroma half takes that had no coefficient tables before (index order:
1428// 32x8, 8x32, 8x4, 4x8). One counter per shape because a gate that only
1429// proves the pair it happens to hit cannot catch a transposed scan/context
1430// table (class scan-weights-cross-axis).
1431thread_local! {
1432 static RECT_SPLIT_CHROMA_SHAPE_HITS: std::cell::Cell<[usize; 4]> =
1433 const { std::cell::Cell::new([0; 4]) };
1434}
1435
1436/// Current value of [`RECT_SPLIT_CHROMA_SHAPE_HITS`] (32x8, 8x32, 8x4, 4x8).
1437pub(crate) fn rect_split_chroma_shape_hits() -> [usize; 4] {
1438 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| c.get())
1439}
1440
1441// How many HORZ/VERT intra strips actually predicted with filter intra
1442// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name
1443// ("this decoder predicts square-only") until `predict_filter_intra` took
1444// `bw`x`bh`.
1445thread_local! {
1446 static FILTER_INTRA_RECT_HITS: std::cell::Cell<usize> =
1447 const { std::cell::Cell::new(0) };
1448}
1449
1450/// Current value of [`FILTER_INTRA_RECT_HITS`].
1451pub(crate) fn filter_intra_rect_hits() -> usize {
1452 FILTER_INTRA_RECT_HITS.with(|c| c.get())
1453}
1454
1455// As [`FILTER_INTRA_RECT_HITS`], counting only the 32x32-level 1:4 strips
1456// (32x8/8x32, lane-fi32x8 r1) -- the shapes whose `use_filter_intra` symbol
1457// was never read at all before that round, so a gate needs to prove the flag
1458// fired at THAT shape and not at a 16x8 one somewhere else in the frame.
1459// Split by ORIENTATION: rows 8 (32x8) and 9 (8x32) of `cdf::FILTER_INTRA`
1460// carry different probabilities (18101 vs 20229), so a transposed pair is
1461// only caught by a gate that sees the flag fire on BOTH shapes (class
1462// scan-weights-cross-axis).
1463thread_local! {
1464 static FILTER_INTRA_RECT4_HORZ_HITS: std::cell::Cell<usize> =
1465 const { std::cell::Cell::new(0) };
1466 static FILTER_INTRA_RECT4_VERT_HITS: std::cell::Cell<usize> =
1467 const { std::cell::Cell::new(0) };
1468}
1469
1470/// Current value of [`FILTER_INTRA_RECT4_HORZ_HITS`] (32x8 strips).
1471pub(crate) fn filter_intra_rect4_horz_hits() -> usize {
1472 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.get())
1473}
1474
1475/// Current value of [`FILTER_INTRA_RECT4_VERT_HITS`] (8x32 strips).
1476pub(crate) fn filter_intra_rect4_vert_hits() -> usize {
1477 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.get())
1478}
1479
1480// How many rectangular transform units actually coded coefficients through
1481// [`read_coeffs_rect`] (`all_zero == 0`) -- lane-rect1d's measure that a gate
1482// exercised the rect coefficient reader at all rather than passing on
1483// all-skip blocks.
1484thread_local! {
1485 static RECT_COEFF_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1486 static RECT_CLASS1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1487}
1488
1489/// Current value of [`RECT_COEFF_TU_HITS`].
1490pub(crate) fn rect_coeff_tu_hits() -> usize {
1491 RECT_COEFF_TU_HITS.with(|c| c.get())
1492}
1493
1494/// Rectangular transform units whose resolved `tx_type` is a 1D class
1495/// (`V_DCT`/`H_DCT`) -- [`TX_CLASS1_HITS`]'s rect-only half, so a gate can
1496/// pin that the 1D-class-on-a-RECT-transform path fired rather than settling
1497/// for the square reader's own 1D types.
1498pub(crate) fn rect_class1_hits() -> usize {
1499 RECT_CLASS1_HITS.with(|c| c.get())
1500}
1501
1502// As [`FILTER_INTRA_RECT_HITS`], counting only the strips BELOW 16x16
1503// (8x16/16x8 leaves of a 16x16 HORZ/VERT partition, lane-fistrip r1) -- the
1504// shapes whose `use_filter_intra` symbol had no CDF class before this round.
1505// A gate asserting the wider counter would be satisfied by a 32x16 strip and
1506// prove nothing about the new shapes.
1507thread_local! {
1508 static FILTER_INTRA_RECT_SUB16_HITS: std::cell::Cell<usize> =
1509 const { std::cell::Cell::new(0) };
1510}
1511
1512/// Current value of [`FILTER_INTRA_RECT_SUB16_HITS`].
1513pub(crate) fn filter_intra_rect_sub16_hits() -> usize {
1514 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.get())
1515}
1516
1517// As [`FILTER_INTRA_RECT_SUB16_HITS`], one partition level further down:
1518// 4x8/8x4 leaves of an 8x8 HORZ/VERT (lane-fi8 r1). A gate on the sub16
1519// counter would be satisfied by a 16x8 strip and prove nothing here.
1520thread_local! {
1521 static FILTER_INTRA_RECT_SUB8_HITS: std::cell::Cell<usize> =
1522 const { std::cell::Cell::new(0) };
1523}
1524
1525/// Current value of [`FILTER_INTRA_RECT_SUB8_HITS`].
1526pub(crate) fn filter_intra_rect_sub8_hits() -> usize {
1527 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.get())
1528}
1529
1530// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
1531// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
1532// call on the current thread -- the same before/after counter pattern as
1533// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
1534// `eob_pt`/1D-neighbour context path rather than every block coincidentally
1535// landing on `DCT_DCT`.
1536thread_local! {
1537 static TX_CLASS1_HITS: std::cell::Cell<usize> =
1538 const { std::cell::Cell::new(0) };
1539}
1540
1541// How many `uv_mode` reads resolved to a directional chroma mode (neither
1542// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
1543// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1544// actually exercised chroma's own directional predictor.
1545thread_local! {
1546 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
1547 const { std::cell::Cell::new(0) };
1548}
1549
1550/// Current value of [`DIRECTIONAL_UV_HITS`].
1551pub(crate) fn directional_uv_hits() -> usize {
1552 DIRECTIONAL_UV_HITS.with(|c| c.get())
1553}
1554
1555// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
1556// something other than [`ANGLE_DELTA_ZERO`], across every call in the
1557// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
1558// proving a stream actually exercised a nonzero angle delta.
1559thread_local! {
1560 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
1561 const { std::cell::Cell::new(0) };
1562}
1563
1564// How many [`read_single_ref`] reads resolved to a reference other than
1565// `LAST_FRAME`, across every call on the current thread -- the same before/after
1566// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1567// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
1568// only other supported one so far) rather than every block coincidentally
1569// resolving `LAST_FRAME`.
1570thread_local! {
1571 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
1572 const { std::cell::Cell::new(0) };
1573}
1574
1575/// Current value of [`NON_LAST_REF_HITS`].
1576pub(crate) fn non_last_ref_hits() -> usize {
1577 NON_LAST_REF_HITS.with(|c| c.get())
1578}
1579
1580// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
1581// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
1582// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
1583// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
1584// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
1585// `GOLDEN_FRAME` draw it did not ask for.
1586thread_local! {
1587 static LAST2_HITS: std::cell::Cell<usize> =
1588 const { std::cell::Cell::new(0) };
1589}
1590thread_local! {
1591 static LAST3_HITS: std::cell::Cell<usize> =
1592 const { std::cell::Cell::new(0) };
1593}
1594thread_local! {
1595 static GOLDEN_HITS: std::cell::Cell<usize> =
1596 const { std::cell::Cell::new(0) };
1597}
1598thread_local! {
1599 static BWDREF_HITS: std::cell::Cell<usize> =
1600 const { std::cell::Cell::new(0) };
1601}
1602thread_local! {
1603 static ALTREF2_HITS: std::cell::Cell<usize> =
1604 const { std::cell::Cell::new(0) };
1605}
1606thread_local! {
1607 static ALTREF_HITS: std::cell::Cell<usize> =
1608 const { std::cell::Cell::new(0) };
1609}
1610
1611// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
1612// -- proves a `reference_select` stream actually reached a block that picked
1613// compound, not just that the header bit was set. Every such block is
1614// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
1615// so this only ever counts attempted reads, never a completed decode.
1616thread_local! {
1617 static COMP_MODE_HITS: std::cell::Cell<usize> =
1618 const { std::cell::Cell::new(0) };
1619}
1620
1621/// Current value of [`COMP_MODE_HITS`].
1622pub(crate) fn comp_mode_hits() -> usize {
1623 COMP_MODE_HITS.with(|c| c.get())
1624}
1625
1626// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
1627// use for, across every call on the current thread -- the same before/after
1628// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1629// exercised palette reconstruction rather than only reading and refusing the
1630// `palette_y_mode` symbol.
1631thread_local! {
1632 static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1633}
1634
1635/// Current value of [`PALETTE_HITS`].
1636pub(crate) fn palette_hits() -> usize {
1637 PALETTE_HITS.with(|c| c.get())
1638}
1639
1640// lane-tiles r12: of those, how many sat at their own TILE's left column --
1641// exactly the blocks whose palette cache/ctx must NOT see the previous tile's
1642// colours (`av1_get_palette_cache`'s `xd->left_mbmi == NULL`). A multi-tile
1643// palette gate that never hits one proves nothing about the tile guard.
1644thread_local! {
1645 static PALETTE_TILE_LEFT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1646}
1647
1648/// Current value of [`PALETTE_TILE_LEFT_HITS`].
1649pub(crate) fn palette_tile_left_hits() -> usize {
1650 PALETTE_TILE_LEFT_HITS.with(|c| c.get())
1651}
1652
1653// lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma
1654// palette use -- proves a stream actually reconstructed UV palette pixels,
1655// not just read and refused the `palette_uv_mode` symbol.
1656thread_local! {
1657 static PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1658}
1659
1660/// Current value of [`PALETTE_UV_HITS`].
1661pub(crate) fn palette_uv_hits() -> usize {
1662 PALETTE_UV_HITS.with(|c| c.get())
1663}
1664
1665// lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`])
1666// decoded a real palette-Y use -- proves the rect strip's own palette syntax
1667// (not just the square path's) actually fired.
1668thread_local! {
1669 static PALETTE_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1670}
1671
1672/// Current value of [`PALETTE_RECT_HITS`].
1673pub(crate) fn palette_rect_hits() -> usize {
1674 PALETTE_RECT_HITS.with(|c| c.get())
1675}
1676
1677// lane-palette2 r6: how many HORZ/VERT rect intra strips ran the
1678// [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] --
1679// i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in
1680// range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per
1681// RD, almost always refused-on-use because the block doesn't end up USING a
1682// palette -- see r5's report). This is the site the removed refusal
1683// ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it
1684// fired here whether or not the block picked a palette, so this is the
1685// counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost
1686// never observes.
1687thread_local! {
1688 static RECT_SCREEN_CONTENT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1689}
1690
1691/// Current value of [`RECT_SCREEN_CONTENT_HITS`].
1692pub(crate) fn rect_screen_content_hits() -> usize {
1693 RECT_SCREEN_CONTENT_HITS.with(|c| c.get())
1694}
1695
1696// lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a
1697// split luma transform (`logical_tx != side`) -- proves the per-TU index-map
1698// windowing actually ran, not just that the whole-block path stayed exact.
1699// Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16);
1700// first actually incremented in r7, when the refusal it guarded was lifted.
1701thread_local! {
1702 static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1703}
1704
1705thread_local! {
1706 /// lane-kf900 r4: rect intra strips that ACTUALLY use a palette -- the
1707 /// 1:4 shapes (32x8/8x32, 16x4/4x16) and the sub-16x16 2:1 leaves
1708 /// (16x8/8x16), the two shapes the lifted refusals named.
1709 static RECT4_PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1710}
1711
1712/// Current value of [`RECT4_PALETTE_HITS`].
1713pub(crate) fn rect4_palette_hits() -> usize {
1714 RECT4_PALETTE_HITS.with(|c| c.get())
1715}
1716
1717/// Current value of [`PALETTE_SPLIT_TX_HITS`].
1718pub(crate) fn palette_split_tx_hits() -> usize {
1719 PALETTE_SPLIT_TX_HITS.with(|c| c.get())
1720}
1721
1722thread_local! {
1723 /// lane-pal8 r1: square 8x8 LEAVES ([`decode_leaf8`]) that actually use a
1724 /// palette (Y or UV) -- the shape every 8-bit `--tune-content=screen`
1725 /// stream stopped on, since aomenc palettes square blocks at 8 bit and
1726 /// `--min-partition-size=8` puts them on this leaf path.
1727 static PALETTE_LEAF8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1728}
1729
1730/// Current value of [`PALETTE_LEAF8_HITS`].
1731pub(crate) fn palette_leaf8_hits() -> usize {
1732 PALETTE_LEAF8_HITS.with(|c| c.get())
1733}
1734
1735/// Zeroes [`PALETTE_LEAF8_HITS`] (per-attempt gate counting).
1736pub(crate) fn reset_palette_leaf8_hits() {
1737 PALETTE_LEAF8_HITS.with(|c| c.set(0));
1738}
1739
1740thread_local! {
1741 /// lane-pal8 r1: NON-SKIP palette blocks on a superblock-level (64-level)
1742 /// HORZ/VERT or 1:4 strip ([`decode_block_rect64`]) -- i.e. a palette
1743 /// block that also carries a real, corner-cropped luma transform.
1744 static PALETTE_SB_STRIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1745}
1746
1747/// Current value of [`PALETTE_SB_STRIP_HITS`].
1748pub(crate) fn palette_sb_strip_hits() -> usize {
1749 PALETTE_SB_STRIP_HITS.with(|c| c.get())
1750}
1751
1752/// Zeroes [`PALETTE_SB_STRIP_HITS`] (per-attempt gate counting).
1753pub(crate) fn reset_palette_sb_strip_hits() {
1754 PALETTE_SB_STRIP_HITS.with(|c| c.set(0));
1755}
1756
1757// lane-t900 r22: palette blocks reconstructed inside an INTER frame (the
1758// intra-in-inter path, `decode_inter_block`/`decode_inter_block8`) -- counted
1759// apart from [`PALETTE_HITS`] so a witness gate can prove the INTER-frame
1760// capability rather than the key frame's, which every screen stream also
1761// carries.
1762thread_local! {
1763 static INTRA_IN_INTER_PALETTE_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1764 static INTRA_IN_INTER_PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1765}
1766
1767// lane-t900 r23: as [`INTRA_IN_INTER_PALETTE_Y_HITS`], narrowed to the 8x8
1768// LEAF site ([`decode_inter_block8`]'s intra arm) -- the >=16 site fires the
1769// shared counter too, so only this one proves a gate really reached the leaf
1770// where the refusal used to sit.
1771thread_local! {
1772 static INTER8_PALETTE_HITS: std::cell::Cell<(usize, usize)> =
1773 const { std::cell::Cell::new((0, 0)) };
1774}
1775
1776/// Current values of the 8x8-leaf intra-in-inter palette counters, `(y, uv)`.
1777pub(crate) fn inter8_palette_hits() -> (usize, usize) {
1778 INTER8_PALETTE_HITS.with(std::cell::Cell::get)
1779}
1780
1781/// Current values of the two intra-in-inter palette counters, `(y, uv)`.
1782pub(crate) fn intra_in_inter_palette_hits() -> (usize, usize) {
1783 (
1784 INTRA_IN_INTER_PALETTE_Y_HITS.with(|c| c.get()),
1785 INTRA_IN_INTER_PALETTE_UV_HITS.with(|c| c.get()),
1786 )
1787}
1788
1789// lane-hgkf r2: SKIPPED intra blocks whose `tx_depth` split the luma transform
1790// and which are therefore predicted one transform unit at a time (a skipped
1791// block codes no coefficients, so nothing else in the stream witnesses this
1792// path -- only the pixels do).
1793thread_local! {
1794 static SKIP_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1795}
1796
1797/// Current value of [`SKIP_SPLIT_TX_HITS`] (blocks, not units).
1798pub fn skip_split_tx_hits() -> usize {
1799 SKIP_SPLIT_TX_HITS.with(|c| c.get())
1800}
1801
1802/// Zeroes [`SKIP_SPLIT_TX_HITS`] before a gate's own decode attempt.
1803pub fn reset_skip_split_tx_hits() {
1804 SKIP_SPLIT_TX_HITS.with(|c| c.set(0));
1805}
1806
1807// lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth`
1808// symbol split their luma transform, bucketed by block side (8, 16, 32, 64) --
1809// the gate's proof that the lifted path actually ran, per size.
1810thread_local! {
1811 static INTRA_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 4]> =
1812 const { std::cell::Cell::new([0; 4]) };
1813}
1814
1815/// Current value of [`INTRA_IN_INTER_SPLIT_TX_HITS`], indexed 8/16/32/64.
1816pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] {
1817 INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
1818}
1819
1820thread_local! {
1821 /// A just-decoded palette-Y block's own predicted pixels
1822 /// (`side*side`, row-major, `colors[map[i]]`), consumed by
1823 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
1824 /// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
1825 /// per-block override through `read_plane`'s two dozen call sites is the
1826 /// alternative this avoids). Always empty again once that call consumes
1827 /// it (`.take()`), so a non-palette block's own `reconstruct` call never
1828 /// sees stale state.
1829 static PALETTE_PRED: std::cell::RefCell<Option<Vec<u16>>> =
1830 const { std::cell::RefCell::new(None) };
1831}
1832
1833
1834/// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
1835/// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a
1836/// site whose reconstruct never runs would be picked up by the NEXT block's
1837/// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
1838/// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
1839#[track_caller]
1840fn set_palette_pred(buf: Vec<u16>) {
1841 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
1842 let stale = PALETTE_PRED.with(|c| c.borrow().is_some());
1843 eprintln!(
1844 "PALSET len={} stale={stale} at {}",
1845 buf.len(),
1846 std::panic::Location::caller()
1847 );
1848 }
1849 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(buf));
1850}
1851
1852#[track_caller]
1853fn take_palette_pred() -> Option<Vec<u16>> {
1854 let got = PALETTE_PRED.with(|c| c.borrow_mut().take());
1855 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
1856 eprintln!(
1857 "PALTAKE len={:?} at {}",
1858 got.as_ref().map(Vec::len),
1859 std::panic::Location::caller()
1860 );
1861 }
1862 got
1863}
1864
1865thread_local! {
1866 /// The current frame's `mi` grid, kept only while a frame header set
1867 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
1868 /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
1869 /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
1870 /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
1871 /// does not allow intrabc (so nothing is paid for it).
1872 ///
1873 /// corner-cut: only [`decode_block`] (the square path) records into it,
1874 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
1875 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
1876 /// be wrong there; upgrade = record from the rect/leaf paths too.
1877 static INTRABC_MI_GRID: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>> =
1878 const { std::cell::RefCell::new(None) };
1879 /// The block vector [`read_intra_mode`] just decoded, handed to
1880 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
1881 /// which the alternative -- a tenth tuple member through every caller --
1882 /// already avoids). Always `.take()`n by the block that reads it.
1883 static INTRABC_DV: std::cell::Cell<Option<(i32, i32)>> = const { std::cell::Cell::new(None) };
1884 /// How many blocks decoded `use_intrabc == 1` -- the gate's hit counter.
1885 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1886 /// The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so
1887 /// an intrabc block's chroma reads can inherit it (see
1888 /// [`INTRABC_CHROMA_TX`]). Written on every luma read; only ever read
1889 /// through that one arming site.
1890 static LUMA_TX_TYPE: std::cell::Cell<TxType> = const { std::cell::Cell::new(TxType::DctDct) };
1891 /// libaom `av1_get_tx_type` (`blockd.h:1350`): for `PLANE_TYPE_UV` it
1892 /// branches on `is_inter_block(mbmi)` -- which `is_intrabc_block` also
1893 /// satisfies (`blockd.h:373`) -- and takes the *colocated luma
1894 /// transform's coded* `tx_type` (`mbmi->txk_type[...]`), never
1895 /// `intra_mode_to_tx_type` of the chroma mode. `Some` only across an
1896 /// intrabc block's two chroma [`read_plane`] calls; the type decides the
1897 /// `TX_CLASS`, hence the scan order, `eob_multi_ctx` and every nz context
1898 /// -- getting it wrong desyncs the chroma coefficients, it is not a
1899 /// reconstruction-only detail.
1900 static INTRABC_CHROMA_TX: std::cell::Cell<Option<TxType>> = const { std::cell::Cell::new(None) };
1901}
1902
1903/// Whether this frame's header set `allow_intrabc` -- [`INTRABC_MI_GRID`] is
1904/// `Some` exactly then (set once per frame in `decode_frame`), so the flag
1905/// needs no separate plumbing to reach the rect-strip mode reader.
1906fn allow_intrabc_frame() -> bool {
1907 INTRABC_MI_GRID.with(|g| g.borrow().is_some())
1908}
1909
1910thread_local! {
1911 /// How many rect intra strips READ the `use_intrabc` symbol (i.e. how many
1912 /// times the fix below was exercised) -- the rect-strip gate's hit counter,
1913 /// distinct from [`INTRABC_HITS`] which counts blocks that USE intrabc.
1914 static RECT_INTRABC_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1915}
1916
1917/// Current value of [`RECT_INTRABC_READS`].
1918pub(crate) fn rect_intrabc_reads() -> usize {
1919 RECT_INTRABC_READS.with(|c| c.get())
1920}
1921
1922/// Zeroes [`RECT_INTRABC_READS`] (gate tests call this before a decode).
1923pub(crate) fn reset_rect_intrabc_reads() {
1924 RECT_INTRABC_READS.with(|c| c.set(0));
1925}
1926
1927thread_local! {
1928 /// Blocks that USED intrabc at an 8x8 LEAF (`decode_leaf8`) specifically
1929 /// -- the shape lane-kf900 r7 fixed; [`INTRABC_HITS`] counts every shape.
1930 static LEAF8_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1931}
1932
1933/// Current value of [`LEAF8_INTRABC_HITS`].
1934pub(crate) fn leaf8_intrabc_hits() -> usize {
1935 LEAF8_INTRABC_HITS.with(|c| c.get())
1936}
1937
1938/// Zeroes [`LEAF8_INTRABC_HITS`] (gate tests call this before a decode).
1939pub(crate) fn reset_leaf8_intrabc_hits() {
1940 LEAF8_INTRABC_HITS.with(|c| c.set(0));
1941}
1942
1943/// Current value of [`INTRABC_HITS`].
1944pub(crate) fn intrabc_hits() -> usize {
1945 INTRABC_HITS.with(|c| c.get())
1946}
1947
1948/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
1949pub(crate) fn reset_intrabc_hits() {
1950 INTRABC_HITS.with(|c| c.set(0));
1951}
1952
1953/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
1954/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
1955/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
1956/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
1957fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>) {
1958 INTRABC_MI_GRID.with(|g| {
1959 let mut g = g.borrow_mut();
1960 let Some((grid, _, _)) = g.as_mut() else {
1961 return;
1962 };
1963 let info = crate::mvstack::MiInfo {
1964 is_inter: dv.is_some(),
1965 ref_frame: 0,
1966 ref_frame1: None,
1967 mv: dv.unwrap_or((0, 0)),
1968 mv1: None,
1969 is_new_mv: dv.is_some(),
1970 is_global_mv0: false,
1971 is_global_mv1: false,
1972 size: n4,
1973 size_h: n4,
1974 };
1975 for r in mi_r..mi_r + n4 {
1976 for c in mi_c..mi_c + n4 {
1977 grid.set(r, c, info);
1978 }
1979 }
1980 });
1981}
1982
1983// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
1984// proves a real `skip_mode_present` stream actually reached a block that
1985// picked it, not just that the frame header bit was set.
1986thread_local! {
1987 static SKIP_MODE_HITS: std::cell::Cell<usize> =
1988 const { std::cell::Cell::new(0) };
1989}
1990
1991/// Current value of [`SKIP_MODE_HITS`].
1992pub(crate) fn skip_mode_hits() -> usize {
1993 SKIP_MODE_HITS.with(|c| c.get())
1994}
1995
1996// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
1997// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
1998// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
1999// reached [`obmc_blend`], not just the header bit.
2000thread_local! {
2001 static OBMC_HITS: std::cell::Cell<usize> =
2002 const { std::cell::Cell::new(0) };
2003}
2004
2005// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the
2006// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled
2007// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while
2008// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have
2009// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this
2010// decoder used to read with the wrong alphabet, so a gate that asserts this
2011// counter advanced proves the fixed path fired (class
2012// `gate-blind-to-feature`).
2013thread_local! {
2014 static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2015}
2016
2017/// Current value of [`FIMV_ALPHABET_HITS`].
2018pub fn fimv_alphabet_hits() -> usize {
2019 FIMV_ALPHABET_HITS.with(|c| c.get())
2020}
2021
2022// lane-fimv r1: how many frame headers this decoder has decoded with
2023/// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate
2024// prove the encoder really produced the header state under test rather than
2025// assume it.
2026thread_local! {
2027 static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2028}
2029
2030/// Current value of [`FIMV_FRAME_HITS`].
2031pub fn fimv_frame_hits() -> usize {
2032 FIMV_FRAME_HITS.with(|c| c.get())
2033}
2034
2035/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
2036/// `force_integer_mv` bit is set.
2037pub fn note_force_integer_mv_frame() {
2038 FIMV_FRAME_HITS.with(|c| c.set(c.get() + 1));
2039}
2040
2041/// Current value of [`OBMC_HITS`].
2042pub(crate) fn obmc_hits() -> usize {
2043 OBMC_HITS.with(|c| c.get())
2044}
2045
2046// lane-t900 r27: OBMC blends that actually READ a recorded switchable filter
2047// off the neighbour band -- the positive half of the proof for "an OBMC
2048// neighbour whose switchable interp filter was never recorded". A
2049// fixed-filter frame returns before this point (its neighbours legitimately
2050// carry the `[3, 3]` sentinel), so every bump is a neighbour whose own
2051// `interp_filter` symbols were published by `record_inter_rect_mi`.
2052thread_local! {
2053 static OBMC_FILTER_BAND_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2054}
2055
2056/// Current value of [`OBMC_FILTER_BAND_READS`].
2057pub(crate) fn obmc_filter_band_reads() -> usize {
2058 OBMC_FILTER_BAND_READS.with(|c| c.get())
2059}
2060
2061// lane-scaledref r1: per-case firing counts for the scaled-reference gate
2062// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED
2063// reference would pass just as well and prove nothing, so the gate
2064// hard-asserts each combination this round lifts actually occurred:
2065// a compound block with a scaled tap, a warp block whose warp libaom
2066// suppresses because the reference is scaled, an OBMC block, an interintra
2067// block, and an 8x8 leaf.
2068thread_local! {
2069 static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2070 static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2071 static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2072 static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2073 static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2074 static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2075 static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2076}
2077
2078/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one
2079/// scaled and one unscaled tap.
2080pub(crate) fn mixed_scale_compound_hits() -> usize {
2081 MIXED_SCALE_COMPOUND_HITS.with(|c| c.get())
2082}
2083
2084/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have
2085/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf`
2086/// instead because their reference is scaled (libaom `motion_mode_allowed`,
2087/// `blockd.h:1484`).
2088pub(crate) fn scaled_warp_suppressed_hits() -> usize {
2089 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get())
2090}
2091
2092/// Current value of [`SCALED_COMPOUND_HITS`].
2093pub(crate) fn scaled_compound_hits() -> usize {
2094 SCALED_COMPOUND_HITS.with(|c| c.get())
2095}
2096
2097/// Current value of [`SCALED_WARP_FALLBACK_HITS`].
2098pub fn scaled_warp_fallback_hits() -> usize {
2099 SCALED_WARP_FALLBACK_HITS.with(|c| c.get())
2100}
2101
2102/// Current value of [`SCALED_OBMC_HITS`].
2103pub(crate) fn scaled_obmc_hits() -> usize {
2104 SCALED_OBMC_HITS.with(|c| c.get())
2105}
2106
2107/// Current value of [`SCALED_INTERINTRA_HITS`].
2108pub(crate) fn scaled_interintra_hits() -> usize {
2109 SCALED_INTERINTRA_HITS.with(|c| c.get())
2110}
2111
2112/// Current value of [`SCALED_BLOCK8_HITS`].
2113pub(crate) fn scaled_block8_hits() -> usize {
2114 SCALED_BLOCK8_HITS.with(|c| c.get())
2115}
2116
2117// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
2118// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
2119// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
2120// 8x8-leaf OBMC block apart from a 16x16+ one.
2121thread_local! {
2122 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2123}
2124
2125// lane-interp3 r1: how many inter blocks read a SWITCHABLE `interp_filter`
2126// pair whose two directions differ (`enable_dual_filter` only -- with dual
2127// filter off both directions take the single symbol, so this can never fire).
2128// A gate asserting it proves the stream really carries dual-filter blocks.
2129thread_local! {
2130 static DUAL_FILTER_DIFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2131}
2132
2133// lane-interp3 r1: how many COMPOUND 8x8 leaves read their own
2134// `read_mb_interp_filter` symbol(s) -- the read this round added (the leaf
2135// used to skip it entirely, losing a symbol and stamping the `[3, 3]`
2136// no-filter sentinel that made a neighbouring OBMC block panic).
2137thread_local! {
2138 static COMPOUND8_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2139}
2140
2141/// Current value of [`DUAL_FILTER_DIFF_HITS`].
2142pub(crate) fn dual_filter_diff_hits() -> usize {
2143 DUAL_FILTER_DIFF_HITS.with(|c| c.get())
2144}
2145
2146/// Current value of [`COMPOUND8_FILTER_HITS`].
2147pub(crate) fn compound8_filter_hits() -> usize {
2148 COMPOUND8_FILTER_HITS.with(|c| c.get())
2149}
2150
2151// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
2152// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
2153// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
2154// -- the gate's proof that a fixture really exercises the alphabet this
2155// round changed, even though the block itself still refuses (warp
2156// estimation/filter not ported).
2157thread_local! {
2158 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
2159 const { std::cell::Cell::new(0) };
2160}
2161
2162/// Current value of [`WARP_SELECTED_HITS`].
2163pub(crate) fn warp_selected_hits() -> usize {
2164 WARP_SELECTED_HITS.with(|c| c.get())
2165}
2166
2167// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one
2168// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane`
2169// into the compound intermediate) rather than translationally -- the
2170// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model
2171// really reached [`crate::warp::warp_affine_compound`].
2172thread_local! {
2173 static COMPOUND_WARP_HITS: std::cell::Cell<usize> =
2174 const { std::cell::Cell::new(0) };
2175}
2176
2177/// Current value of [`COMPOUND_WARP_HITS`].
2178pub(crate) fn compound_warp_hits() -> usize {
2179 COMPOUND_WARP_HITS.with(|c| c.get())
2180}
2181
2182// lane-interp3 r3: the same proof narrowed to the 8x8 LEAF's own compound
2183// arm ([`decode_inter_block8`]) -- that arm predicted both taps
2184// translationally until r3, so a gate needs to tell a warped 8x8 compound
2185// leaf apart from a warped 16x16+ one (both bump [`COMPOUND_WARP_HITS`]).
2186thread_local! {
2187 static COMPOUND_WARP_HITS_8: std::cell::Cell<usize> =
2188 const { std::cell::Cell::new(0) };
2189}
2190
2191/// Current value of [`COMPOUND_WARP_HITS_8`].
2192pub(crate) fn compound_warp_hits_8() -> usize {
2193 COMPOUND_WARP_HITS_8.with(|c| c.get())
2194}
2195
2196// lane-gmaffine r1: how many blocks built their prediction from a
2197// SIX-parameter (`AFFINE`) global-motion model through
2198// `crate::warp::global_warp_params` -- the gate's proof that a stream really
2199// carried an AFFINE `global_motion_params` AND that a block was predicted
2200// with it, not merely that the header parsed one.
2201thread_local! {
2202 static AFFINE_GM_HITS: std::cell::Cell<usize> =
2203 const { std::cell::Cell::new(0) };
2204}
2205
2206/// Current value of [`AFFINE_GM_HITS`].
2207pub(crate) fn affine_gm_hits() -> usize {
2208 AFFINE_GM_HITS.with(|c| c.get())
2209}
2210
2211// lane-t900 r9: rect blocks whose warp-sample top-right probe answers
2212// differently at the block's WIDTH than at libaom's
2213// `AOMMAX(xd->width, xd->height)` -- each one is a `num_proj_ref` that could
2214// pick the wrong motion_mode alphabet.
2215thread_local! {
2216 static TR_REACH_LONGER_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2217}
2218
2219/// Current value of [`TR_REACH_LONGER_SIDE_HITS`].
2220pub fn tr_reach_longer_side_hits() -> usize {
2221 TR_REACH_LONGER_SIDE_HITS.with(std::cell::Cell::get)
2222}
2223
2224// lane-t900 r9: libaom `is_nontrans_global_motion` (mvref_common.h) returns 0
2225// for `AOMMIN(mi_size_wide[bsize], mi_size_high[bsize]) < 2`, i.e. any block
2226// with a 4-px side is NEVER "non-translational global" and therefore ALWAYS
2227// reads its interp-filter symbol. Counts the blocks where that guard flips
2228// our answer -- a GLOBALMV/GLOBAL_GLOBALMV block with a non-TRANSLATION model
2229// and a 4-px side, which we used to suppress the interp read on (a pre-mode
2230// entropy desync one symbol wide).
2231thread_local! {
2232 static GM_NONTRANS_SMALL_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2233}
2234
2235/// Current value of [`GM_NONTRANS_SMALL_SIDE_HITS`].
2236pub fn gm_nontrans_small_side_hits() -> usize {
2237 GM_NONTRANS_SMALL_SIDE_HITS.with(std::cell::Cell::get)
2238}
2239
2240// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves
2241// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real
2242// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented
2243// only once `find_projection` returned a usable model, unlike
2244// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates'
2245// proof that the leaf path itself fired, not the 16x16+ one.
2246thread_local! {
2247 static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2248 static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2249}
2250
2251/// Current value of [`GLOBALMV_HITS_8`].
2252pub(crate) fn globalmv_hits_8() -> usize {
2253 GLOBALMV_HITS_8.with(|c| c.get())
2254}
2255
2256/// Current value of [`WARP_HITS_8`].
2257pub(crate) fn warp_hits_8() -> usize {
2258 WARP_HITS_8.with(|c| c.get())
2259}
2260
2261// How many blocks decoded `interintra == 1` with the non-wedge blended
2262// prediction applied (lane-interintra r1) -- the gate's proof that a
2263// stream actually exercised interintra.
2264thread_local! {
2265 static INTERINTRA_HITS: std::cell::Cell<usize> =
2266 const { std::cell::Cell::new(0) };
2267}
2268
2269/// Current value of [`INTERINTRA_HITS`].
2270pub(crate) fn interintra_hits() -> usize {
2271 INTERINTRA_HITS.with(|c| c.get())
2272}
2273
2274// lane-midcut r1: of those, how many were RECTANGULAR (`write_w != write_h`)
2275// -- the shape `interintra_blend` used to build a square `side x side` intra
2276// predictor for, with `ii_size_scales`/`edges` taken at the square. Every
2277// pre-existing interintra gate passed with that bug, so the rect arm needs
2278// its own counter to stop being vacuous.
2279thread_local! {
2280 static INTERINTRA_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2281}
2282
2283/// Current value of [`INTERINTRA_RECT_HITS`].
2284pub fn interintra_rect_hits() -> usize {
2285 INTERINTRA_RECT_HITS.with(|c| c.get())
2286}
2287
2288// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
2289// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
2290// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
2291// gate fixture actually exercises this alphabet, even though the block
2292// still refuses (the mask blend itself is unported).
2293thread_local! {
2294 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
2295 const { std::cell::Cell::new(0) };
2296}
2297
2298/// Current value of [`MASKED_COMPOUND_HITS`].
2299pub(crate) fn masked_compound_hits() -> usize {
2300 MASKED_COMPOUND_HITS.with(|c| c.get())
2301}
2302
2303// lane-intersub8 r4/r5: the NON-SQUARE half of `MASKED_COMPOUND_HITS` -- a
2304// masked-compound block whose true footprint is rectangular, i.e. the case
2305// whose `compound_type`/`wedge_idx` CDF row r4 fixed (it used to read the
2306// square envelope's `BLOCK_SIZES_ALL` index). Square blocks cannot show that
2307// defect, so a gate asserting `masked_compound_hits` alone stays vacuous for it.
2308thread_local! {
2309 static RECT_MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
2310 const { std::cell::Cell::new(0) };
2311}
2312
2313/// Current value of [`RECT_MASKED_COMPOUND_HITS`].
2314pub(crate) fn rect_masked_compound_hits() -> usize {
2315 RECT_MASKED_COMPOUND_HITS.with(|c| c.get())
2316}
2317
2318// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
2319// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
2320// actually exercised the wedge blend, not just the DIFFWTD half of
2321// `MASKED_COMPOUND_HITS`.
2322thread_local! {
2323 static WEDGE_HITS: std::cell::Cell<usize> =
2324 const { std::cell::Cell::new(0) };
2325}
2326
2327/// Current value of [`WEDGE_HITS`].
2328pub(crate) fn wedge_hits() -> usize {
2329 WEDGE_HITS.with(|c| c.get())
2330}
2331
2332// How many blocks decoded a real wedge-INTERINTRA block
2333// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
2334// a gate fixture exercised the wedge blend (fixed sign 0), not just the
2335// smooth arm counted by `INTERINTRA_HITS`.
2336thread_local! {
2337 static WII_HITS: std::cell::Cell<usize> =
2338 const { std::cell::Cell::new(0) };
2339}
2340
2341/// Current value of [`WII_HITS`].
2342pub(crate) fn wii_hits() -> usize {
2343 WII_HITS.with(|c| c.get())
2344}
2345
2346// lane-sbrect10 r1: how many INTRA blocks read `uv_mode` off the 13-symbol
2347// NO-CFL alphabet *because their size excludes CFL* (libaom `is_cfl_allowed`:
2348// wide <= 32 && high <= 32). The witness that a gate stream really carries a
2349// 64-axis intra block -- the shape whose 14-symbol read desynced every inter
2350// frame carrying one.
2351thread_local! {
2352 static NOCFL_UV_MODE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2353}
2354
2355/// Current value of [`NOCFL_UV_MODE_HITS`].
2356pub(crate) fn nocfl_uv_mode_hits() -> usize {
2357 NOCFL_UV_MODE_HITS.with(|c| c.get())
2358}
2359
2360/// lane-inter16ab r5: the six RECTANGULAR wedge shapes, in this order --
2361/// the counter slots of [`RECT_WEDGE_HITS`]/[`RECT_WII_HITS`].
2362pub(crate) const RECT_WEDGE_SHAPES: [(usize, usize); 6] =
2363 [(8, 16), (16, 8), (16, 32), (32, 16), (8, 32), (32, 8)];
2364
2365fn rect_wedge_slot(bw: usize, bh: usize) -> Option<usize> {
2366 RECT_WEDGE_SHAPES.iter().position(|&s| s == (bw, bh))
2367}
2368
2369// lane-inter16ab r5: how many COMPOUND_WEDGE / wedge-INTERINTRA blocks used a
2370// RECTANGULAR codebook row (hgtw/hltw), per shape -- the gate's proof that
2371// the rect wedge masks lifted this round actually fired, not just the square
2372// ones already counted by `WEDGE_HITS`/`WII_HITS`.
2373thread_local! {
2374 static RECT_WEDGE_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
2375 static RECT_WII_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
2376}
2377
2378/// Current value of [`RECT_WEDGE_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
2379pub(crate) fn rect_wedge_hits() -> [usize; 6] {
2380 RECT_WEDGE_HITS.with(|c| c.get())
2381}
2382
2383/// Current value of [`RECT_WII_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
2384pub(crate) fn rect_wii_hits() -> [usize; 6] {
2385 RECT_WII_HITS.with(|c| c.get())
2386}
2387
2388// lane-inter4 r4: how many 16x8/8x16 INTER LEAVES actually ran the OBMC
2389// blend -- the gate's proof that `--enable-obmc=1` reached this shape (the
2390// r3 refusal's replacement: prefilt frames are bit-exact vs an instrumented
2391// aomdec, neighbour list included).
2392thread_local! {
2393 static OBMC_RECT_LEAF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2394}
2395
2396/// Current value of [`OBMC_RECT_LEAF_HITS`].
2397pub(crate) fn obmc_rect_leaf_hits() -> usize {
2398 OBMC_RECT_LEAF_HITS.with(|c| c.get())
2399}
2400
2401// lane-obmcrec r1: how many OBMC neighbours were taken from the SECOND half of
2402// a 4-wide/4-tall (1:4 strip) chroma pair -- the case whose interp filter used
2403// to be read from the pair's FIRST mi, which is a different block and, when
2404// that half is intra, carries the `[3, 3]` "no filter" sentinel (the three
2405// 1080p 10-bit film cuts refused there). The gate's proof the shape fired.
2406thread_local! {
2407 static OBMC_PAIR_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2408}
2409
2410/// Current value of [`OBMC_PAIR_FILTER_HITS`].
2411pub(crate) fn obmc_pair_filter_hits() -> usize {
2412 OBMC_PAIR_FILTER_HITS.with(|c| c.get())
2413}
2414
2415// lane-t900 r14: how many OBMC neighbour predictions run PAST the frame edge
2416// -- libaom's `op_mi_size` is `AOMMIN(xd->width|height, mi_step)`, the block's
2417// own side, so a block overhanging the bottom/right still predicts the full
2418// neighbour strip (the destination write is what clips). We used to shrink the
2419// prediction to the visible part, which at 4 chroma rows/cols also swaps the
2420// vertical/horizontal kernel to the 4-tap one. The gate's proof the shape fired.
2421thread_local! {
2422 static OBMC_EDGE_SPAN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2423}
2424
2425/// Current value of [`OBMC_EDGE_SPAN_HITS`].
2426pub(crate) fn obmc_edge_span_hits() -> usize {
2427 OBMC_EDGE_SPAN_HITS.with(|c| c.get())
2428}
2429
2430/// Current value of [`OBMC_HITS_8`].
2431pub(crate) fn obmc_hits_8() -> usize {
2432 OBMC_HITS_8.with(|c| c.get())
2433}
2434
2435// lane-rectgate r1: how many 32x32 quadrants actually decoded a
2436// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
2437// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
2438// `VERT_B` all still fall into the generic "a partition type this encoder
2439// never writes" refusal below) -- the gate's proof that a free-partition
2440// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
2441// coincidentally never selecting one.
2442thread_local! {
2443 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
2444 const { std::cell::Cell::new(0) };
2445}
2446
2447/// Current value of [`EXTENDED_PARTITION_HITS`].
2448pub(crate) fn extended_partition_hits() -> usize {
2449 EXTENDED_PARTITION_HITS.with(|c| c.get())
2450}
2451
2452// lane-partitions r1: how many 32x32 quadrants decoded a real
2453// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
2454// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
2455// gate's proof this round's arms actually fired.
2456thread_local! {
2457 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
2458 const { std::cell::Cell::new(0) };
2459}
2460
2461/// Current value of [`RECT_PARTITION_HITS`].
2462pub(crate) fn rect_partition_hits() -> usize {
2463 RECT_PARTITION_HITS.with(|c| c.get())
2464}
2465
2466// lane-inter8 r1: how many superblocks an inter tile coded as a single
2467// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for
2468// static content, previously a named refusal).
2469thread_local! {
2470 /// lane-sb128c r1: how many 128x128 `PARTITION_NONE` roots this INTER tile
2471 /// path decoded as one whole block (its gate's own witness).
2472 pub(crate) static INTER_SB128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2473 /// 128x64 / 64x128 INTER blocks decoded at the 128 root (lane-sb128c r7).
2474 pub(crate) static INTER_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2475 pub(crate) static INTER_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2476}
2477
2478/// Current value of [`INTER_SB128_HORZ_HITS`], for a gate's before/after delta.
2479pub(crate) fn inter_sb128_horz_hits() -> usize {
2480 INTER_SB128_HORZ_HITS.with(std::cell::Cell::get)
2481}
2482
2483/// Current value of [`INTER_SB128_VERT_HITS`], for a gate's before/after delta.
2484pub(crate) fn inter_sb128_vert_hits() -> usize {
2485 INTER_SB128_VERT_HITS.with(std::cell::Cell::get)
2486}
2487
2488/// Current value of [`INTER_SB128_NONE_HITS`], for a gate's before/after delta.
2489pub fn inter_sb128_none_hits() -> usize {
2490 INTER_SB128_NONE_HITS.with(std::cell::Cell::get)
2491}
2492
2493thread_local! {
2494 /// lane-sb128c r3: how many INTRA-coded 128x128 blocks inside an INTER
2495 /// frame this decoder reconstructed (mu-chunk chroma, four TX_64X64 luma
2496 /// units) -- the gate's witness that the lifted refusal's case fired.
2497 pub(crate) static INTRA_128_IN_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2498}
2499
2500/// Current value of [`INTRA_128_IN_INTER_HITS`], for a gate's before/after delta.
2501pub fn intra_128_in_inter_hits() -> usize {
2502 INTRA_128_IN_INTER_HITS.with(std::cell::Cell::get)
2503}
2504
2505thread_local! {
2506 static INTER_SB_NONE_HITS: std::cell::Cell<usize> =
2507 const { std::cell::Cell::new(0) };
2508}
2509
2510/// Current value of [`INTER_SB_NONE_HITS`].
2511pub(crate) fn inter_sb_none_hits() -> usize {
2512 INTER_SB_NONE_HITS.with(|c| c.get())
2513}
2514
2515// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter
2516// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle
2517// path has always run that loop, so only this counter proves the newly-lifted
2518// alphabet value fired.
2519thread_local! {
2520 static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> =
2521 const { std::cell::Cell::new(0) };
2522}
2523
2524/// Current value of [`INTER_SUB16_SPLIT_HITS`].
2525pub(crate) fn inter_sub16_split_hits() -> usize {
2526 INTER_SUB16_SPLIT_HITS.with(|c| c.get())
2527}
2528
2529// lane-t900 r28: how many 16x16 inter splits reached their four 8x8 leaves
2530// while at least one reference picture was SCALED (superres) -- the counter
2531// behind the lifted "8x8 partition leaf under a scaled reference" refusal.
2532thread_local! {
2533 static SCALED_LEAF8_HITS: std::cell::Cell<usize> =
2534 const { std::cell::Cell::new(0) };
2535}
2536
2537/// Current value of [`SCALED_LEAF8_HITS`].
2538pub fn scaled_leaf8_hits() -> usize {
2539 SCALED_LEAF8_HITS.with(|c| c.get())
2540}
2541
2542// lane-t900 r28: how many sub-8x8 inter blocks (the 4x4 split and the 8x4/4x8
2543// rect pair) were predicted from a SCALED reference -- the counter behind the
2544// lifted "sub-8x8 inter block under a scaled reference" refusal.
2545thread_local! {
2546 static SCALED_SUB8_HITS: std::cell::Cell<usize> =
2547 const { std::cell::Cell::new(0) };
2548}
2549
2550/// Current value of [`SCALED_SUB8_HITS`].
2551pub fn scaled_sub8_hits() -> usize {
2552 SCALED_SUB8_HITS.with(|c| c.get())
2553}
2554
2555// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
2556// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
2557// rect coefficient reader itself fired, not just the strip-level partition
2558// symbol [`RECT_PARTITION_HITS`] already counts.
2559thread_local! {
2560 static RECT_COEFF_HITS: std::cell::Cell<usize> =
2561 const { std::cell::Cell::new(0) };
2562}
2563
2564/// Current value of [`RECT_COEFF_HITS`].
2565pub(crate) fn rect_coeff_hits() -> usize {
2566 RECT_COEFF_HITS.with(|c| c.get())
2567}
2568
2569// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`])
2570// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the
2571// charter's real-aomenc gate hard-asserts.
2572thread_local! {
2573 static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> =
2574 const { std::cell::Cell::new(0) };
2575}
2576
2577/// Current value of [`RECT_LEAF_COEFF_HITS`].
2578pub(crate) fn rect_leaf_coeff_hits() -> usize {
2579 RECT_LEAF_COEFF_HITS.with(|c| c.get())
2580}
2581
2582// lane-intrarect r1: how many intra-coded HORZ/VERT strips decoded on the
2583// INTER block path ([`decode_intra_rect_in_inter`]), per shape class --
2584// [0] the superblock-level 64x32/32x64, [1] 32x16/16x32, [2] 16x8/8x16.
2585// Every one of them was the named refusal "an intra-coded HORZ/VERT strip
2586// needs rectangular intra prediction" before this round.
2587thread_local! {
2588 static INTRA_RECT_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
2589 const { std::cell::Cell::new([0; 3]) };
2590}
2591
2592/// Current value of [`INTRA_RECT_IN_INTER_HITS`] for one shape class
2593/// (0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16).
2594pub(crate) fn intra_rect_strip_in_inter_hits(class: usize) -> usize {
2595 INTRA_RECT_IN_INTER_HITS.with(|c| c.get()[class])
2596}
2597
2598// lane-rect64port r1 (ported by hand from lane-intra64split 5ffbaf3): coded
2599// (non-skip) 64-level HORZ/VERT intra strips whose luma transform is the
2600// un-split TX_64X32/TX_32X64 -- the corner-cropped 32x32 coefficient read of
2601// [`decode_rect_split`], the shape both 10-bit 3840x1608 film cuts stop on.
2602// Split by ORIENTATION (index 0 = 64x32 wide / HORZ, 1 = 32x64 tall / VERT):
2603// a single counter cannot tell an axis swap from a working arm
2604// (class [[scan-weights-cross-axis]]), so the gate asserts both cells.
2605thread_local! {
2606 static RECT64_CORNER_TU_HITS: std::cell::Cell<[usize; 2]> =
2607 const { std::cell::Cell::new([0; 2]) };
2608}
2609
2610/// Current value of [`RECT64_CORNER_TU_HITS`] for one orientation
2611/// (0 = 64x32, 1 = 32x64).
2612pub(crate) fn rect64_corner_tu_hits(orient: usize) -> usize {
2613 RECT64_CORNER_TU_HITS.with(|c| c.get()[orient])
2614}
2615
2616// lane-intrasplit r1: intra HORZ/VERT strips inside an INTER frame whose luma
2617// transform is SPLIT, bucketed by the read `tx_depth` (index 1 and 2; index 0
2618// is never incremented) -- the gate's proof that the lifted path ran per depth.
2619thread_local! {
2620 static INTRA_RECT_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 3]> =
2621 const { std::cell::Cell::new([0; 3]) };
2622}
2623
2624// lane-t900 r21: rect intra strips inside an inter frame that read the
2625// screen-content palette syntax (`allow_screen_content_tools` set and the
2626// strip's own shape admitted by `palette_bsize_ctx_wh`) -- the site a blanket
2627// refusal used to guard, so this counter is what keeps its witness gate
2628// non-vacuous.
2629thread_local! {
2630 static INTRA_RECT_IN_INTER_SCREEN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2631}
2632
2633/// Current value of [`INTRA_RECT_IN_INTER_SCREEN_HITS`].
2634pub(crate) fn intra_rect_in_inter_screen_hits() -> usize {
2635 INTRA_RECT_IN_INTER_SCREEN_HITS.with(std::cell::Cell::get)
2636}
2637
2638/// Resets [`INTRA_RECT_IN_INTER_SCREEN_HITS`] before a decode.
2639pub(crate) fn reset_intra_rect_in_inter_screen_hits() {
2640 INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(0));
2641}
2642
2643/// Current value of [`INTRA_RECT_IN_INTER_SPLIT_TX_HITS`], indexed by tx depth.
2644pub(crate) fn intra_rect_in_inter_split_tx_hits() -> [usize; 3] {
2645 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
2646}
2647
2648// lane-midcut r2: rect intra blocks inside an inter frame whose `tx_depth` CDF
2649// ROW moved when libaom's inter-neighbour override was applied -- i.e. exactly
2650// the blocks the key frame's deblock-grid approximation used to mis-read.
2651thread_local! {
2652 static INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS: std::cell::Cell<usize> =
2653 const { std::cell::Cell::new(0) };
2654}
2655
2656/// Current value of [`INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS`].
2657pub(crate) fn intra_rect_in_inter_txctx_override_hits() -> usize {
2658 INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS.with(std::cell::Cell::get)
2659}
2660
2661// lane-intra14 r1: how many intra-coded 1:4 strips decoded on the INTER
2662// block path, per shape -- [0] 64x16, [1] 16x64, [2] 32x8, [3] 8x32. Every
2663// one of them was the named refusal "an intra-coded 1:4 (or other non-2:1)
2664// rect strip on the inter block path" before this round.
2665thread_local! {
2666 static INTRA_RECT4_IN_INTER_HITS: std::cell::Cell<[usize; 4]> =
2667 const { std::cell::Cell::new([0; 4]) };
2668}
2669
2670/// Current value of [`INTRA_RECT4_IN_INTER_HITS`] for one shape
2671/// (0 = 64x16, 1 = 16x64, 2 = 32x8, 3 = 8x32).
2672pub(crate) fn intra_rect4_strip_in_inter_hits(shape: usize) -> usize {
2673 INTRA_RECT4_IN_INTER_HITS.with(|c| c.get()[shape])
2674}
2675
2676// lane-intra14 r1: set while an INTRA block of an INTER frame is decoded
2677// through one of the key-frame rect readers ([`decode_block_rect4`],
2678// [`decode_block_rect64`]). `Some((size_group, skip))` tells
2679// [`read_intra_mode_rect`] that (a) `skip`/segment id/cdef/delta-q were
2680// already read by [`decode_inter_block`] and (b) the luma mode comes off
2681// `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`,
2682// decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair.
2683thread_local! {
2684 static INTRA_IN_INTER_MODE: std::cell::Cell<Option<(usize, bool)>> =
2685 const { std::cell::Cell::new(None) };
2686}
2687
2688// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
2689// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
2690// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16
2691// slot -- i.e. how often the r5 defect would have picked the wrong CDF row.
2692thread_local! {
2693 static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
2694 const { std::cell::Cell::new(0) };
2695}
2696
2697/// Current value of [`MODE_MI_OVERRIDE_HITS`].
2698pub(crate) fn mode_mi_override_hits() -> usize {
2699 MODE_MI_OVERRIDE_HITS.with(|c| c.get())
2700}
2701
2702// lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a
2703// TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a
2704// mode from the previous tile, where libaom's `up_available`/`left_available`
2705// make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams:
2706// `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode`
2707// per superblock row in `start_row`, so the luma fallback cannot leak the way
2708// lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is
2709// the invariant that makes the coarse fallback safe.
2710thread_local! {
2711 static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell<usize> =
2712 const { std::cell::Cell::new(0) };
2713}
2714
2715/// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`].
2716pub(crate) fn mode_tile_edge_coarse_leaks() -> usize {
2717 MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get())
2718}
2719
2720// lane-cfl r1: how many times a chroma intra-edge filter-type read
2721// (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the
2722// mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the
2723// r1 defect would have filtered a chroma edge with the wrong strength.
2724thread_local! {
2725 static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
2726 const { std::cell::Cell::new(0) };
2727}
2728
2729/// Current value of [`UV_MODE_MI_OVERRIDE_HITS`].
2730pub(crate) fn uv_mode_mi_override_hits() -> usize {
2731 UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get())
2732}
2733
2734// lane-t900 r12: how many chroma edge-filter-type reads took their above/left
2735// `uv_mode` from the mi GRID where the one-slot-per-column map would have
2736// answered differently -- the sub-8x8 pair case where the pair's own first
2737// half had already overwritten the column slot the chroma-ref half reads.
2738thread_local! {
2739 static UV_MODE_GRID_OVERRIDE_HITS: std::cell::Cell<usize> =
2740 const { std::cell::Cell::new(0) };
2741}
2742
2743/// Current value of [`UV_MODE_GRID_OVERRIDE_HITS`].
2744pub fn uv_mode_grid_override_hits() -> usize {
2745 UV_MODE_GRID_OVERRIDE_HITS.with(|c| c.get())
2746}
2747
2748// lane-t900 r8: how many intra edge-filter-type reads (luma + chroma) the
2749// INTER neighbour stamp saved: the coarse SUB band still held a SMOOTH mode
2750// from an earlier block in that pixel row/column while the mi-exact map --
2751// which an inter block only started writing this round -- correctly says the
2752// neighbour is not smooth (libaom `is_smooth`: an inter neighbour's `mode` is
2753// an INTER mode, and its `uv_mode` "is not set for inter blocks").
2754thread_local! {
2755 static INTER_NEIGHBOUR_NOT_SMOOTH_HITS: std::cell::Cell<usize> =
2756 const { std::cell::Cell::new(0) };
2757}
2758
2759/// Current value of [`INTER_NEIGHBOUR_NOT_SMOOTH_HITS`].
2760pub(crate) fn inter_neighbour_not_smooth_hits() -> usize {
2761 INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|c| c.get())
2762}
2763
2764// lane-mtfix r1: how many times a chroma intra-edge filter-type read was
2765// suppressed at a TILE edge that is not a frame edge -- the above/left
2766// `uv_mode` neighbour of a block on a tile's first mi row/column lives in
2767// another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The
2768// coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per
2769// tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile
2770// above would decide this tile's chroma edge filter strength.
2771thread_local! {
2772 static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell<usize> =
2773 const { std::cell::Cell::new(0) };
2774}
2775
2776/// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`].
2777pub(crate) fn uv_tile_edge_suppressed_hits() -> usize {
2778 UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get())
2779}
2780
2781// lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs`
2782// read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block
2783// shapes the r1 chroma defect showed up on.
2784thread_local! {
2785 static CFL_BLOCK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2786 static UV_ANGLE_DELTA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2787}
2788
2789/// Current value of [`CFL_BLOCK_HITS`].
2790pub(crate) fn cfl_block_hits() -> usize {
2791 CFL_BLOCK_HITS.with(|c| c.get())
2792}
2793
2794/// Current value of [`UV_ANGLE_DELTA_HITS`].
2795pub(crate) fn uv_angle_delta_hits() -> usize {
2796 UV_ANGLE_DELTA_HITS.with(|c| c.get())
2797}
2798
2799// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
2800// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
2801// gate's proof this round's arms actually reached a real block, not just
2802// that `partition_w64` read one of those two symbol values.
2803thread_local! {
2804 static SB_RECT_HITS: std::cell::Cell<usize> =
2805 const { std::cell::Cell::new(0) };
2806}
2807
2808/// Current value of [`SB_RECT_HITS`].
2809// lane-hgkf r1: the frame-edge partition bit, one level each. Slot 0 = a
2810// 64-level gathered edge bit read as HORZ/VERT, 1 = the same bit read as
2811// SPLIT, 2/3 = the 32-level pair. A gate asserting slot 0 or 2 proves the
2812// non-SPLIT edge arm actually decoded (before this round the bit was read and
2813// thrown away, so that arm was unreachable).
2814thread_local! {
2815 static EDGE_PART_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
2816}
2817
2818/// Current value of [`EDGE_PART_HITS`].
2819pub(crate) fn edge_part_hits() -> [usize; 4] {
2820 EDGE_PART_HITS.with(|c| c.get())
2821}
2822
2823/// Reset [`EDGE_PART_HITS`] (a gate counts one stream at a time).
2824pub(crate) fn reset_edge_part_hits() {
2825 EDGE_PART_HITS.with(|c| c.set([0; 4]));
2826}
2827
2828fn bump_edge_part(slot: usize) {
2829 EDGE_PART_HITS.with(|c| {
2830 let mut h = c.get();
2831 h[slot] += 1;
2832 c.set(h);
2833 });
2834}
2835
2836pub(crate) fn sb_rect_hits() -> usize {
2837 SB_RECT_HITS.with(|c| c.get())
2838}
2839
2840// lane-golomb r2: the 32x32-level FRAME-EDGE partition. Slot 0/1 = the
2841// gathered edge bit read as 0 (HORZ/VERT) / 1 (SPLIT); slot 2 = a 32-level
2842// PARTITION_HORZ decoded with `has_rows32 == false` (only the top 32x16 half
2843// is coded), slot 3 = a PARTITION_VERT with `has_cols32 == false`. Both tile
2844// paths (intra and inter) feed the same counter.
2845//
2846// lane-golomb r3: slots 4..7 are the same four facts one level up, at the
2847// SUPERBLOCK (64x64) edge -- 4/5 = the gathered 64-level bit read as
2848// HORZ/VERT / SPLIT, 6 = a 64x32 bottom-edge strip decoded with
2849// `has_rows == false`, 7 = a 32x64 right-edge strip. Real aomenc answers a
2850// bottom-edge superblock with the 64-level HORZ (measured: 192x80 flat-band,
2851// every SB of the last row), so the 32-level slots stay 0 on that content and
2852// only these prove the arm fired.
2853thread_local! {
2854 static EDGE32_HITS: std::cell::Cell<[usize; 8]> =
2855 const { std::cell::Cell::new([0; 8]) };
2856}
2857
2858/// Current value of [`EDGE32_HITS`].
2859pub(crate) fn edge32_hits() -> [usize; 8] {
2860 EDGE32_HITS.with(|c| c.get())
2861}
2862
2863/// [`bump_edge32`] of `base + bit`, returning the bit -- the gathered edge
2864/// reads are `if`-conditions, so the counter has to ride the expression.
2865fn bump_edge32_bit(base: usize, bit: usize) -> usize {
2866 bump_edge32(base + bit.min(1));
2867 bit
2868}
2869
2870fn bump_edge32(slot: usize) {
2871 EDGE32_HITS.with(|c| {
2872 let mut h = c.get();
2873 h[slot] += 1;
2874 c.set(h)
2875 });
2876}
2877
2878// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/
2879// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64
2880// strip) fired. Real aomenc picks these at 64 even with
2881// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is
2882// the counter the gate hard-asserts.
2883thread_local! {
2884 static SB_AB_HITS: std::cell::Cell<[usize; 4]> =
2885 const { std::cell::Cell::new([0; 4]) };
2886}
2887
2888/// Current value of [`SB_AB_HITS`], summed over the four arms.
2889pub(crate) fn sb_ab_hits() -> usize {
2890 SB_AB_HITS.with(|c| c.get().iter().sum())
2891}
2892
2893/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`,
2894/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a
2895/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as
2896/// proof of all four.
2897pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] {
2898 SB_AB_HITS.with(std::cell::Cell::get)
2899}
2900
2901// lane-tx64x16: the two 1:4 superblock arms, counted per orientation --
2902// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64
2903// strips). Two counters, not one, because a gate that only proved "some 1:4
2904// strip fired" would pass on a stream that never coded the other axis, and
2905// every scan/context table this round added comes in a transposed pair.
2906thread_local! {
2907 static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2908 static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2909}
2910
2911/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded).
2912pub(crate) fn sb_rect4_horz_hits() -> usize {
2913 SB_RECT4_HORZ_HITS.with(|c| c.get())
2914}
2915
2916/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded).
2917pub(crate) fn sb_rect4_vert_hits() -> usize {
2918 SB_RECT4_VERT_HITS.with(|c| c.get())
2919}
2920
2921// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation --
2922// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32
2923// strips), the arms the ReelB mid-film extract stops at.
2924thread_local! {
2925 static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2926 static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2927 /// lane-inter4 r1: the INTER-frame twins of the two counters above --
2928 /// four 32x8 / 8x32 inter strips of a 32x32-level `PARTITION_HORZ_4` /
2929 /// `PARTITION_VERT_4`.
2930 static RECT4_32_HORZ_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2931 static RECT4_32_VERT_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2932 /// lane-inter4 r1: superblock-level inter `PARTITION_HORZ`/`PARTITION_VERT`
2933 /// strips (64x32 / 32x64) and their 1:4 pair (64x16 / 16x64).
2934 static INTER_SB_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2935 static INTER_SB_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2936 static INTER_SB_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2937 static INTER_SB_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2938}
2939
2940/// How many 32x32-level 1:4 strips actually read coefficients (non-skip):
2941/// a gate that only counted strips would pass on an all-skip stream, which
2942/// exercises none of the new scan/context tables.
2943thread_local! {
2944 static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2945}
2946
2947// lane-rectsplitx r1: 1:4 strips (32x8/8x32/64x16/16x64) decoded through the
2948// per-transform-unit split path, split by tx depth -- depth 1 is a 2:1 RECT
2949// unit (TX_16X8/TX_32X16), depth 2 a square one, and the two INTERLEAVE in
2950// every real stream, so a gate must prove both fired. `SUB16_SPLIT_HITS`
2951// counts the same for a 16x8/8x16 strip below 16x16.
2952thread_local! {
2953 static RECT4_SPLIT_DEPTH1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2954 static RECT4_SPLIT_DEPTH2_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2955 static SUB16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2956}
2957
2958/// Current values of `RECT4_SPLIT_DEPTH1_HITS` / `RECT4_SPLIT_DEPTH2_HITS`.
2959pub(crate) fn rect4_split_depth_hits() -> (usize, usize) {
2960 (
2961 RECT4_SPLIT_DEPTH1_HITS.with(|c| c.get()),
2962 RECT4_SPLIT_DEPTH2_HITS.with(|c| c.get()),
2963 )
2964}
2965
2966/// Current value of `SUB16_SPLIT_HITS`.
2967pub(crate) fn sub16_split_hits() -> usize {
2968 SUB16_SPLIT_HITS.with(|c| c.get())
2969}
2970
2971// lane-frame36 r2: superblock-level strips ([`decode_block_rect64`]) whose
2972// luma transform is SPLIT and which therefore leave through that fn's early
2973// return -- the arm that published no `TXFM_CONTEXT` band until this round.
2974thread_local! {
2975 static RECT64_SPLIT_TXFM_PUBLISH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2976}
2977
2978/// Current value of `RECT64_SPLIT_TXFM_PUBLISH_HITS`.
2979pub(crate) fn rect64_split_txfm_publish_hits() -> usize {
2980 RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.get())
2981}
2982
2983/// Current value of `RECT4_COEFF_HITS`.
2984pub(crate) fn rect4_coeff_hits() -> usize {
2985 RECT4_COEFF_HITS.with(|c| c.get())
2986}
2987
2988// lane-sbab r1: how many superblock-level (64x64) AB partitions fired IN AN
2989// INTER frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`,
2990// `_VERT_B` order (the intra-frame counterpart is `SB_AB_HITS`). Each arm is
2991// two 32x32 inter squares plus one true 64x32/32x64 inter strip; the gate
2992// asserts the arms it proves separately so a run whose RD only picked one
2993// cannot pass as proof of the others.
2994thread_local! {
2995 static SB_AB_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
2996}
2997
2998/// [`SB_AB_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 64x64 in an
2999/// inter frame).
3000pub fn sb_ab_inter_hits_by_arm() -> [usize; 4] {
3001 SB_AB_INTER_HITS.with(std::cell::Cell::get)
3002}
3003
3004// lane-inter16ab r1: how many 16x16-level AB partitions fired IN AN INTER
3005// frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B`
3006// order (the intra-frame counterpart is `AB16_HITS`). Each arm is two 8x8
3007// inter leaves (`decode_inter_block8`) plus one true 16x8/8x16 inter strip
3008// (`decode_inter_block` with `write_w`/`write_h`); the gate asserts every
3009// arm separately so a run whose RD only picked one cannot pass as proof of
3010// four.
3011thread_local! {
3012 static AB16_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
3013}
3014
3015/// [`AB16_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16 in an
3016/// inter frame).
3017pub fn ab16_inter_hits_by_arm() -> [usize; 4] {
3018 AB16_INTER_HITS.with(std::cell::Cell::get)
3019}
3020
3021// lane-inter16ab r2: the 16x16-level 1:4 pair as INTER blocks -- four 16x4
3022// (`PARTITION_HORZ_4`) or 4x16 (`PARTITION_VERT_4`) strips. `CHROMA_PAIRS`
3023// counts the odd strips that close a 4:2:0 chroma pair
3024// (`is_chroma_reference`, av1_common_int.h:1454: bh == 1 mi => odd mi_row),
3025// `SUB8_PIECES` the pair chroma blocks whose TOP (LEFT) half was built from
3026// the PREVIOUS strip's own mv/ref/filters -- libaom
3027// `build_inter_predictors_sub8x8` (reconinter_template.inc:87-160), reached
3028// through `is_sub8x8_inter` (same file, :54).
3029thread_local! {
3030 static INTER16_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3031 static INTER16_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3032 static INTER16_CHROMA_PAIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3033 static INTER16_SUB8_PIECE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3034}
3035
3036// lane-intra16x4: INTRA-coded strips of an inter 16x16-level 1:4 partition --
3037// [0] 16x4, [1] 4x16, [2] the odd (chroma-reference) ones, which carry the
3038// pair's single 8x4 (4x8) chroma unit for BOTH strips.
3039thread_local! {
3040 static INTRA16X4_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
3041 const { std::cell::Cell::new([0; 3]) };
3042}
3043
3044/// `(intra 16x4 strips, intra 4x16 strips, of which chroma-reference)` decoded
3045/// inside an INTER 16x16-level 1:4 partition (lane-intra16x4).
3046pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) {
3047 let v = INTRA16X4_IN_INTER_HITS.with(std::cell::Cell::get);
3048 (v[0], v[1], v[2])
3049}
3050
3051/// Current values of the inter 16x16-level 1:4 counters: `(16x4 strips, 4x16
3052/// strips, chroma pairs closed, chroma pairs built from two different
3053/// strips' motion vectors)`.
3054pub fn inter16_rect4_counters() -> (usize, usize, usize, usize) {
3055 (
3056 INTER16_HORZ4_HITS.with(std::cell::Cell::get),
3057 INTER16_VERT4_HITS.with(std::cell::Cell::get),
3058 INTER16_CHROMA_PAIR_HITS.with(std::cell::Cell::get),
3059 INTER16_SUB8_PIECE_HITS.with(std::cell::Cell::get),
3060 )
3061}
3062
3063/// One 16x4 / 4x16 inter strip's chroma situation, handed to
3064/// [`decode_inter_block`] out of band (the same one-shot thread-local idiom
3065/// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites
3066/// that all mean "an ordinary block, chroma of its own".
3067#[derive(Clone, Copy)]
3068struct InterStripChroma {
3069 /// `is_chroma_reference` for this strip: false on strips 0 and 2, which
3070 /// read and reconstruct NO chroma at all.
3071 has_chroma: bool,
3072 /// `PARTITION_HORZ_4` (16x4 strips) rather than `PARTITION_VERT_4`.
3073 horz: bool,
3074 /// The mi position of the EVEN strip of this pair -- `setup_pred_plane`'s
3075 /// `if (ss_y && (mi_row & 1) && mi_size_high[bsize] == 1) mi_row -= 1`,
3076 /// i.e. the origin of the 8x4 (4x8) chroma transform.
3077 pair_mi: (usize, usize),
3078 /// The previous (even) strip's single-reference MC parameters, `None`
3079 /// when it was intra or compound -- `is_sub8x8_inter` then returns false
3080 /// and the whole chroma block is predicted from THIS strip's mv.
3081 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
3082}
3083
3084thread_local! {
3085 static INTER_STRIP_CHROMA: std::cell::Cell<Option<InterStripChroma>> =
3086 const { std::cell::Cell::new(None) };
3087 /// The single-reference MC parameters of the inter block that decoded
3088 /// last -- read by the next 1:4 strip to build its pair's chroma.
3089 static INTER_LAST_MC: std::cell::Cell<
3090 Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
3091 > = const { std::cell::Cell::new(None) };
3092}
3093
3094fn bump_ab16_inter(arm: usize) {
3095 AB16_INTER_HITS.with(|c| {
3096 let mut v = c.get();
3097 v[arm] += 1;
3098 c.set(v);
3099 });
3100}
3101
3102// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or
3103// 4x16 (`PARTITION_VERT_4`) strips, `CHROMA` counting the odd strips that
3104// close a 4:2:0 chroma pair and `COEFF` the strips with a coded residual.
3105thread_local! {
3106 static RECT4_16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3107 static RECT4_16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3108 static RECT4_16_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3109 static RECT4_16_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3110 static RECT4_16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3111 /// lane-kf1200: pairs whose chroma edge-filter type read from the PAIR's
3112 /// base mi differs from what the strip's own (odd) mi would have said --
3113 /// the shape that made 4 chroma samples of the ReelB `-ss 1200`
3114 /// key frame miss by 1. Zero here means a gate never exercised the fix.
3115 static RECT4_16_UV_PAIR_FILT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3116 /// lane-kf1200 r2: sub-8x8 chroma blocks that are `skip_txfm` AND
3117 /// `UV_CFL_PRED` -- the arm that used to drop the CfL alpha entirely.
3118 static SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3119}
3120
3121/// How many skipped sub-8x8 chroma blocks carried a CfL alpha (the shape
3122/// that reconstructed as flat DC before lane-kf1200 r2).
3123pub fn skip_cfl_hits() -> usize {
3124 SKIP_CFL_HITS.with(|c| c.get())
3125}
3126
3127/// How many 16x4/4x16 chroma pairs took a different `intra_edge_filter_type`
3128/// from the pair's base mi than the strip's own mi would have given.
3129pub fn rect4_16_uv_pair_filt_hits() -> usize {
3130 RECT4_16_UV_PAIR_FILT_HITS.with(|c| c.get())
3131}
3132
3133// lane-reelckf r1: the two chroma defects ReelC's key frames exposed --
3134// CHROMA_SKIP_CFL counts skipped intra blocks whose chroma is `UV_CFL_PRED`
3135// (prediction still runs, libaom `predict_and_reconstruct_intra_block`), and
3136// RECT4_16_CHROMA_DIR counts 1:4 chroma pairs predicted directionally (whose
3137// intra-edge filter type must come from the chroma-reference position).
3138thread_local! {
3139 static CHROMA_SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3140 static RECT4_16_CHROMA_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3141}
3142
3143/// `(skipped UV_CFL_PRED blocks, directional 1:4 chroma pairs)` -- lane-reelckf.
3144pub fn reelc_chroma_counters() -> (usize, usize) {
3145 (
3146 CHROMA_SKIP_CFL_HITS.with(|c| c.get()),
3147 RECT4_16_CHROMA_DIR_HITS.with(|c| c.get()),
3148 )
3149}
3150
3151/// Current values of the 16x16-level 1:4 counters: `(16x4 strips, 4x16
3152/// strips, chroma-reference strips, strips with a coded residual, strips
3153/// whose luma transform is split)`.
3154pub fn rect4_16_counters() -> (usize, usize, usize, usize, usize) {
3155 (
3156 RECT4_16_HORZ_HITS.with(|c| c.get()),
3157 RECT4_16_VERT_HITS.with(|c| c.get()),
3158 RECT4_16_CHROMA_HITS.with(|c| c.get()),
3159 RECT4_16_COEFF_HITS.with(|c| c.get()),
3160 RECT4_16_SPLIT_HITS.with(|c| c.get()),
3161 )
3162}
3163
3164/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded).
3165pub(crate) fn rect4_32_horz_hits() -> usize {
3166 RECT4_32_HORZ_HITS.with(|c| c.get())
3167}
3168
3169/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded).
3170pub(crate) fn rect4_32_vert_hits() -> usize {
3171 RECT4_32_VERT_HITS.with(|c| c.get())
3172}
3173
3174/// Current value of `RECT4_32_HORZ_INTER_HITS` (32x8 inter strips decoded).
3175pub(crate) fn rect4_32_horz_inter_hits() -> usize {
3176 RECT4_32_HORZ_INTER_HITS.with(|c| c.get())
3177}
3178
3179/// Current value of `RECT4_32_VERT_INTER_HITS` (8x32 inter strips decoded).
3180pub(crate) fn rect4_32_vert_inter_hits() -> usize {
3181 RECT4_32_VERT_INTER_HITS.with(|c| c.get())
3182}
3183
3184/// Current value of `INTER_SB_HORZ_HITS` (64x32 inter strips decoded).
3185pub(crate) fn inter_sb_horz_hits() -> usize {
3186 INTER_SB_HORZ_HITS.with(|c| c.get())
3187}
3188
3189/// Current value of `INTER_SB_VERT_HITS` (32x64 inter strips decoded).
3190pub(crate) fn inter_sb_vert_hits() -> usize {
3191 INTER_SB_VERT_HITS.with(|c| c.get())
3192}
3193
3194/// Current value of `INTER_SB_HORZ4_HITS` (64x16 inter strips decoded).
3195pub(crate) fn inter_sb_horz4_hits() -> usize {
3196 INTER_SB_HORZ4_HITS.with(|c| c.get())
3197}
3198
3199/// Current value of `INTER_SB_VERT4_HITS` (16x64 inter strips decoded).
3200pub(crate) fn inter_sb_vert4_hits() -> usize {
3201 INTER_SB_VERT4_HITS.with(|c| c.get())
3202}
3203
3204// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
3205// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
3206// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
3207// just inert-compiled. Zero forever on a passing gate means that gate's
3208// stream never carries `delta_q_present=1` through a rect64 block.
3209thread_local! {
3210 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
3211 const { std::cell::Cell::new(0) };
3212}
3213
3214/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
3215pub(crate) fn rect64_qidx_drift_hits() -> usize {
3216 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
3217}
3218
3219// lane-partab r1: how many 32x32 quadrants decoded an AB partition
3220// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
3221// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
3222// free-partition gate's proof this round's arms actually fired.
3223thread_local! {
3224 static PARTAB_HITS: std::cell::Cell<usize> =
3225 const { std::cell::Cell::new(0) };
3226}
3227
3228/// Current value of [`PARTAB_HITS`].
3229pub(crate) fn partab_hits() -> usize {
3230 PARTAB_HITS.with(|c| c.get())
3231}
3232
3233// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm,
3234// one counter per arm rather than one shared total -- the gate hard-asserts
3235// each of these individually nonzero so a recipe that only ever fires
3236// HORZ_A can't silently stand in for the whole set.
3237thread_local! {
3238 static INTRA_HORZ_A_HITS: std::cell::Cell<usize> =
3239 const { std::cell::Cell::new(0) };
3240 static INTRA_HORZ_B_HITS: std::cell::Cell<usize> =
3241 const { std::cell::Cell::new(0) };
3242 static INTRA_VERT_A_HITS: std::cell::Cell<usize> =
3243 const { std::cell::Cell::new(0) };
3244 static INTRA_VERT_B_HITS: std::cell::Cell<usize> =
3245 const { std::cell::Cell::new(0) };
3246}
3247
3248/// Current value of [`INTRA_HORZ_A_HITS`].
3249pub(crate) fn intra_horz_a_hits() -> usize {
3250 INTRA_HORZ_A_HITS.with(|c| c.get())
3251}
3252/// Current value of [`INTRA_HORZ_B_HITS`].
3253pub(crate) fn intra_horz_b_hits() -> usize {
3254 INTRA_HORZ_B_HITS.with(|c| c.get())
3255}
3256/// Current value of [`INTRA_VERT_A_HITS`].
3257pub(crate) fn intra_vert_a_hits() -> usize {
3258 INTRA_VERT_A_HITS.with(|c| c.get())
3259}
3260/// Current value of [`INTRA_VERT_B_HITS`].
3261pub(crate) fn intra_vert_b_hits() -> usize {
3262 INTRA_VERT_B_HITS.with(|c| c.get())
3263}
3264
3265// How many [`read_inter_compound_mode`] reads actually happened
3266// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
3267// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
3268// mvstack build), not just that `comp_mode` fired. Still refused right
3269// after (no MV assignment or MC wired), so this only counts attempted
3270// reads.
3271thread_local! {
3272 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
3273 const { std::cell::Cell::new(0) };
3274}
3275
3276/// Current value of [`COMPOUND_MODE_HITS`].
3277pub(crate) fn compound_mode_hits() -> usize {
3278 COMPOUND_MODE_HITS.with(|c| c.get())
3279}
3280
3281/// How many query blocks folded in at least one temporal MV candidate
3282/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
3283/// temporal-MV gate's own firing counter (lane-av1tmvp).
3284///
3285/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
3286/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
3287/// this file (`decode_inter_block`) still passes `tpl: None` -- this
3288/// counter compiles and the projection math it counts is unit-tested
3289/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
3290/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
3291/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
3292/// against any real stream today. See the module doc on
3293/// `crate::motion_field` and this crate's ledger for the remaining wiring.
3294pub(crate) fn tmv_hits() -> usize {
3295 crate::mvstack::tmv_hits()
3296}
3297
3298/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
3299/// produced on this thread, the 10-bit inter gate's firing proof.
3300pub(crate) fn inter_pred_hits() -> usize {
3301 crate::mc::inter_pred_hits()
3302}
3303
3304/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
3305/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
3306/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
3307/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
3308/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
3309/// needs to turn a query block's own resolved `ref_frame` into
3310/// `TplArgs::cur_offset_0` (spec 7.9.3).
3311pub(crate) struct TplFrameArgs<'a> {
3312 pub field: &'a crate::motion_field::TplField,
3313 pub order_hint_bits: u32,
3314 pub order_hint: u32,
3315 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
3316 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
3317 /// frame's own `ref_frame_idx` names for each single reference.
3318 pub ref_order_hints: [u32; 7],
3319}
3320
3321/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
3322/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
3323/// decoded `grid`: every 4x4 unit an inter block covers reads the same
3324/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
3325/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
3326/// exact — every block this crate ever codes is at least 8x8, so no 8x8
3327/// cell straddles two different blocks' values.
3328pub(crate) fn build_motion_field(
3329 grid: &MiGrid,
3330 mi_cols: usize,
3331 mi_rows: usize,
3332 order_hint: u32,
3333 order_hint_bits: u32,
3334 ref_order_hints: [u32; 7],
3335) -> crate::motion_field::MotionField {
3336 let mut field =
3337 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false);
3338 // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference
3339 // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other
3340 // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block
3341 // referencing one stores only its OTHER side's mv. With
3342 // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and
3343 // nothing is skipped.
3344 let other_side = |rf: i8| -> bool {
3345 if order_hint_bits == 0 {
3346 return false;
3347 }
3348 let oh = ref_order_hints[(rf - LAST_FRAME) as usize];
3349 crate::motion_field::get_relative_dist(order_hint_bits, oh, order_hint) > 0
3350 || oh == order_hint
3351 };
3352 // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is
3353 // capped at 12 bits per component; a longer one is not stored at all.
3354 const REFMVS_LIMIT: i32 = (1 << 12) - 1;
3355 for row in 0..mi_rows {
3356 for col in 0..mi_cols {
3357 let Some(info) = grid.get_frame(row, col) else {
3358 continue;
3359 };
3360 // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and
3361 // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`),
3362 // so an intra block -- or an inter block whose every slot is on the
3363 // other side / over the limit -- wipes what an earlier block wrote
3364 // into the same 8x8 cell (only reachable from sub-8x8 leaves, which
3365 // share a cell).
3366 if !info.is_inter {
3367 field.set(row, col, None);
3368 continue;
3369 }
3370 // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST
3371 // qualifying one wins -- a compound block stores its second
3372 // reference's mv, never its first (unless the second is on the
3373 // other side or over the limit). Storing slot 0 unconditionally
3374 // put the wrong (mv, ref_frame_offset) pair in every compound
3375 // block's cell, which a later frame's temporal candidate then
3376 // projected with the wrong reference distance.
3377 let mut saved: Option<crate::motion_field::SavedMv> = None;
3378 for (rf, mv) in [
3379 (info.ref_frame, Some(info.mv)),
3380 (info.ref_frame1.unwrap_or(0), info.mv1),
3381 ] {
3382 let (Some(mv), true) = (mv, rf > 0) else {
3383 continue;
3384 };
3385 if other_side(rf) {
3386 continue;
3387 }
3388 if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT {
3389 continue;
3390 }
3391 saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf });
3392 }
3393 field.set(row, col, saved);
3394 }
3395 }
3396 if crate::envflags::env_flag!("EC_TRACE_TPL") {
3397 eprintln!("EC_TPL_SAVED oh={order_hint}");
3398 for (r, row) in field.occupancy().iter().enumerate() {
3399 eprintln!("EC_TPL_SAVED r{r} {row}");
3400 }
3401 }
3402 field
3403}
3404
3405/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
3406/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
3407pub(crate) fn ref_hits(ref_frame: i8) -> usize {
3408 let c = match ref_frame {
3409 LAST2_FRAME => &LAST2_HITS,
3410 LAST3_FRAME => &LAST3_HITS,
3411 GOLDEN_FRAME => &GOLDEN_HITS,
3412 BWDREF_FRAME => &BWDREF_HITS,
3413 ALTREF2_FRAME => &ALTREF2_HITS,
3414 ALTREF_FRAME => &ALTREF_HITS,
3415 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
3416 };
3417 c.with(|v| v.get())
3418}
3419
3420thread_local! {
3421 /// The sequence header's `enable_intra_edge_filter`, set once per
3422 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
3423 /// own read of it, kept off the call stack (see that function's own doc
3424 /// comment for why) rather than threaded through every `read_plane`/
3425 /// `decode_block`/`decode_leaf8` call between here and there.
3426 static ENABLE_EDGE_FILTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3427}
3428
3429/// Set [`ENABLE_EDGE_FILTER`] for this thread.
3430///
3431/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
3432/// never did -- so an inter frame's intra blocks read whatever value the last
3433/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
3434/// harmless (its own key frame sets it first), but a caller that decodes an
3435/// inter frame directly, or a test harness running several streams on one
3436/// thread, inherits a foreign sequence's bit: decode stops being a pure
3437/// function of the bitstream. `decode_stream` now calls this once per stream
3438/// from the sequence header, which covers every frame including inter ones.
3439pub(crate) fn set_enable_edge_filter(value: bool) {
3440 ENABLE_EDGE_FILTER.with(|f| f.set(value));
3441}
3442
3443/// Current value of [`ANGLE_DELTA_HITS`].
3444pub(crate) fn angle_delta_hits() -> usize {
3445 ANGLE_DELTA_HITS.with(|c| c.get())
3446}
3447
3448/// Current value of [`TX_CLASS1_HITS`].
3449pub(crate) fn tx_class1_hits() -> usize {
3450 TX_CLASS1_HITS.with(|c| c.get())
3451}
3452
3453// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent
3454// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion
3455// bottom) this thread's decode actually reconstructed -- the same
3456// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream
3457// genuinely exercised the sub-8x8 leaf path rather than every attempt
3458// coincidentally landing on `PARTITION_NONE`.
3459thread_local! {
3460 static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3461 /// How many 8x8 groups an INTER frame split into four BLOCK_4X4 inter
3462 /// sub-blocks (lane-intersub8).
3463 static SUB8_INTER_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3464 /// How many 8x8 groups an INTER frame split into two rectangular sub-8x8
3465 /// inter leaves (lane-intersub8 r3), indexed `[0] = HORZ` (two BLOCK_8X4),
3466 /// `[1] = VERT` (two BLOCK_4X8).
3467 static SUB8_INTER_RECT_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
3468 /// lane-sub8intra: INTRA leaves decoded inside an inter frame's sub-8x8
3469 /// HORZ/VERT partition -- `[0]` 8x4, `[1]` 4x8, `[2]` of those that were
3470 /// the chroma reference (so coded the group's 4x4 chroma intra), `[3]`
3471 /// MIXED groups whose chroma reference is INTER while its sibling is
3472 /// intra (the `is_sub8x8_inter` false path), `[4]` INTRA `BLOCK_4X4`
3473 /// leaves of an inter frame's sub-8x8 `PARTITION_SPLIT` (lane-sub8x4 r2 --
3474 /// the second lifted refusal's own witness; `[0]`/`[1]` count those too,
3475 /// so only this cell separates the split arm from the HORZ/VERT one).
3476 static SUB8_INTRA_RECT_HITS: std::cell::Cell<[usize; 5]> = const { std::cell::Cell::new([0; 5]) };
3477}
3478
3479/// Current value of [`SUB8_INTRA_RECT_HITS`]: `(8x4, 4x8, chroma-reference,
3480/// mixed groups, split 4x4 leaves)`.
3481pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) {
3482 SUB8_INTRA_RECT_HITS.with(|c| {
3483 let h = c.get();
3484 (h[0], h[1], h[2], h[3], h[4])
3485 })
3486}
3487
3488/// Current value of [`SUB8_INTER_RECT_HITS`]: `(8x4 groups, 4x8 groups)`.
3489pub fn sub8_inter_rect_hits() -> (usize, usize) {
3490 SUB8_INTER_RECT_HITS.with(|c| {
3491 let h = c.get();
3492 (h[0], h[1])
3493 })
3494}
3495
3496// lane-cdef r1: (a) how many 8x8 CDEF units `apply_cdef` EXCLUDED because all
3497// four of their mi cells are `skip_txfm` (libaom `cdef.c:29-38`
3498// `is_8x8_block_skip` / `av1_cdef_compute_sb_list`'s dlist test), and (b) how
3499// many 8x8 inter leaves (`decode_inter_block8`) wrote that skip band at all.
3500// (b) was 0 for every stream before this round -- the leaf path never touched
3501// the band, so an all-skip 8x8 group kept the PREVIOUS frame's flags and got
3502// filtered where libaom skips it. A gate asserts both are non-zero.
3503thread_local! {
3504 static CDEF_SKIPPED_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3505 static INTER8_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3506 // lane-cdef r2: (c) 8x8 CDEF units that are FILTERED and whose extent
3507 // crosses the cropped frame edge -- the only units for which "clamp at
3508 // the crop" and "pad past the mi-rounded extent with CDEF_VERY_LARGE"
3509 // (libaom `cdef.c:249-256`, `cdef_prepare_fb`'s hsize/vsize are
3510 // `nhb << mi_wide_l2` off the MI grid, not the crop) differ. A frame
3511 // whose width or height is not a multiple of 8 is the only shape that
3512 // produces one; the straddling-band gate arms assert it grew.
3513 static CDEF_STRADDLE_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3514 // lane-cdefstrip r1: 8x8 CDEF units visited with an UNWRITTEN skip band
3515 // (see `Neighbours::skip_written`).
3516 static CDEF_UNWRITTEN_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3517 // lane-cdefstrip r1: (d) skip RECTANGULAR blocks (every strip arm: 32x8,
3518 // 8x32, 16x8, 32x16, 64x16, AB/1:4 pieces...) that wrote the CDEF skip
3519 // band, and (e) 8x8 CDEF units whose four mi cells do NOT agree on skip --
3520 // the shape libaom's `is_8x8_block_skip` (`cdef.c:29-38`) exists for: an
3521 // 8-tall strip pair where only one half is skip must still be FILTERED.
3522 static RECT_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3523 static CDEF_MIXED_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3524}
3525
3526/// Current value of `RECT_SKIP_BAND_HITS`.
3527pub fn rect_skip_band_hits() -> usize {
3528 RECT_SKIP_BAND_HITS.with(|c| c.get())
3529}
3530
3531/// Current value of `CDEF_MIXED_SKIP_UNITS`.
3532pub fn cdef_mixed_skip_units() -> usize {
3533 CDEF_MIXED_SKIP_UNITS.with(|c| c.get())
3534}
3535
3536/// Current value of `CDEF_SKIPPED_UNITS`.
3537pub(crate) fn cdef_skipped_units() -> usize {
3538 CDEF_SKIPPED_UNITS.with(|c| c.get())
3539}
3540
3541/// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded
3542/// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1).
3543pub fn cdef_unwritten_skip_units() -> usize {
3544 CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get())
3545}
3546
3547/// Current value of `INTER8_SKIP_BAND_HITS`.
3548pub(crate) fn inter8_skip_band_hits() -> usize {
3549 INTER8_SKIP_BAND_HITS.with(|c| c.get())
3550}
3551
3552/// Current value of `CDEF_STRADDLE_UNITS`.
3553pub(crate) fn cdef_straddle_units() -> usize {
3554 CDEF_STRADDLE_UNITS.with(|c| c.get())
3555}
3556
3557/// Current value of [`SUB8_SPLIT_HITS`].
3558pub(crate) fn sub8_split_hits() -> usize {
3559 SUB8_SPLIT_HITS.with(|c| c.get())
3560}
3561
3562/// Current value of [`SUB8_INTER_SPLIT_HITS`].
3563pub fn sub8_inter_split_hits() -> usize {
3564 SUB8_INTER_SPLIT_HITS.with(|c| c.get())
3565}
3566
3567// lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherits a
3568// `tx_type` DIFFERENT from the group's FIRST sub-block -- the only shape that
3569// tells the two rules apart (`av1_get_tx_type` indexes `xd->tx_type_map`,
3570// which `set_mi_offsets` re-points to the CHROMA-REFERENCE sub-block, so the
3571// first sub-block's type is never the one). Reading it off sub-block 0
3572// inverted one 4x4 chroma unit on the wrong basis with the entropy stream
3573// perfectly in sync (no chroma `tx_type` symbol is coded), so a gate can only
3574// see this rule through this counter.
3575thread_local! {
3576 static SUB8_CHROMA_TX_FROM_REF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3577}
3578
3579/// Current value of `SUB8_CHROMA_TX_FROM_REF_HITS`.
3580pub fn sub8_chroma_tx_from_ref_hits() -> usize {
3581 SUB8_CHROMA_TX_FROM_REF_HITS.with(|c| c.get())
3582}
3583
3584fn note_sub8_chroma_tx(first_sub: TxType, chroma_ref: TxType, coeffs: bool) {
3585 if coeffs && first_sub != chroma_ref {
3586 SUB8_CHROMA_TX_FROM_REF_HITS.with(|c| c.set(c.get() + 1));
3587 }
3588}
3589
3590// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ`
3591// of an 8x8 block) this thread's decode reconstructed with REAL coefficients
3592// -- a skipped leaf exercises the prediction and the mi bookkeeping but never
3593// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate
3594// asserts on these two rather than a plain leaf count.
3595thread_local! {
3596 static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3597 static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3598 /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's
3599 /// two 4x4 transform units, predicted one after the other. A separate
3600 /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so
3601 /// the gate can prove THIS path fired.
3602 static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3603 /// 16x8/8x16 intra strips whose prediction actually read past the block's
3604 /// own width (above-right) or height (below-left) -- the samples
3605 /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/
3606 /// `has_bl_*` table row can corrupt (lane-tx4x8 r3).
3607 static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3608 /// Every 16x8/8x16 intra strip predicted, reaching or not -- the
3609 /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of.
3610 static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3611}
3612
3613/// Current value of [`RECT8_SPLIT_TX_HITS`].
3614pub(crate) fn rect8_split_tx_hits() -> usize {
3615 RECT8_SPLIT_TX_HITS.with(|c| c.get())
3616}
3617
3618/// Current value of [`RECT_STRIP_PRED_HITS`].
3619pub(crate) fn rect_strip_pred_hits() -> usize {
3620 RECT_STRIP_PRED_HITS.with(|c| c.get())
3621}
3622
3623/// Current value of [`RECT_STRIP_REACH_HITS`].
3624pub(crate) fn rect_strip_reach_hits() -> usize {
3625 RECT_STRIP_REACH_HITS.with(|c| c.get())
3626}
3627
3628/// Current value of [`TX4X8_CODED_HITS`].
3629pub(crate) fn tx4x8_coded_hits() -> usize {
3630 TX4X8_CODED_HITS.with(|c| c.get())
3631}
3632
3633/// Current value of [`TX8X4_CODED_HITS`].
3634pub(crate) fn tx8x4_coded_hits() -> usize {
3635 TX8X4_CODED_HITS.with(|c| c.get())
3636}
3637
3638// How many CHROMA coefficient blocks read their `eob_pt` from the class-1
3639// (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread.
3640// Chroma never codes a `tx_type` symbol -- it inherits the colocated luma
3641// type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on
3642// an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired
3643// (`eob_pt_{16,64,128,256}_chroma_class1`).
3644thread_local! {
3645 static CHROMA_EOB_CLASS1_HITS: std::cell::Cell<usize> =
3646 const { std::cell::Cell::new(0) };
3647}
3648
3649/// Current value of [`CHROMA_EOB_CLASS1_HITS`].
3650pub(crate) fn chroma_eob_class1_hits() -> usize {
3651 CHROMA_EOB_CLASS1_HITS.with(|c| c.get())
3652}
3653
3654/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
3655/// `tx_type` put this block's `eob_pt` on the class-1 row.
3656fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
3657 if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD {
3658 CHROMA_EOB_CLASS1_HITS.with(|c| c.set(c.get() + 1));
3659 }
3660}
3661
3662const SUB_MI: u32 = 4;
3663const MI: usize = 4;
3664const SB: usize = 64;
3665/// The `above_side`/`left_side` value a cell with no decoded neighbour holds
3666/// (tile start, superblock-row start).
3667///
3668/// [`Neighbours::partition_ctx_mi`] reads it as libaom's
3669/// `av1_get_partition_plane_context` reads its own zero-initialised
3670/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at
3671/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB`
3672/// (64), which reads identically at every level up to 64x64 but sets the bit
3673/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition
3674/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec
3675/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`).
3676const NO_NEIGHBOUR_SIDE: usize = 128;
3677const BLOCK: usize = 32;
3678const SUB: usize = 16;
3679const TX32: usize = 32;
3680const TX16: usize = 16;
3681const TX8: usize = 8;
3682const TX4: usize = 4;
3683const DC_PRED: usize = 0;
3684/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
3685/// carries an angle delta — [`crate::tile`]'s own private copy of the same
3686/// constant.
3687const V_PRED: usize = 1;
3688const H_PRED: usize = 2;
3689/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
3690/// `Fimode_To_Intradir`, libaom `blockd.h`).
3691const D157_PRED: usize = 6;
3692/// The last directional mode, `D67_PRED`.
3693const D67_PRED: usize = 8;
3694/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
3695/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
3696/// codes anything else, so this decoder never reads anything else either.
3697const ANGLE_DELTA_ZERO: usize = 3;
3698const NUM_BASE_LEVELS: i32 = 2;
3699const COEFF_BASE_RANGE: i32 = 12;
3700const BR_STEP: i32 = 3;
3701const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
3702
3703/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
3704/// whose probability mass a superblock or block half outside the frame
3705/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
3706/// duplicated here (that module is another lane's territory this round) and
3707/// kept in step with it by the byte-exact round-trip tests below rather than
3708/// by sharing code.
3709const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
3710const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
3711
3712fn trace_edge(mi_r: usize, mi_c: usize, bsize: u32, ctx: usize, rng: u32) {
3713 if crate::envflags::env_flag!("EC_AV1_TRACE") {
3714 eprintln!("OUR_PART mi_row={mi_r} mi_col={mi_c} bsize={bsize} ctx={ctx} rng={rng}");
3715 }
3716}
3717
3718fn element_prob(cdf: &[u16], element: usize) -> u16 {
3719 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
3720}
3721
3722/// The two-symbol CDF a partial superblock/block's forced-split flag is read
3723/// with: the mass of `elements` becomes the probability of the one partition
3724/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
3725/// (the encoder's non-adapting counterpart to this read).
3726fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
3727 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
3728 [32768 - split, 32768, 0]
3729}
3730
3731fn unsupported(what: impl Into<String>) -> Error {
3732 Error::unsupported("AV1 tile", what.into())
3733}
3734
3735/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
3736/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
3737/// same rule.
3738pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
3739 match base_q_idx {
3740 0..=20 => 0,
3741 21..=60 => 1,
3742 61..=120 => 2,
3743 _ => 3,
3744 }
3745}
3746
3747/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
3748/// [`crate::tile`]'s writer generates its scan tables with.
3749fn default_scan(side: usize) -> Vec<u16> {
3750 let mut scan = Vec::with_capacity(side * side);
3751 for d in 0..(2 * side - 1) {
3752 let lo = d.saturating_sub(side - 1);
3753 let hi = d.min(side - 1);
3754 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
3755 if d % 2 == 0 {
3756 scan.extend(diagonal.rev());
3757 } else {
3758 scan.extend(diagonal);
3759 }
3760 }
3761 scan
3762}
3763
3764/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
3765/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
3766/// in, instead of the default zigzag. libaom's own tables are keyed by a
3767/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
3768/// physically column-major level buffer, but they decompose to the exact
3769/// same (row, col) walk as a flat row-major traversal of *our* row-major
3770/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
3771/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
3772/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
3773/// transposed (column 0 down every row, then column 1, ...).
3774fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
3775 class_scan_table_wh(side, side, class)
3776}
3777
3778/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
3779/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
3780/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
3781/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
3782/// transcribed with -- `mrow` is the plain row-major raster in our indexing
3783/// and `mcol` its transpose, at rect sizes exactly as at square ones.
3784fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
3785 match class {
3786 TxClass::Vert => (0..(w * h) as u16).collect(),
3787 TxClass::Horiz => (0..w)
3788 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
3789 .collect(),
3790 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
3791 }
3792}
3793
3794fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
3795 match scan_idx {
3796 0 => 0,
3797 i if i <= area / 8 => 1,
3798 i if i <= area / 4 => 2,
3799 _ => 3,
3800 }
3801}
3802
3803fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
3804 if row >= side || col >= side {
3805 0
3806 } else {
3807 grid[row * side + col]
3808 }
3809}
3810
3811/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
3812/// `txb_common.h`): everything but the two lone-axis-identity types this
3813/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
3814#[derive(Clone, Copy, PartialEq, Eq)]
3815enum TxClass {
3816 TwoD,
3817 Horiz,
3818 Vert,
3819}
3820
3821impl TxClass {
3822 fn of(tx_type: TxType) -> Self {
3823 match tx_type {
3824 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
3825 // key on axis alone -- FLIPADST is still ADST for this purpose.
3826 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
3827 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
3828 _ => Self::TwoD,
3829 }
3830 }
3831}
3832
3833/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
3834/// table (indexed by the position along the transform's *coded* axis --
3835/// `col` for horiz, `row` for vert) that places their contexts past the 2D
3836/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
3837/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
3838fn nz_map_ctx_offset_1d(i: usize) -> usize {
3839 match i {
3840 0 => 26,
3841 1 => 31,
3842 _ => 36,
3843 }
3844}
3845
3846fn base_ctx(
3847 grid: &[i32],
3848 side: usize,
3849 row: usize,
3850 col: usize,
3851 class: TxClass,
3852 rect_shape: Option<(usize, usize)>,
3853) -> usize {
3854 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
3855 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
3856 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
3857 // position through the full 1D neighbour sum and offset table. Skipping
3858 // that for every class desynced the last (DC) coefficient of a
3859 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
3860 // 0, which then read one extra `BR` symbol at the max and forced a
3861 // spurious third Golomb call).
3862 if class == TxClass::TwoD && row == 0 && col == 0 {
3863 return 0;
3864 }
3865 let offsets: [(usize, usize); 5] = match class {
3866 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
3867 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
3868 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
3869 };
3870 let mag: i32 = offsets
3871 .iter()
3872 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
3873 .sum();
3874 let ctx = ((mag + 1) >> 1).min(4) as usize;
3875 match class {
3876 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
3877 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
3878 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
3879 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
3880 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
3881 // strip, which own a genuinely different table from the square one
3882 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
3883 // square table vs the real ctx 13 the rect table gives).
3884 TxClass::TwoD => {
3885 // lane-rectsplit r4: apply libaom's GENERATING RULE
3886 // (`txb_common.h:199-209`) directly instead of indexing the
3887 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
3888 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
3889 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
3890 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
3891 // so 32 consecutive entries are one COLUMN: the [`cdf`]
3892 // transcriptions are `[col][row]` and this read had them as
3893 // `[row][col]` -- the transpose, i.e. the other shape's rule with
3894 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
3895 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
3896 // pins the rule against the tables over their whole 5x5 domain.
3897 if let Some((w, h)) = rect_shape {
3898 if crate::envflags::env_flag!("EC_NZOFF_DUMP") {
3899 eprintln!("NZOFF side={side} shape={w}x{h} row={row} col={col}");
3900 }
3901 if w < h && row < 2 {
3902 return ctx + 11;
3903 }
3904 if w > h && col < 2 {
3905 return ctx + 16;
3906 }
3907 }
3908 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
3909 }
3910 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
3911 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
3912 }
3913}
3914
3915fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize, class: TxClass) -> usize {
3916 let extra = match class {
3917 TxClass::TwoD => neighbour(grid, side, row + 1, col + 1).abs(),
3918 TxClass::Horiz => neighbour(grid, side, row, col + 2).abs(),
3919 TxClass::Vert => neighbour(grid, side, row + 2, col).abs(),
3920 };
3921 let mag = neighbour(grid, side, row + 1, col).abs()
3922 + neighbour(grid, side, row, col + 1).abs()
3923 + extra;
3924 let mag = (((mag + 1) >> 1).min(6)) as usize;
3925 if row == 0 && col == 0 {
3926 return mag;
3927 }
3928 let near_origin = match class {
3929 TxClass::TwoD => row < 2 && col < 2,
3930 TxClass::Horiz => col == 0,
3931 TxClass::Vert => row == 0,
3932 };
3933 if near_origin { mag + 7 } else { mag + 14 }
3934}
3935
3936/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
3937/// transposed from libaom's column-major buffer into this decoder's row-major
3938/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
3939/// against the real table). Not the square zigzag formula generalized to
3940/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
3941const SCAN_32X16: [u16; 512] = [
3942 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161,
3943 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39,
3944 8, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72,
3945 41, 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229,
3946 198, 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44,
3947 13, 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418,
3948 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326,
3949 295, 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234,
3950 203, 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142,
3951 111, 80, 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19,
3952 485, 454, 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424,
3953 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332,
3954 301, 270, 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240,
3955 209, 178, 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148,
3956 117, 86, 55, 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25,
3957 491, 460, 429, 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430,
3958 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338,
3959 307, 276, 245, 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246,
3960 215, 184, 153, 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154,
3961 123, 92, 61, 30, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31,
3962 497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405,
3963 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251,
3964 220, 189, 158, 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439,
3965 408, 377, 346, 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503,
3966 472, 441, 410, 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443,
3967 412, 381, 350, 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415,
3968 509, 478, 447, 510, 479, 511,
3969];
3970
3971/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
3972/// [`SCAN_32X16`]'s doc comment).
3973const SCAN_16X32: [u16; 512] = [
3974 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,
3975 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
3976 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
3977 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
3978 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
3979 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
3980 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
3981 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
3982 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
3983 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
3984 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
3985 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
3986 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
3987 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
3988 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
3989 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
3990 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
3991 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
3992 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
3993 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
3994 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
3995 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
3996 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
3997 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
3998 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
3999 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
4000];
4001
4002/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
4003/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
4004/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
4005/// the same source).
4006const SCAN_4X8: [u16; 32] = [
4007 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,
4008 23, 26, 29, 27, 30, 31,
4009];
4010
4011/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
4012const SCAN_8X4: [u16; 32] = [
4013 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,
4014 29, 22, 15, 30, 23, 31,
4015];
4016
4017/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
4018/// [`SCAN_32X16`]'s doc comment).
4019const SCAN_16X8: [u16; 128] = [
4020 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,
4021 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
4022 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
4023 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
4024 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
4025 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
4026];
4027
4028/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
4029/// [`SCAN_32X16`]'s doc comment).
4030const SCAN_8X16: [u16; 128] = [
4031 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,
4032 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
4033 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
4034 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
4035 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
4036 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
4037];
4038
4039/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
4040/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
4041/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
4042/// scans column-major (`p = col * height + row`), so a naive copy of
4043/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
4044/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
4045/// are byte-identical to this decoder's [`SCAN_8X16`].
4046const SCAN_32X8: [u16; 256] = [
4047 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
4048 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226, 195,
4049 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104, 73, 42,
4050 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200, 169,
4051 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78, 47, 16,
4052 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205, 174, 143,
4053 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83, 52, 21, 239,
4054 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210, 179, 148, 117,
4055 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88, 57, 26, 244, 213,
4056 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215, 184, 153, 122, 91,
4057 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93, 62, 31, 249, 218, 187,
4058 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127, 252, 221, 190, 159, 253,
4059 222, 191, 254, 223, 255,
4060];
4061/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
4062/// 16x64 `PARTITION_VERT_4` strip).
4063const SCAN_8X32: [u16; 256] = [
4064 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,
4065 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
4066 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
4067 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
4068 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
4069 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
4070 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
4071 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
4072 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
4073 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
4074 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
4075 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
4076 239, 246, 253, 247, 254, 255,
4077];
4078/// `Default_Scan_16x4`, this decoder's own row-major transcription of
4079/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
4080/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
4081/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
4082/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
4083/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
4084/// were emitted -- a naive copy installs the transpose (class
4085/// reference-layout-not-spec).
4086const SCAN_16X4: [u16; 64] = [
4087 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,
4088 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
4089 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
4090];
4091/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
4092/// 8x32 `PARTITION_VERT_4` strip).
4093const SCAN_4X16: [u16; 64] = [
4094 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,
4095 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
4096 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
4097];
4098
4099/// [`neighbour`] with independent `w` (row stride)/`h` (row-bound) extents
4100/// (lane-rectwire, mirrors [`record_rect`](Neighbours::record_rect)'s
4101/// asymmetric-extent pattern).
4102fn neighbour_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> i32 {
4103 if row >= h || col >= w {
4104 0
4105 } else {
4106 grid[row * w + col]
4107 }
4108}
4109
4110/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
4111/// the rect generalization is libaom's own comment in
4112/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
4113/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
4114/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
4115/// [`decode_block_rect`] codes (see that function's own doc comment).
4116fn base_ctx_rect(
4117 grid: &[i32],
4118 w: usize,
4119 h: usize,
4120 row: usize,
4121 col: usize,
4122 class: TxClass,
4123) -> usize {
4124 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
4125 // the 2D class short-circuits the DC position.
4126 if class == TxClass::TwoD && row == 0 && col == 0 {
4127 return 0;
4128 }
4129 let offsets: [(usize, usize); 5] = match class {
4130 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
4131 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
4132 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
4133 };
4134 let mag: i32 = offsets
4135 .iter()
4136 .map(|&(dr, dc)| neighbour_rect(grid, w, h, row + dr, col + dc).abs().min(3))
4137 .sum();
4138 let ctx = ((mag + 1) >> 1).min(4) as usize;
4139 match class {
4140 TxClass::TwoD => {
4141 if w < h && row < 2 {
4142 return ctx + 11;
4143 }
4144 if w > h && col < 2 {
4145 return ctx + 16;
4146 }
4147 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
4148 }
4149 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
4150 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
4151 // position along one axis only).
4152 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
4153 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
4154 }
4155}
4156
4157/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
4158/// neighbour-offset math itself is shape-independent, only the boundary
4159/// clamp needs the real bound in each axis.
4160fn br_ctx_rect(
4161 grid: &[i32],
4162 w: usize,
4163 h: usize,
4164 row: usize,
4165 col: usize,
4166 class: TxClass,
4167) -> usize {
4168 let extra = match class {
4169 TxClass::TwoD => neighbour_rect(grid, w, h, row + 1, col + 1).abs(),
4170 TxClass::Horiz => neighbour_rect(grid, w, h, row, col + 2).abs(),
4171 TxClass::Vert => neighbour_rect(grid, w, h, row + 2, col).abs(),
4172 };
4173 let mag = neighbour_rect(grid, w, h, row + 1, col).abs()
4174 + neighbour_rect(grid, w, h, row, col + 1).abs()
4175 + extra;
4176 let mag = (((mag + 1) >> 1).min(6)) as usize;
4177 if row == 0 && col == 0 {
4178 return mag;
4179 }
4180 let near_origin = match class {
4181 TxClass::TwoD => row < 2 && col < 2,
4182 TxClass::Horiz => col == 0,
4183 TxClass::Vert => row == 0,
4184 };
4185 if near_origin { mag + 7 } else { mag + 14 }
4186}
4187
4188fn dc_vote(dc: Option<bool>) -> i32 {
4189 match dc {
4190 None => 0,
4191 Some(true) => -1,
4192 Some(false) => 1,
4193 }
4194}
4195
4196fn dc_sign_ctx(vote: i32) -> usize {
4197 match vote.signum() {
4198 0 => 0,
4199 -1 => 1,
4200 _ => 2,
4201 }
4202}
4203
4204/// The `tx_type` a CDF symbol names, given the width of the row it was read
4205/// from.
4206///
4207/// The row's own width names its set (spec `Tx_Type_Intra_Inv_Set*` /
4208/// `Tx_Type_Inter_Inv_Set*`): 17 slots (16 symbols) is `EXT_TX_SET_ALL16`, 13
4209/// (12) `EXT_TX_SET_DTT9_IDTX_1DDCT`, 8 (7) `TX_SET_INTRA_1`, and everything
4210/// narrower the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` order, whose two
4211/// members are a prefix of the five.
4212///
4213/// One function rather than a `match` at each reader, so
4214/// [`crate::refusal_inventory`]'s enumeration of every (width, symbol) pair
4215/// tests the mapping the readers actually use.
4216pub(crate) fn tx_type_from_symbol(cdf_len: usize, t: usize) -> Option<TxType> {
4217 match cdf_len {
4218 17 => TxType::from_symbol_all16(t),
4219 13 => TxType::from_symbol_set2_12(t),
4220 8 => TxType::from_symbol_set1(t),
4221 _ => TxType::from_symbol(t),
4222 }
4223}
4224
4225/// The remainder of a level the base and base-range syntax could not reach
4226/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
4227/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
4228pub(crate) fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
4229 // lane-scaledref r1: this cap MASKS A REAL DEFECT and must not be lifted
4230 // on its own. Reading up to 32 leading zeros (dav1d's `len < 32`; libaom
4231 // itself calls a 21st bit a corrupt frame, decodetxb.c:30) is bit-identical
4232 // for every tail any encoder writes -- our own writer tops out at 19 zeros
4233 // (`tile::MAX_LEVEL == MAX_BR_LEVEL + (1 << 19)`) -- and was implemented
4234 // and round-trip tested here (commit ee1f980, reverted in 314ee08). It
4235 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
4236 // RED: seed 67 stops here today, and with the cap raised it decodes to a
4237 // frame-0 LUMA MISMATCH instead. A key frame cannot legitimately carry a
4238 // level above 1<<19, so the long tail is the SYMPTOM of an earlier desync
4239 // in that intra rect64 stream -- class `refusal-hides-a-defect`. Lift this
4240 // together with that defect's fix, not before.
4241 let mut length = 1u32;
4242 while dec.literal(1) == 0 {
4243 length += 1;
4244 if length > 20 {
4245 return Err(unsupported("a Golomb tail longer than this decoder reads"));
4246 }
4247 }
4248 let mut x = 1u32;
4249 for _ in 1..length {
4250 x = (x << 1) | dec.literal(1);
4251 }
4252 Ok(x - 1)
4253}
4254
4255/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
4256/// [`crate::tile`]'s `write_eob`.
4257fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
4258 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
4259 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
4260
4261 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
4262 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
4263 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
4264 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
4265 // `eob_multi_ctx`). Missing that split desynced the very first
4266 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
4267 // against a real aomdec trace).
4268 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
4269 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
4270 (_, Some(class1)) => class1,
4271 };
4272 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
4273 let (range, value) = dec.debug_state();
4274 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
4275 }
4276 let group = dec.symbol(eob_pt) + 1;
4277 if trace {
4278 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
4279 }
4280 let bits = OFFSET_BITS[group];
4281 let mut offset = 0u32;
4282 if bits > 0 {
4283 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
4284 if trace {
4285 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
4286 }
4287 offset = top << (bits - 1);
4288 if bits > 1 {
4289 offset |= dec.literal(bits - 1);
4290 }
4291 }
4292 GROUP_START[group] + offset as usize
4293}
4294
4295/// One transform block's levels, the inverse of [`crate::tile`]'s
4296/// `write_coeffs`, returned as a `side * side` grid in raster order, along
4297/// with the transform type that grid was coded under (`DCT_DCT` when the
4298/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
4299/// 64-point transforms, which never code anything else).
4300///
4301/// # Errors
4302/// Returns an error if the `tx_type` symbol decodes to a value outside its
4303/// CDF's own set (a corrupt or unsupported bitstream) — every value the
4304/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
4305/// produce dispatches to a real inverse transform.
4306/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
4307/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
4308/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
4309/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
4310/// the plane's own predicted mode instead. Every entry this table can
4311/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
4312/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
4313/// table ever names), so unlike the CDF-coded luma path there is no
4314/// ext-tx-set membership check to fall back from here.
4315fn default_intra_tx_type(mode: u8) -> TxType {
4316 use crate::intra::{
4317 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
4318 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
4319 };
4320 match mode {
4321 DC_PRED | D45_PRED => TxType::DctDct,
4322 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
4323 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
4324 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
4325 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
4326 }
4327}
4328
4329/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
4330/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
4331/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
4332fn is_smooth_mode(mode: usize) -> bool {
4333 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
4334}
4335
4336fn read_coeffs(
4337 dec: &mut SymbolDecoder,
4338 coding: &mut TxbTables,
4339 scan: &[u16],
4340 skip_ctx: usize,
4341 sign_ctx: usize,
4342 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
4343 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
4344 // nothing at all; `DctDct` for every luma call and every chroma call at
4345 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
4346 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
4347 default_tx_type: TxType,
4348 // `Some((w, h))` with `w != h` when this read is a superblock-level
4349 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
4350 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
4351 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
4352 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
4353 // caller's block genuinely is `side` x `side`.
4354 rect_shape: Option<(usize, usize)>,
4355) -> Result<(Vec<i32>, TxType)> {
4356 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
4357 let side = coding.side;
4358 let mut grid = vec![0i32; side * side];
4359 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
4360 let (range, value) = dec.debug_state();
4361 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
4362 }
4363 let dbg_txbskip = if coeff_trace_on() {
4364 coding.txb_skip[skip_ctx]
4365 } else {
4366 [0; 3]
4367 };
4368 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
4369 if coeff_trace_on() {
4370 let (rng, _) = dec.debug_state();
4371 eprintln!(
4372 "EC_COEFF_STEP tag=all_zero side={} ctx={skip_ctx} cdf={dbg_txbskip:?} all_zero={} rng={rng}",
4373 coding.side,
4374 all_zero as i32
4375 );
4376 }
4377 if crate::envflags::env_flag!("EC_AV1_TELL") {
4378 eprintln!(
4379 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
4380 all_zero as u8, dec.debug_bitpos(), dec.debug_state().0
4381 );
4382 }
4383 if trace {
4384 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
4385 }
4386 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
4387 let (range, value) = dec.debug_state();
4388 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
4389 }
4390 if all_zero {
4391 return Ok((grid, TxType::DctDct));
4392 }
4393 let mut tx_type = default_tx_type;
4394 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
4395 // The CDF row's own width names its set (lane-cdffwd2: extended
4396 // past the original two-way intra split once wider `reduced_tx_set
4397 // == 0` inter sets joined the table): 17 slots (16 symbols) is
4398 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
4399 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
4400 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
4401 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
4402 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
4403 let len = tx_type_cdf.len();
4404 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") && len == 3 {
4405 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
4406 }
4407 let t = dec.symbol(tx_type_cdf);
4408 if coeff_trace_on() {
4409 let (rng, _) = dec.debug_state();
4410 eprintln!("EC_COEFF_STEP tag=tx_type len={len} rng={rng}");
4411 }
4412 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
4413 let (range, value) = dec.debug_state();
4414 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
4415 }
4416 if trace {
4417 eprintln!("TRACE tx_type value={t} len={len}");
4418 }
4419 tx_type = tx_type_from_symbol(len, t)
4420 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
4421 }
4422
4423 let class = TxClass::of(tx_type);
4424 if class != TxClass::TwoD {
4425 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
4426 RECT_CLASS1_HITS.with(|c| c.set(c.get() + 1));
4427 }
4428 let eob = read_eob(dec, coding, class);
4429 if trace {
4430 eprintln!("TRACE eob value={eob}");
4431 }
4432 let ec_trace_coeff = coeff_trace_on();
4433 if ec_trace_coeff {
4434 let (rng, _) = dec.debug_state();
4435 let cls = match class { TxClass::TwoD => "2d", TxClass::Horiz => "horiz", TxClass::Vert => "vert" };
4436 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
4437 }
4438 let class_scan;
4439 let scan: &[u16] = if class == TxClass::TwoD {
4440 scan
4441 } else {
4442 class_scan = class_scan_table(side, class);
4443 &class_scan
4444 };
4445 let mut levels = vec![0i32; side * side];
4446 for scan_idx in (0..eob).rev() {
4447 let pos = scan[scan_idx] as usize;
4448 let (row, col) = (pos / side, pos % side);
4449 let level = if scan_idx == eob - 1 {
4450 let ctx = eob_coeff_ctx(scan_idx, side * side);
4451 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
4452 if trace {
4453 eprintln!(
4454 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
4455 );
4456 }
4457 v
4458 } else {
4459 let ctx = base_ctx(&levels, side, row, col, class, rect_shape);
4460 let v = dec.symbol(&mut coding.base[ctx]) as i32;
4461 if ec_trace_coeff {
4462 let (rng, _) = dec.debug_state();
4463 // `pos` in libaom's column-major `coeff_idx` convention, so
4464 // the ladder lines up with instrumented `aomdec`.
4465 let apos = col * side + row;
4466 eprintln!(
4467 "EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}"
4468 );
4469 }
4470 if trace {
4471 eprintln!(
4472 "TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
4473 );
4474 }
4475 v
4476 };
4477 let level = if level > NUM_BASE_LEVELS {
4478 let ctx = br_ctx(&levels, side, row, col, class);
4479 let mut level = level;
4480 let mut sent = 0;
4481 loop {
4482 let k = dec.symbol(&mut coding.br[ctx]) as i32;
4483 if ec_trace_coeff {
4484 // lane-leaf8tx r3: the `br` rung was missing from THIS
4485 // path's trace, so the cross-decoder range ladder was
4486 // blind to every base-range symbol and mis-reported the
4487 // first divergence (class [[gate-blind-to-feature]]).
4488 let (rng, _) = dec.debug_state();
4489 let apos = col * side + row;
4490 eprintln!(
4491 "EC_COEFF_STEP tag=br c={scan_idx} pos={apos} ctx={ctx} k={k} rng={rng}"
4492 );
4493 }
4494 if trace {
4495 eprintln!(
4496 "TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}"
4497 );
4498 }
4499 level += k;
4500 sent += BR_STEP;
4501 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
4502 break;
4503 }
4504 }
4505 level
4506 } else {
4507 level
4508 };
4509 if ec_trace_coeff && scan_idx == eob - 1 {
4510 let (rng, _) = dec.debug_state();
4511 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
4512 }
4513 levels[pos] = level;
4514 }
4515 if ec_trace_coeff {
4516 let (rng, _) = dec.debug_state();
4517 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
4518 }
4519
4520 for (c, &pos) in scan[..eob].iter().enumerate() {
4521 let level = levels[pos as usize];
4522 if level == 0 {
4523 continue;
4524 }
4525 let negative = if pos == 0 {
4526 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
4527 if trace {
4528 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
4529 }
4530 v
4531 } else {
4532 dec.literal(1) == 1
4533 };
4534 if ec_trace_coeff {
4535 let (rng, _) = dec.debug_state();
4536 eprintln!("EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}", negative as i32);
4537 }
4538 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
4539 let g = read_golomb(dec)?;
4540 if trace {
4541 eprintln!("TRACE golomb pos={pos} value={g}");
4542 }
4543 level + g as i32
4544 } else {
4545 level
4546 };
4547 if ec_trace_coeff {
4548 let (rng, _) = dec.debug_state();
4549 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
4550 }
4551 grid[pos as usize] = if negative { -level } else { level };
4552 }
4553 Ok((grid, tx_type))
4554}
4555
4556/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
4557/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
4558/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
4559/// can ever produce, since every `tx_type` this decoder's rect sets can read
4560/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
4561/// rather than guess-decode if a non-2D class ever shows up here, since
4562/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
4563/// form for those.
4564fn read_coeffs_rect(
4565 dec: &mut SymbolDecoder,
4566 coding: &mut TxbTables,
4567 scan: &[u16],
4568 w: usize,
4569 h: usize,
4570 skip_ctx: usize,
4571 sign_ctx: usize,
4572 default_tx_type: TxType,
4573) -> Result<(Vec<i32>, TxType)> {
4574 let rect_trace = coeff_trace_on();
4575 let mut grid = vec![0i32; w * h];
4576 let entry_rng = dec.debug_state().0;
4577 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
4578 if rect_trace {
4579 eprintln!(
4580 "EC_COEFF_STEP tag=all_zero plane=0 ctx={skip_ctx} entry={entry_rng} all_zero={} rng={}",
4581 all_zero as i32,
4582 dec.debug_state().0
4583 );
4584 }
4585 if all_zero {
4586 return Ok((grid, TxType::DctDct));
4587 }
4588 RECT_COEFF_TU_HITS.with(|c| c.set(c.get() + 1));
4589 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
4590 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
4591 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
4592 // context offsets -- both of which now have rect forms
4593 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
4594 // The rect sets that carry no symbol at all still pass `None` here.
4595 let mut tx_type = default_tx_type;
4596 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
4597 let len = tx_type_cdf.len();
4598 let t = dec.symbol(tx_type_cdf);
4599 tx_type = tx_type_from_symbol(len, t)
4600 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
4601 if rect_trace {
4602 eprintln!("EC_COEFF_STEP tag=tx_type plane=0 rng={}", dec.debug_state().0);
4603 }
4604 }
4605 let class = TxClass::of(tx_type);
4606 if class != TxClass::TwoD {
4607 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
4608 }
4609 let eob = read_eob(dec, coding, class);
4610 if rect_trace {
4611 eprintln!("EC_COEFF_STEP tag=eob eob={eob} rng={}", dec.debug_state().0);
4612 }
4613 let class_scan;
4614 let scan: &[u16] = if class == TxClass::TwoD {
4615 scan
4616 } else {
4617 class_scan = class_scan_table_wh(w, h, class);
4618 &class_scan
4619 };
4620 let mut levels = vec![0i32; w * h];
4621 for scan_idx in (0..eob).rev() {
4622 let pos = scan[scan_idx] as usize;
4623 let (row, col) = (pos / w, pos % w);
4624 // libaom's column-major `coeff_idx`, for ladder comparison.
4625 let apos = col * h + row;
4626 let level = if scan_idx == eob - 1 {
4627 let ctx = eob_coeff_ctx(scan_idx, w * h);
4628 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
4629 if rect_trace {
4630 eprintln!(
4631 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
4632 dec.debug_state().0
4633 );
4634 }
4635 v
4636 } else {
4637 let ctx = base_ctx_rect(&levels, w, h, row, col, class);
4638 let v = dec.symbol(&mut coding.base[ctx]) as i32;
4639 if rect_trace {
4640 eprintln!(
4641 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
4642 dec.debug_state().0
4643 );
4644 }
4645 v
4646 };
4647 let level = if level > NUM_BASE_LEVELS {
4648 let ctx = br_ctx_rect(&levels, w, h, row, col, class);
4649 let mut level = level;
4650 let mut sent = 0;
4651 loop {
4652 let k = dec.symbol(&mut coding.br[ctx]) as i32;
4653 if rect_trace {
4654 eprintln!(
4655 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
4656 dec.debug_state().0
4657 );
4658 }
4659 level += k;
4660 sent += BR_STEP;
4661 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
4662 break;
4663 }
4664 }
4665 level
4666 } else {
4667 level
4668 };
4669 levels[pos] = level;
4670 if rect_trace {
4671 let (rng, _) = dec.debug_state();
4672 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}");
4673 }
4674 }
4675 if rect_trace {
4676 let (rng, _) = dec.debug_state();
4677 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
4678 }
4679 for &pos in &scan[..eob] {
4680 let level = levels[pos as usize];
4681 if level == 0 {
4682 continue;
4683 }
4684 let negative = if pos == 0 {
4685 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
4686 } else {
4687 dec.literal(1) == 1
4688 };
4689 if rect_trace {
4690 let (rng, _) = dec.debug_state();
4691 eprintln!("EC_COEFF_STEP tag=sign_rect pos={pos} sign={} dcctx={sign_ctx} rng={rng}", u8::from(negative));
4692 }
4693 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
4694 let g = read_golomb(dec)?;
4695 level + g as i32
4696 } else {
4697 level
4698 };
4699 grid[pos as usize] = if negative { -level } else { level };
4700 }
4701 Ok((grid, tx_type))
4702}
4703
4704/// What one coded block leaves behind for the blocks that read it as a
4705/// neighbour: whether it coded anything at all, and the sign of its DC —
4706/// [`crate::tile`]'s own private `Neighbour`.
4707#[derive(Clone, Copy, Default)]
4708struct Neighbour {
4709 /// The transform unit's cumulative coefficient level (spec `cul_level`,
4710 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
4711 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
4712 /// boolean (`level != 0`) is enough for every context this decoder read
4713 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
4714 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
4715 /// needs the actual magnitude tier of its above/left neighbours, not
4716 /// just whether they coded anything.
4717 level: u8,
4718 dc: Option<bool>,
4719}
4720
4721fn neighbour_state(grid: &[i32]) -> Neighbour {
4722 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
4723 Neighbour {
4724 level: cul.min(7) as u8,
4725 dc: (grid[0] != 0).then_some(grid[0] < 0),
4726 }
4727}
4728
4729/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
4730/// transform unit smaller than the block it sits in): `top`/`left` are the
4731/// above/left neighbours' magnitude tiers, each already clamped to 4.
4732const SKIP_CONTEXTS: [[usize; 5]; 5] = [
4733 [1, 2, 2, 2, 3],
4734 [2, 4, 4, 4, 5],
4735 [2, 4, 4, 4, 5],
4736 [2, 4, 4, 4, 5],
4737 [3, 5, 5, 5, 6],
4738];
4739
4740/// The neighbour state a block's contexts are read from — a duplicate of
4741/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
4742/// territory this round), kept at the same two granularities the real writer
4743/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
4744/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
4745/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
4746/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
4747/// chroma transform straddling the true, odd-sized frame edge see its
4748/// neighbour's state clamped at its own subsampled edge rather than luma's.
4749struct Neighbours {
4750 above: Vec<[Neighbour; 3]>,
4751 left: Vec<[Neighbour; 3]>,
4752 above_mode: Vec<usize>,
4753 left_mode: Vec<usize>,
4754 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
4755 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
4756 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
4757 /// luma one -- the same block can (and often does) code a different
4758 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
4759 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
4760 /// within-block neighbour finer than this grid) is luma-only -- a known,
4761 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
4762 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
4763 above_uv_mode: Vec<usize>,
4764 left_uv_mode: Vec<usize>,
4765 above_side: Vec<usize>,
4766 left_side: Vec<usize>,
4767 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
4768 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
4769 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
4770 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
4771 /// array cannot tell the second leaf's partition symbol that the first
4772 /// one was coded at 8x8.
4773 above_side_mi: Vec<usize>,
4774 left_side_mi: Vec<usize>,
4775 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
4776 /// / row, with the mi position it was written at
4777 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
4778 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
4779 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
4780 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
4781 /// leaf whose neighbour is another split group needs that group's leaf 3
4782 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
4783 /// and read only by [`decode_leaf_split4`]; the position guard makes it
4784 /// fall back to the coarse slot whenever the real neighbour was a block
4785 /// of 8x8 or larger (whose one mode is correct for every row it spans).
4786 sub8_mode_col: Vec<(usize, usize)>,
4787 sub8_mode_row: Vec<(usize, usize)>,
4788 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
4789 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
4790 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
4791 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
4792 /// the leaf above writes the same row slot the block to the left owns.
4793 uv_mode_col: Vec<(usize, usize)>,
4794 uv_mode_row: Vec<(usize, usize)>,
4795 /// Every mi cell's own `uv_mode`, the mi grid libaom's
4796 /// `chroma_above_mbmi`/`chroma_left_mbmi` read directly (`set_mi_row_col`,
4797 /// blockd.h). lane-t900 r12: the one-slot-per-column
4798 /// `uv_mode_col`/`uv_mode_row` maps above hold only the LAST block written
4799 /// in that column, so a sub-8x8 pair's own first (non-chroma-ref) half
4800 /// overwrote the row the pair's chroma-ref half then wanted to read --
4801 /// the mi-exact match failed and the coarse [`SUB`] band answered instead.
4802 /// `u8::MAX` = no block has written this cell yet (fall back to the maps).
4803 uv_mode_grid: Vec<u8>,
4804 /// [`Self::uv_mode_grid`]'s stride, in mi units (superblock-padded, like
4805 /// every other band here).
4806 uv_grid_cols: usize,
4807 /// Whether the block above/left of this column/row was coded `skip` --
4808 /// an inter frame's own `skip` context (spec `SkipContext`), which the
4809 /// key-frame writer never tracks (its skip context is always zero); a
4810 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
4811 /// `left_skip`.
4812 above_skip: Vec<bool>,
4813 left_skip: Vec<bool>,
4814 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
4815 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
4816 /// pixels last written over each unit by `set_txfm_ctxs`/
4817 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
4818 /// symbol reads its context from (lane-txselect, spec 5.11.17).
4819 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
4820 /// array is exactly libaom's per-superblock-row reset, since each mi row
4821 /// is only ever visited inside one superblock row.
4822 above_txfm: Vec<u8>,
4823 left_txfm: Vec<u8>,
4824 /// Whether the block above/left of this column/row coded `skip_mode`
4825 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
4826 /// lane-av1comp round 14.
4827 above_skip_mode: Vec<bool>,
4828 left_skip_mode: Vec<bool>,
4829 /// Whether the block above/left was coded inter -- the `is_inter`
4830 /// context (spec `av1_get_intra_inter_context`), a duplicate of
4831 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
4832 above_inter: Vec<bool>,
4833 left_inter: Vec<bool>,
4834 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
4835 /// alphabet) the block above/left of this column/row coded, or `-1` for
4836 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
4837 /// functions (`mvstack::ref_ctx` family) need the real reference, not
4838 /// just "was it inter" (lane-av1refs: every inter block used to be
4839 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
4840 /// enough).
4841 above_ref: Vec<i8>,
4842 left_ref: Vec<i8>,
4843 /// The block above/left's *second* reference frame when it was coded
4844 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
4845 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
4846 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
4847 /// `i8`, once a compound `read_ref_frames` lands. Always `None` today
4848 /// (no decode path here ever produces a compound block yet).
4849 above_ref1: Vec<Option<i8>>,
4850 left_ref1: Vec<Option<i8>>,
4851 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
4852 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
4853 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
4854 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
4855 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
4856 above_comp_group_idx: Vec<u8>,
4857 left_comp_group_idx: Vec<u8>,
4858 above_compound_idx: Vec<u8>,
4859 left_compound_idx: Vec<u8>,
4860 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
4861 /// `3` = "no info": an intra neighbour or the frame's own border) of the
4862 /// block above/left of this column/row -- spec
4863 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
4864 above_filter: Vec<[u8; 2]>,
4865 left_filter: Vec<[u8; 2]>,
4866 mi_cols: usize,
4867 mi_rows: usize,
4868 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
4869 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
4870 /// 7.15) never filters an 8x8 luma block whose covering coded block read
4871 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
4872 /// grain [`Self::record_mi`] already writes at), read back at 8x8
4873 /// granularity by [`apply_cdef`] since `skip` is constant across every
4874 /// mi cell one coded block covers.
4875 skip_grid: Vec<bool>,
4876 /// lane-cdefstrip r1 instrument: whether any coded block actually WROTE
4877 /// [`Self::skip_grid`] at this mi cell during this frame. A fresh
4878 /// `Neighbours` seeds `skip_grid` all-`false` ("not skip"), so a decode
4879 /// arm that forgets [`Self::fill_skip_grid_rect`] silently makes
4880 /// [`apply_cdef`] filter an 8x8 unit libaom's `is_8x8_block_skip`
4881 /// (`cdef.c:29-38`) excludes -- exactly the lane-cdef defect, and
4882 /// unobservable from the pixels alone. Counted by
4883 /// [`cdef_unwritten_skip_units`].
4884 skip_written: Vec<bool>,
4885 /// Per-4x4-mi origin `(mi_row, mi_col)` of the coded (prediction) block
4886 /// covering that cell -- spec 7.14.2's `isBlockEdge`/libaom `pu_edge`,
4887 /// which re-enables the loop filter at a prediction boundary between two
4888 /// skipped inter blocks (lane-mergefix r4). Written by
4889 /// [`Self::fill_skip_grid_rect`], whose `at_mi` IS that origin.
4890 blk_org_grid: Vec<[u16; 2]>,
4891 /// Per-4x4-mi `(width, height)` in mi units of the coded block covering
4892 /// that cell -- the other half of `pu_edge`: libaom tests the edge
4893 /// coordinate against the block's size in the FILTERED plane's own
4894 /// pixels, which for chroma is `max(luma_dim / 2, 4)` (lane-t900 r30b).
4895 blk_dim_grid: Vec<[u8; 2]>,
4896 skip_grid_cols_mi: usize,
4897 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
4898 /// never splits a coded block's transform below its own size (round 2:
4899 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
4900 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
4901 /// edge-length lookup (`apply_deblock`).
4902 tx_grid: Vec<u8>,
4903 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
4904 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
4905 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
4906 tx_h_grid: Vec<u8>,
4907 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
4908 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
4909 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
4910 /// does NOT follow luma's `tx_depth` split, so deriving it as
4911 /// `tx_grid / 2` invented chroma transform edges the deblocker then
4912 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
4913 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
4914 /// every caller routes through.
4915 uv_tx_grid: Vec<u8>,
4916 uv_tx_h_grid: Vec<u8>,
4917 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
4918 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
4919 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
4920 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
4921 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
4922 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
4923 /// reference onto `LAST_FRAME`'s own delta).
4924 ref_grid: Vec<i8>,
4925 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
4926 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
4927 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
4928 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
4929 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
4930 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
4931 /// to know which mode produced the value.
4932 delta_lf_grid: Vec<[i8; 4]>,
4933 /// The block above/left's own palette-Y size (0 = not a palette block)
4934 /// and its base colours -- `av1_get_palette_mode_ctx`/
4935 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
4936 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
4937 above_palette_size: Vec<usize>,
4938 left_palette_size: Vec<usize>,
4939 above_palette_colors: Vec<[u16; 8]>,
4940 left_palette_colors: Vec<[u16; 8]>,
4941 /// As the four fields above, for the neighbour's own chroma (U-channel
4942 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
4943 /// palette size/colours (lane-palette2 r1).
4944 above_palette_uv_size: Vec<usize>,
4945 left_palette_uv_size: Vec<usize>,
4946 above_palette_uv_colors: Vec<[u16; 8]>,
4947 left_palette_uv_colors: Vec<[u16; 8]>,
4948 /// This tile's own top-left corner, in 4x4 mode-info units (spec
4949 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
4950 /// neighbour" check compares against this instead of literal `0`, since a
4951 /// block at the tile's own top/left edge has no usable neighbour even
4952 /// though a decoded block sits there in the picture (spec `decode_tile`'s
4953 /// per-tile `clear_above_context`/`left_available`/`up_available`).
4954 /// `0` for a single-tile frame, matching every existing caller exactly.
4955 tile_row0_mi: usize,
4956 tile_col0_mi: usize,
4957}
4958
4959impl Neighbours {
4960 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
4961 /// true (unpadded) size in 4x4 mode-info units.
4962 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
4963 // lane-sb128c r7: a 128x64 block at the bottom frame edge records its
4964 // neighbour state over the whole 64-row extent, past the frame's last
4965 // mi row (mi_rows 198, block rows 192..208). libaom's own context
4966 // buffers are superblock-aligned for exactly that reason
4967 // (`av1_alloc_context_buffers` rounds to `MAX_MIB_SIZE`), so pad the
4968 // side arrays to a superblock multiple and leave those cells unread --
4969 // every availability check uses the true `mi_rows`/`mi_cols` below.
4970 let sb_sub = (sb_mi_cur() as usize) / (SUB / MI);
4971 let (cols, rows) = (
4972 cols.next_multiple_of(sb_sub),
4973 rows.next_multiple_of(sb_sub),
4974 );
4975 Self {
4976 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
4977 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
4978 above_mode: vec![DC_PRED; cols],
4979 left_mode: vec![DC_PRED; rows],
4980 above_uv_mode: vec![DC_PRED; cols],
4981 left_uv_mode: vec![DC_PRED; rows],
4982 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
4983 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
4984 above_side_mi: vec![NO_NEIGHBOUR_SIDE; cols * (SUB / MI)],
4985 left_side_mi: vec![NO_NEIGHBOUR_SIDE; rows * (SUB / MI)],
4986 sub8_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],
4987 sub8_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)],
4988 uv_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],
4989 uv_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)],
4990 uv_mode_grid: vec![u8::MAX; cols * (SUB / MI) * rows * (SUB / MI)],
4991 uv_grid_cols: cols * (SUB / MI),
4992 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
4993 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
4994 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
4995 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
4996 // 16x16 block beside it, which a SUB-grid slot cannot name
4997 // (class context-read-from-one-cell).
4998 above_skip: vec![false; cols * (SUB / MI)],
4999 left_skip: vec![false; rows * (SUB / MI)],
5000 above_skip_mode: vec![false; cols * (SUB / MI)],
5001 left_skip_mode: vec![false; rows * (SUB / MI)],
5002 above_inter: vec![false; cols * (SUB / MI)],
5003 left_inter: vec![false; rows * (SUB / MI)],
5004 above_ref: vec![-1; cols * (SUB / MI)],
5005 left_ref: vec![-1; rows * (SUB / MI)],
5006 above_ref1: vec![None; cols * (SUB / MI)],
5007 left_ref1: vec![None; rows * (SUB / MI)],
5008 above_comp_group_idx: vec![0; cols * (SUB / MI)],
5009 left_comp_group_idx: vec![0; rows * (SUB / MI)],
5010 above_compound_idx: vec![0; cols * (SUB / MI)],
5011 left_compound_idx: vec![0; rows * (SUB / MI)],
5012 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
5013 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
5014 mi_cols,
5015 mi_rows,
5016 skip_grid: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
5017 skip_written: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
5018 blk_org_grid: vec![[0u16; 2]; cols * (SUB / MI) * rows * (SUB / MI)],
5019 blk_dim_grid: vec![[1u8; 2]; cols * (SUB / MI) * rows * (SUB / MI)],
5020 skip_grid_cols_mi: cols * (SUB / MI),
5021 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
5022 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
5023 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
5024 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
5025 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
5026 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
5027 above_palette_size: vec![0; cols * (SUB / MI)],
5028 left_palette_size: vec![0; rows * (SUB / MI)],
5029 above_palette_colors: vec![[0u16; 8]; cols * (SUB / MI)],
5030 left_palette_colors: vec![[0u16; 8]; rows * (SUB / MI)],
5031 above_palette_uv_size: vec![0; cols * (SUB / MI)],
5032 left_palette_uv_size: vec![0; rows * (SUB / MI)],
5033 above_palette_uv_colors: vec![[0u16; 8]; cols * (SUB / MI)],
5034 left_palette_uv_colors: vec![[0u16; 8]; rows * (SUB / MI)],
5035 tile_row0_mi: 0,
5036 tile_col0_mi: 0,
5037 }
5038 }
5039
5040 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
5041 /// tile's own column span (`col1_mi` exclusive), plus recording
5042 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
5043 /// availability check below. Left context resets every superblock row
5044 /// regardless of tile ([`Self::start_row`], already called once per SB
5045 /// row by every caller) so it needs no tile-specific reset here.
5046 fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize) {
5047 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
5048 // are tile-relative, same as every other neighbour lookup here.
5049 SEG_TILE_ORIGIN.with(|c| c.set((row0_mi, col0_mi)));
5050 self.tile_row0_mi = row0_mi;
5051 self.tile_col0_mi = col0_mi;
5052 let end = col1_mi.min(self.above.len());
5053 for i in col0_mi.min(end)..end {
5054 self.above[i] = Default::default();
5055 self.above_side_mi[i] = NO_NEIGHBOUR_SIDE;
5056 }
5057 let (sc0, sc1) = (
5058 col0_mi / (SUB / MI),
5059 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
5060 );
5061 for i in sc0.min(sc1)..sc1 {
5062 self.above_mode[i] = DC_PRED;
5063 self.above_side[i] = NO_NEIGHBOUR_SIDE;
5064 }
5065 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
5066 // the tile's own mi column span directly.
5067 let mend = col1_mi.min(self.above_skip.len());
5068 for i in col0_mi.min(mend)..mend {
5069 self.above_skip[i] = false;
5070 self.above_skip_mode[i] = false;
5071 self.above_inter[i] = false;
5072 self.above_ref[i] = -1;
5073 self.above_ref1[i] = None;
5074 self.above_comp_group_idx[i] = 0;
5075 self.above_compound_idx[i] = 0;
5076 self.above_filter[i] = [3u8; 2];
5077 }
5078 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
5079 // stale `(row, mode)` from the tile to the LEFT names an mi row this
5080 // tile's first block would read as its own above neighbour.
5081 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
5082 for i in col0_mi.min(mcol_end)..mcol_end {
5083 self.sub8_mode_col[i] = (usize::MAX, 0);
5084 self.uv_mode_col[i] = (usize::MAX, 0);
5085 }
5086 // lane-mergefix r2: `av1_zero_above_context` also memsets the txfm row
5087 // over the tile's own column span (to `tx_size_wide[TX_SIZES_LARGEST]`,
5088 // not zero) -- without it a second tile column reads the first one's
5089 // resolved transform sizes as its own above context.
5090 let tend = col1_mi.min(self.above_txfm.len());
5091 for i in col0_mi.min(tend)..tend {
5092 self.above_txfm[i] = TXFM_CTX_INIT;
5093 }
5094 }
5095
5096 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
5097 /// for a non-palette block, clearing any stale neighbour state) into every
5098 /// [`SUB`]-grid cell it covers on both the above and left edges --
5099 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
5100 /// call sites are all square blocks).
5101 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
5102 self.record_palette_y_rect((at.0 * (SUB / MI), at.1 * (SUB / MI)), side, side, size, colors);
5103 }
5104
5105 /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
5106 /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
5107 /// [`Self::record`]): a true rect strip's above/left neighbour spans
5108 /// differ.
5109 fn record_palette_y_rect(
5110 &mut self,
5111 mi: (usize, usize),
5112 w: usize,
5113 h: usize,
5114 size: usize,
5115 colors: [u16; 8],
5116 ) {
5117 let (r, c) = mi;
5118 if crate::envflags::env_flag!("EC_PALPUB") {
5119 eprintln!("EC_PALPUB yrect mi={r},{c} bw={w} bh={h} y={size}");
5120 }
5121 // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size`
5122 // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi
5123 // cell immediately left of the block, not its 16px [`SUB`] cell. The
5124 // old SUB grid let a 16x8 strip pair share one slot, so the second
5125 // strip of mi(0,8) read the FIRST strip's palette size and the colour
5126 // cache came out one entry short (class [[context-read-from-one-cell]]).
5127 for cell in 0..(w / MI).max(1) {
5128 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
5129 *e = size;
5130 self.above_palette_colors[c + cell] = colors;
5131 }
5132 }
5133 for cell in 0..(h / MI).max(1) {
5134 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
5135 *e = size;
5136 self.left_palette_colors[r + cell] = colors;
5137 }
5138 }
5139 }
5140
5141 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
5142 /// neighbours that are themselves a palette-Y block, plus
5143 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
5144 /// cache (pred_common.c:73).
5145 ///
5146 /// The SB-top-row exclusion of the above neighbour (`row % 64` in
5147 /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
5148 /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
5149 /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
5150 /// the ctx too made every superblock in the frame's second SB row read
5151 /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
5152 /// palette block decoded as "no palette" and the tile desynced from
5153 /// there (class [[cdf-row-held-constant]]).
5154 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
5155 self.palette_ctx_and_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
5156 }
5157
5158 /// [`Self::palette_ctx_and_cache`] with the block's REAL mi row, which a
5159 /// 1:4 strip does not share with its [`SUB`] cell: `av1_get_palette_cache`
5160 /// drops the above neighbour on a 64-px superblock boundary
5161 /// (pred_common.c:76, `row % (1 << MIN_SB_SIZE_LOG2)` with `row` the
5162 /// block's own PIXEL row), and strip 1 of a HORZ_4 sits 8 px into the
5163 /// cell -- reading `at.0 % 4` there excludes strip 0 from the cache of
5164 /// every strip in an SB's top cell row, which libaom does not do.
5165 fn palette_ctx_and_cache_mi(&self, mi: (usize, usize)) -> (usize, Vec<u16>) {
5166 let (r, c) = mi;
5167 let above_ok = r % 16 != 0;
5168 // `xd->above_mbmi` exists for every row but the tile's own first.
5169 let above_is_palette = r > self.tile_row0_mi && self.above_palette_size[c] > 0;
5170 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
5171 (self.above_palette_size[c], self.above_palette_colors[c])
5172 } else {
5173 (0, [0u16; 8])
5174 };
5175 // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which
5176 // is NULL whenever the block sits at its TILE's own left column
5177 // (`left_available`), not the frame's -- without this guard a second
5178 // tile column reads the previous tile's palette colours into its cache
5179 // and its `palette_y_mode` ctx.
5180 let left_ok = c > self.tile_col0_mi;
5181 let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 {
5182 (self.left_palette_size[r], self.left_palette_colors[r])
5183 } else {
5184 (0, [0u16; 8])
5185 };
5186 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
5187 let mut cache = Vec::with_capacity(16);
5188 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
5189 if cache.last() != Some(&v) {
5190 cache.push(v);
5191 }
5192 };
5193 let (mut ai, mut li) = (0usize, 0usize);
5194 while ai < above_n && li < left_n {
5195 let (va, vl) = (above_colors[ai], left_colors[li]);
5196 if vl < va {
5197 push_dedup(&mut cache, vl);
5198 li += 1;
5199 } else {
5200 push_dedup(&mut cache, va);
5201 ai += 1;
5202 if vl == va {
5203 li += 1;
5204 }
5205 }
5206 }
5207 while ai < above_n {
5208 push_dedup(&mut cache, above_colors[ai]);
5209 ai += 1;
5210 }
5211 while li < left_n {
5212 push_dedup(&mut cache, left_colors[li]);
5213 li += 1;
5214 }
5215 (ctx, cache)
5216 }
5217
5218 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
5219 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
5220 /// same way (lane-palette2 r1).
5221 fn record_palette_uv(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
5222 self.record_palette_uv_rect(
5223 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
5224 side,
5225 side,
5226 size,
5227 colors,
5228 );
5229 }
5230
5231 /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
5232 /// extents, in LUMA pixels (lane-palette2 r4, same convention as
5233 /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
5234 /// luma resolution regardless of which plane the recorded state is for).
5235 fn record_palette_uv_rect(
5236 &mut self,
5237 mi: (usize, usize),
5238 w: usize,
5239 h: usize,
5240 size: usize,
5241 colors: [u16; 8],
5242 ) {
5243 let (r, c) = mi;
5244 // mi granularity, see [`Self::record_palette_y_rect`].
5245 for cell in 0..(w / MI).max(1) {
5246 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
5247 *e = size;
5248 self.above_palette_uv_colors[c + cell] = colors;
5249 }
5250 }
5251 for cell in 0..(h / MI).max(1) {
5252 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
5253 *e = size;
5254 self.left_palette_uv_colors[r + cell] = colors;
5255 }
5256 }
5257 }
5258
5259 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
5260 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
5261 /// no neighbour lookup at all (it is this block's own just-decided Y
5262 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
5263 /// so only the cache is wanted here.
5264 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
5265 self.palette_uv_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
5266 }
5267
5268 /// [`Self::palette_uv_cache`] with the block's real mi row -- see
5269 /// [`Self::palette_ctx_and_cache_mi`].
5270 fn palette_uv_cache_mi(&self, mi: (usize, usize)) -> Vec<u16> {
5271 let (r, c) = mi;
5272 let above_ok = r % 16 != 0;
5273 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
5274 (self.above_palette_uv_size[c], self.above_palette_uv_colors[c])
5275 } else {
5276 (0, [0u16; 8])
5277 };
5278 // Same tile-relative left availability as the luma cache above.
5279 let left_ok = c > self.tile_col0_mi;
5280 let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 {
5281 (self.left_palette_uv_size[r], self.left_palette_uv_colors[r])
5282 } else {
5283 (0, [0u16; 8])
5284 };
5285 let mut cache = Vec::with_capacity(16);
5286 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
5287 if cache.last() != Some(&v) {
5288 cache.push(v);
5289 }
5290 };
5291 let (mut ai, mut li) = (0usize, 0usize);
5292 while ai < above_n && li < left_n {
5293 let (va, vl) = (above_colors[ai], left_colors[li]);
5294 if vl < va {
5295 push_dedup(&mut cache, vl);
5296 li += 1;
5297 } else {
5298 push_dedup(&mut cache, va);
5299 ai += 1;
5300 if vl == va {
5301 li += 1;
5302 }
5303 }
5304 }
5305 while ai < above_n {
5306 push_dedup(&mut cache, above_colors[ai]);
5307 ai += 1;
5308 }
5309 while li < left_n {
5310 push_dedup(&mut cache, left_colors[li]);
5311 li += 1;
5312 }
5313 cache
5314 }
5315
5316 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
5317 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
5318 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
5319 /// units as [`Self::fill_skip_grid`].
5320 fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8) {
5321 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame);
5322 }
5323
5324 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
5325 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
5326 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
5327 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
5328 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
5329 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
5330 /// libaom `set_one_param_for_line_luma`/`_chroma`: an edge that is a
5331 /// transform-unit edge but NOT a prediction-unit edge is not filtered when
5332 /// `curr_skipped = mbmi->skip_txfm && is_inter_block(mbmi)`. Widening this
5333 /// block's published transform extent to its own size is exactly that
5334 /// suppression for the deblocker's `x0 % tx != 0` test -- the only shape
5335 /// that needs it is the 128 root, whose chroma extent (64) is the one
5336 /// [`Self::fill_lf_grid_rect`]'s TX_32X32 cap narrows. An INTRA block is
5337 /// never suppressed (libaom's `is_inter_block` term), so this is called
5338 /// only from the skipped-inter branch.
5339 fn suppress_internal_lf_edges(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize) {
5340 let (mi_r, mi_c) = at_mi;
5341 let (uv_w, uv_h) = ((w_mi * MI / 2).max(4) as u8, (h_mi * MI / 2).max(4) as u8);
5342 for rr in 0..h_mi {
5343 for cc in 0..w_mi {
5344 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
5345 if let Some(cell) = self.uv_tx_grid.get_mut(idx) {
5346 *cell = uv_w;
5347 }
5348 if let Some(cell) = self.uv_tx_h_grid.get_mut(idx) {
5349 *cell = uv_h;
5350 }
5351 }
5352 }
5353 }
5354
5355 fn fill_lf_grid_rect(
5356 &mut self,
5357 at_mi: (usize, usize),
5358 w_mi: usize,
5359 h_mi: usize,
5360 tx_px: u8,
5361 tx_h_px: u8,
5362 ref_frame: i8,
5363 ) {
5364 let (mi_r, mi_c) = at_mi;
5365 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
5366 // half its luma one (min 4 px, the smallest transform), capped at
5367 // TX_32X32 -- independent of this block's luma `tx_depth`.
5368 let uv_tx_w = ((w_mi * MI / 2).max(4).min(32)) as u8;
5369 let uv_tx_h = ((h_mi * MI / 2).max(4).min(32)) as u8;
5370 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
5371 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}");
5372 }
5373 let cur = CURRENT_DELTA_LF.with(|c| c.get());
5374 let snapshot: [i8; 4] = if DELTA_LF_MULTI.with(|c| c.get()) {
5375 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
5376 } else {
5377 [cur[0].clamp(-63, 63) as i8; 4]
5378 };
5379 for rr in 0..h_mi {
5380 for cc in 0..w_mi {
5381 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
5382 if let Some(cell) = self.tx_grid.get_mut(idx) {
5383 *cell = tx_px;
5384 }
5385 if let Some(cell) = self.tx_h_grid.get_mut(idx) {
5386 *cell = tx_h_px;
5387 }
5388 if let Some(cell) = self.uv_tx_grid.get_mut(idx) {
5389 *cell = uv_tx_w;
5390 }
5391 if let Some(cell) = self.uv_tx_h_grid.get_mut(idx) {
5392 *cell = uv_tx_h;
5393 }
5394 if let Some(cell) = self.ref_grid.get_mut(idx) {
5395 *cell = ref_frame;
5396 }
5397 if let Some(cell) = self.delta_lf_grid.get_mut(idx) {
5398 *cell = snapshot;
5399 }
5400 }
5401 }
5402 }
5403
5404 /// One var-tx / split-tx LEAF's own LUMA transform dims over its mi span.
5405 /// libaom `get_transform_size` (av1_loopfilter.c:207) applies the split
5406 /// override only `if ((plane == AOM_PLANE_Y) && ...)` -- chroma keeps
5407 /// `av1_get_max_uv_txsize(mbmi->bsize)`, the whole BLOCK's uv transform.
5408 /// Routing a leaf through [`Self::fill_lf_grid_rect`] recomputed the uv
5409 /// dims from the LEAF span and so invented chroma transform edges the
5410 /// deblocker then filtered (lane-golomb r6). `ref_grid`/`delta_lf_grid`
5411 /// are already correct from the block's own fill over the same span.
5412 fn fill_lf_grid_leaf_luma(
5413 &mut self,
5414 at_mi: (usize, usize),
5415 w_mi: usize,
5416 h_mi: usize,
5417 tx_px: u8,
5418 tx_h_px: u8,
5419 ) {
5420 let (mi_r, mi_c) = at_mi;
5421 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
5422 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}");
5423 }
5424 for rr in 0..h_mi {
5425 for cc in 0..w_mi {
5426 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
5427 if let Some(cell) = self.tx_grid.get_mut(idx) {
5428 *cell = tx_px;
5429 }
5430 if let Some(cell) = self.tx_h_grid.get_mut(idx) {
5431 *cell = tx_h_px;
5432 }
5433 }
5434 }
5435 }
5436
5437 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
5438 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
5439 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
5440 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
5441 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
5442 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
5443 }
5444
5445 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
5446 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
5447 let (mi_r, mi_c) = at_mi;
5448 if skip && w_mi != h_mi {
5449 RECT_SKIP_BAND_HITS.with(|c| c.set(c.get() + 1));
5450 }
5451 for rr in 0..h_mi {
5452 for cc in 0..w_mi {
5453 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
5454 if let Some(cell) = self.skip_grid.get_mut(idx) {
5455 *cell = skip;
5456 }
5457 if let Some(cell) = self.skip_written.get_mut(idx) {
5458 *cell = true;
5459 }
5460 if let Some(org) = self.blk_org_grid.get_mut(idx) {
5461 *org = [mi_r as u16, mi_c as u16];
5462 }
5463 if let Some(dim) = self.blk_dim_grid.get_mut(idx) {
5464 *dim = [w_mi as u8, h_mi as u8];
5465 }
5466 }
5467 }
5468 }
5469
5470 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
5471 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
5472 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
5473 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
5474 /// straddle the region with a mix of skip/non-skip blocks).
5475 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
5476 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
5477 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
5478 /// filtered edge's two sides are each exactly one coded block wide.
5479 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
5480 self.skip_grid
5481 .get(mi_r * self.skip_grid_cols_mi + mi_c)
5482 .copied()
5483 .unwrap_or(false)
5484 }
5485
5486 /// The `skip_txfm` context of a block whose top-left mi cell is
5487 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
5488 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
5489 /// with an absent neighbour contributing 0. The mi grid is per tile, so
5490 /// row/column 0 is a tile edge and has no neighbour on that axis.
5491 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
5492 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
5493 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
5494 }
5495
5496 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
5497 (0..2).all(|rr| {
5498 (0..2).all(|cc| {
5499 self.skip_grid
5500 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
5501 .copied()
5502 .unwrap_or(false)
5503 })
5504 })
5505 }
5506
5507 fn start_row(&mut self) {
5508 self.left.iter_mut().for_each(|l| *l = Default::default());
5509 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
5510 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
5511 self.left_side.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
5512 self.left_side_mi.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
5513 self.left_skip.iter_mut().for_each(|s| *s = false);
5514 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
5515 self.left_inter.iter_mut().for_each(|i| *i = false);
5516 self.left_ref.iter_mut().for_each(|r| *r = -1);
5517 self.left_ref1.iter_mut().for_each(|r| *r = None);
5518 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
5519 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
5520 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
5521 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
5522 // context (a tile/SB-row boundary has no left neighbour).
5523 self.sub8_mode_row.iter_mut().for_each(|s| *s = (usize::MAX, 0));
5524 self.uv_mode_row.iter_mut().for_each(|s| *s = (usize::MAX, 0));
5525 // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands
5526 // are per-mi maps like every other one here, so they reset with the
5527 // row too -- the left guard above is what actually stops a cross-tile
5528 // read, this keeps a stale colour out of the arrays at all.
5529 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
5530 self.left_palette_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
5531 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
5532 self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
5533 // lane-mergefix r2: `av1_zero_left_context` memsets
5534 // `left_txfm_context_buffer` to `tx_size_high[TX_SIZES_LARGEST]` at
5535 // every superblock row of every tile -- the var-tx left context does
5536 // NOT carry over a tile boundary (its `txfm_partition` ctx read the
5537 // previous tile column's last block otherwise).
5538 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
5539 }
5540
5541 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
5542 /// block that reads it as a neighbour -- [`crate::tile`]'s
5543 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
5544 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
5545 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
5546 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
5547 /// the real value, not just `is_inter`).
5548 fn record_inter(
5549 &mut self,
5550 at: (usize, usize),
5551 side: usize,
5552 skip: bool,
5553 is_inter: bool,
5554 ref_frame: i8,
5555 filter: [u8; 2],
5556 skip_mode: bool,
5557 ) {
5558 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
5559 }
5560
5561 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
5562 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
5563 /// r1: a true rectangular strip's above-context span (its own width) and
5564 /// left-context span (its own height) differ, unlike every caller before
5565 /// this round (class neighbour-votes-all-its-fields).
5566 #[allow(clippy::too_many_arguments)]
5567 fn record_inter_rect(
5568 &mut self,
5569 at: (usize, usize),
5570 w_sub: usize,
5571 h_sub: usize,
5572 skip: bool,
5573 is_inter: bool,
5574 ref_frame: i8,
5575 filter: [u8; 2],
5576 skip_mode: bool,
5577 ) {
5578 let (r, c) = at;
5579 self.record_inter_rect_mi(
5580 (r * (SUB / MI), c * (SUB / MI)),
5581 w_sub / MI,
5582 h_sub / MI,
5583 skip,
5584 is_inter,
5585 ref_frame,
5586 filter,
5587 skip_mode,
5588 );
5589 }
5590
5591 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
5592 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
5593 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
5594 /// routes through the wrapper above.
5595 #[allow(clippy::too_many_arguments)]
5596 fn record_inter_rect_mi(
5597 &mut self,
5598 at_mi: (usize, usize),
5599 w_mi: usize,
5600 h_mi: usize,
5601 skip: bool,
5602 is_inter: bool,
5603 ref_frame: i8,
5604 filter: [u8; 2],
5605 skip_mode: bool,
5606 ) {
5607 let (r, c) = at_mi;
5608 // lane-t900 r8 (class new-map-ignores-tile-edge's twin: a map NOBODY
5609 // writes for a whole block class): an INTER block left the luma mode
5610 // map untouched, so a later intra block's `get_intra_edge_filter_type`
5611 // (spec 7.11.2, libaom `reconintra.h`'s `is_smooth`) fell back to the
5612 // coarse SUB-row band, which still held a SMOOTH mode from an earlier
5613 // block in that pixel row -- the directional edge filter then ran at
5614 // strength 3 instead of 2. libaom reads `mbmi->mode` of the neighbour,
5615 // which for an inter block is an INTER mode (>= NEARESTMV) and is
5616 // never smooth; DC_PRED is this map's equivalent (the sub-8x8 groups
5617 // already stamped it).
5618 // The chroma twin: `is_smooth(mbmi, plane > 0)` returns 0 outright for
5619 // an inter neighbour ("uv_mode is not set for inter blocks"), so the
5620 // uv map must read DC_PRED over an inter block's cells too.
5621 if is_inter {
5622 self.record_mode_mi(r, c, w_mi, h_mi, DC_PRED);
5623 self.record_uv_mode_mi(r, c, w_mi, h_mi, DC_PRED);
5624 }
5625 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
5626 for cell in 0..w_mi {
5627 self.above_skip[c + cell] = skip;
5628 self.above_skip_mode[c + cell] = skip_mode;
5629 self.above_inter[c + cell] = is_inter;
5630 self.above_ref[c + cell] = ref_frame;
5631 // lane-av1comp: no caller of `record_inter` ever decodes a
5632 // compound block yet (see [`Self::above_ref1`]'s doc); the
5633 // parameter this becomes lands with `read_ref_frames`.
5634 self.above_ref1[c + cell] = None;
5635 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
5636 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
5637 // as `3`/`1` even though this block has no second reference.
5638 // `record_compound_ctx` overwrites this with the real bit for an
5639 // actual compound block's cells, called right after this one.
5640 self.above_comp_group_idx[c + cell] = if altref { 3 } else { 0 };
5641 self.above_compound_idx[c + cell] = u8::from(altref);
5642 self.above_filter[c + cell] = filter;
5643 }
5644 for cell in 0..h_mi {
5645 self.left_skip[r + cell] = skip;
5646 self.left_skip_mode[r + cell] = skip_mode;
5647 self.left_inter[r + cell] = is_inter;
5648 self.left_ref[r + cell] = ref_frame;
5649 self.left_ref1[r + cell] = None;
5650 self.left_comp_group_idx[r + cell] = if altref { 3 } else { 0 };
5651 self.left_compound_idx[r + cell] = u8::from(altref);
5652 self.left_filter[r + cell] = filter;
5653 }
5654 }
5655
5656 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
5657 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
5658 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
5659 /// `get_comp_index_context`) -- called right after `record_inter` for
5660 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
5661 /// stamps `above_ref1`/`left_ref1` with the block's real second
5662 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
5663 /// this is the one caller that actually knows it) -- so the next block's
5664 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
5665 /// neighbour instead of `record_inter`'s single-ref default.
5666 fn record_compound_ctx(
5667 &mut self,
5668 at: (usize, usize),
5669 side: usize,
5670 ref1: i8,
5671 comp_group_idx: u8,
5672 compound_idx: u8,
5673 ) {
5674 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
5675 }
5676
5677 /// [`Self::record_compound_ctx`] with independent above/left extents,
5678 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
5679 #[allow(clippy::too_many_arguments)]
5680 fn record_compound_ctx_rect(
5681 &mut self,
5682 at: (usize, usize),
5683 w_sub: usize,
5684 h_sub: usize,
5685 ref1: i8,
5686 comp_group_idx: u8,
5687 compound_idx: u8,
5688 ) {
5689 let (r, c) = at;
5690 self.record_compound_ctx_rect_mi(
5691 (r * (SUB / MI), c * (SUB / MI)),
5692 w_sub / MI,
5693 h_sub / MI,
5694 ref1,
5695 comp_group_idx,
5696 compound_idx,
5697 );
5698 }
5699
5700 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
5701 /// [`Self::record_inter_rect_mi`]).
5702 fn record_compound_ctx_rect_mi(
5703 &mut self,
5704 at_mi: (usize, usize),
5705 w_mi: usize,
5706 h_mi: usize,
5707 ref1: i8,
5708 comp_group_idx: u8,
5709 compound_idx: u8,
5710 ) {
5711 let (r, c) = at_mi;
5712 for cell in 0..w_mi {
5713 self.above_ref1[c + cell] = Some(ref1);
5714 self.above_comp_group_idx[c + cell] = comp_group_idx;
5715 self.above_compound_idx[c + cell] = compound_idx;
5716 }
5717 for cell in 0..h_mi {
5718 self.left_ref1[r + cell] = Some(ref1);
5719 self.left_comp_group_idx[r + cell] = comp_group_idx;
5720 self.left_compound_idx[r + cell] = compound_idx;
5721 }
5722 }
5723
5724 /// The context of a block's partition symbol: delegates to the mi-precise
5725 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
5726 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
5727 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
5728 /// only touches the finer mi arrays -- leaves them stale for the *next*
5729 /// sibling's own partition symbol.
5730 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
5731 let (r, c) = at;
5732 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
5733 }
5734
5735 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
5736 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
5737 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
5738 /// than the enclosing 16x16 slot's stale, shared state.
5739 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
5740 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side)
5741 + usize::from(self.above_side_mi[mi_c] * 2 <= side)
5742 }
5743
5744 /// The gathered coded/DC-sign state of the blocks above and to the left
5745 /// of a block `side` samples across, per plane.
5746 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
5747 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
5748 }
5749
5750 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
5751 /// units, for the same reason [`Self::record_mi`] does.
5752 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
5753 let side_mi = side / MI;
5754 std::array::from_fn(|plane| {
5755 let mut above_coded = false;
5756 let mut left_coded = false;
5757 let mut vote = 0;
5758 for cell in 0..side_mi {
5759 let above = &self.above[mi_c + cell][plane];
5760 let left = &self.left[mi_r + cell][plane];
5761 above_coded |= above.level != 0;
5762 left_coded |= left.level != 0;
5763 vote += dc_vote(above.dc) + dc_vote(left.dc);
5764 }
5765 (above_coded, left_coded, vote)
5766 })
5767 }
5768
5769 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
5770 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
5771 /// extent pattern for a true rectangular strip's own coefficient context.
5772 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
5773 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
5774 }
5775
5776 /// [`Self::around_rect`] taking the block's position directly in 4x4
5777 /// mode-info units, mirroring [`Self::around_mi`].
5778 fn around_mi_rect(&self, (mi_r, mi_c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
5779 let (w_mi, h_mi) = (w / MI, h / MI);
5780 std::array::from_fn(|plane| {
5781 let mut above_coded = false;
5782 let mut left_coded = false;
5783 let mut vote = 0;
5784 for cell in 0..w_mi {
5785 let above = &self.above[mi_c + cell][plane];
5786 above_coded |= above.level != 0;
5787 vote += dc_vote(above.dc);
5788 }
5789 for cell in 0..h_mi {
5790 let left = &self.left[mi_r + cell][plane];
5791 left_coded |= left.level != 0;
5792 vote += dc_vote(left.dc);
5793 }
5794 if crate::envflags::env_flag!("EC_DCDUMP") {
5795 let ab: Vec<String> = (0..w_mi)
5796 .map(|k| format!("{:?}/{}", self.above[mi_c + k][plane].dc, self.above[mi_c + k][plane].level))
5797 .collect();
5798 let lf: Vec<String> = (0..h_mi)
5799 .map(|k| format!("{:?}/{}", self.left[mi_r + k][plane].dc, self.left[mi_r + k][plane].level))
5800 .collect();
5801 eprintln!("EC_DCDUMP mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]", ab.join(","), lf.join(","));
5802 }
5803 (above_coded, left_coded, vote)
5804 })
5805 }
5806
5807 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
5808 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
5809 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
5810 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
5811 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
5812 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
5813 /// is always 0, spec's `plane_bsize == tx_size` branch).
5814 fn luma_skip_ctx(&self, at_mi: (usize, usize), side_mi: usize) -> usize {
5815 self.luma_skip_ctx_rect(at_mi, side_mi, side_mi)
5816 }
5817
5818 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi
5819 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above
5820 /// context over `tx_size_wide` and the left one over `tx_size_high`.
5821 fn luma_skip_ctx_rect(
5822 &self,
5823 (mi_r, mi_c): (usize, usize),
5824 w_mi: usize,
5825 h_mi: usize,
5826 ) -> usize {
5827 let side_mi = w_mi;
5828 let mut top = 0u8;
5829 let mut left = 0u8;
5830 for cell in 0..w_mi {
5831 top |= self.above[mi_c + cell][0].level;
5832 }
5833 for cell in 0..h_mi {
5834 left |= self.left[mi_r + cell][0].level;
5835 }
5836 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
5837 if crate::envflags::env_flag!("EC_ECDUMP") {
5838 let ab: Vec<String> =
5839 (0..w_mi).map(|k| self.above[mi_c + k][0].level.to_string()).collect();
5840 let lf: Vec<String> =
5841 (0..h_mi).map(|k| self.left[mi_r + k][0].level.to_string()).collect();
5842 eprintln!(
5843 "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},]",
5844 ab.join(","), lf.join(",")
5845 );
5846 }
5847 if crate::envflags::env_flag!("EC_AV1_TRACE") {
5848 eprintln!(
5849 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx} band={:?}",
5850 self.left.iter().map(|e| e[0].level).collect::<Vec<_>>()
5851 );
5852 }
5853 ctx
5854 }
5855
5856 /// Writes one coded block into every cell it covers, on both grids: the
5857 /// mode/side arrays up to `side`'s own width, and the coefficient-context
5858 /// arrays up to the true frame edge — the units past it are left at their
5859 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
5860 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
5861 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
5862 /// not from this block's own side).
5863 fn record(
5864 &mut self,
5865 at: (usize, usize),
5866 side: usize,
5867 mode: usize,
5868 uv_mode: usize,
5869 grids: &[Vec<i32>; 3],
5870 ) {
5871 self.record_rect(at, side, side, mode, uv_mode, grids);
5872 }
5873
5874 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
5875 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
5876 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
5877 /// spec's per-edge partition-context rule, so a true rectangular block
5878 /// naturally wants two different values here rather than one.
5879 /// Writes this block's luma `mode` into the mi-granular
5880 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
5881 /// position a *later* neighbour would read it from: the block's LAST mi
5882 /// row for every column it spans (what the block below reads via
5883 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
5884 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
5885 /// read these back, and only when the recorded position is exactly their
5886 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
5887 fn record_mode_mi(
5888 &mut self,
5889 mi_r: usize,
5890 mi_c: usize,
5891 mi_w: usize,
5892 mi_h: usize,
5893 mode: usize,
5894 ) {
5895 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
5896 for cell in 0..mi_w {
5897 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
5898 *slot = (last_r, mode);
5899 }
5900 }
5901 for cell in 0..mi_h {
5902 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
5903 *slot = (last_c, mode);
5904 }
5905 }
5906 }
5907
5908 /// The mi-exact above/left neighbour luma mode for a block whose top-left
5909 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
5910 /// mi position (then the coarse [`SUB`]-grid slot is right by
5911 /// construction). See [`Self::record_mode_mi`].
5912 fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
5913 match self.sub8_mode_col.get(mi_c) {
5914 Some(&(row, m)) if mi_r > self.tile_row0_mi && row == mi_r - 1 => Some(m),
5915 _ => None,
5916 }
5917 }
5918
5919 fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
5920 match self.sub8_mode_row.get(mi_r) {
5921 Some(&(col, m)) if mi_c > self.tile_col0_mi && col == mi_c - 1 => Some(m),
5922 _ => None,
5923 }
5924 }
5925
5926 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
5927 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
5928 fn record_uv_mode_mi(
5929 &mut self,
5930 mi_r: usize,
5931 mi_c: usize,
5932 mi_w: usize,
5933 mi_h: usize,
5934 uv_mode: usize,
5935 ) {
5936 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
5937 for cell in 0..mi_w {
5938 if let Some(slot) = self.uv_mode_col.get_mut(mi_c + cell) {
5939 *slot = (last_r, uv_mode);
5940 }
5941 }
5942 for cell in 0..mi_h {
5943 if let Some(slot) = self.uv_mode_row.get_mut(mi_r + cell) {
5944 *slot = (last_c, uv_mode);
5945 }
5946 }
5947 // libaom writes one `MB_MODE_INFO` pointer into every mi cell a block
5948 // covers, so the chroma neighbour read below is a plain grid read.
5949 let stride = self.uv_grid_cols;
5950 for row in mi_r..=last_r {
5951 for col in mi_c..=last_c {
5952 if col < stride
5953 && let Some(cell) = self.uv_mode_grid.get_mut(row * stride + col)
5954 {
5955 *cell = uv_mode as u8;
5956 }
5957 }
5958 }
5959 }
5960
5961 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
5962 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
5963 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
5964 /// block has recorded the exact neighbouring mi.
5965 fn smooth_uv_neighbour(&self, mi_r: usize, mi_c: usize, r: usize, c: usize) -> bool {
5966 // lane-kf900 r2: libaom reads the chroma neighbours off the CHROMA
5967 // REFERENCE block, not off the mi that carries the chroma syntax.
5968 // `set_mi_row_col` (`blockd.h`) takes
5969 // `base_mi = &xd->mi[-(mi_row & ss_y) * stride - (mi_col & ss_x)]` and
5970 // only then `chroma_above_mbmi = base_mi[-stride]` /
5971 // `chroma_left_mbmi = base_mi[-1]`. A sub-8 pair codes its chroma at
5972 // the ODD mi, so without the snap we looked one mi row/column too far
5973 // down/right -- the mi-exact slot never matched and the coarse
5974 // fallback answered instead. Measured on a 4K 10-bit key frame, chroma
5975 // 8x4 at (688, 100) = mi (51, 344): libaom's
5976 // `get_intra_edge_filter_type` is 1 (the chroma block above it is
5977 // `UV_SMOOTH_PRED`), ours was 0, which flips
5978 // `av1_use_intra_edge_upsample(8, 4, -6, type)` (`blk_wh == 12`:
5979 // false for type 1, TRUE for type 0) and upsampled an edge libaom
5980 // leaves alone -- +1 on rows 2/3 of that block and every chroma block
5981 // predicting from it (class `context-read-from-one-cell`).
5982 self.smooth_uv_neighbour_unsnapped(mi_r & !1, mi_c & !1, r, c)
5983 }
5984
5985 /// [`Self::smooth_uv_neighbour`] without the chroma-reference snap, i.e.
5986 /// read off the mi passed in exactly. Only the 16x4/4x16 pair witness
5987 /// counter wants this: it measures how often the snap CHANGES the answer,
5988 /// which is what the lane-kf1200/kf900 chroma-reference fix buys. Every
5989 /// decode path uses the snapping form.
5990 fn smooth_uv_neighbour_unsnapped(
5991 &self,
5992 mi_r: usize,
5993 mi_c: usize,
5994 r: usize,
5995 c: usize,
5996 ) -> bool {
5997 // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the
5998 // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid
5999 // array that `start_tile` does not clear, so a block on a tile's first
6000 // mi row used to read the uv_mode of the block above it in the tile
6001 // ABOVE and filter its chroma edge at that neighbour's strength
6002 // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block
6003 // at chroma (120, 32), the top-right tile's first block).
6004 let have_above = mi_r > self.tile_row0_mi;
6005 let have_left = mi_c > self.tile_col0_mi;
6006 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
6007 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
6008 {
6009 UV_TILE_EDGE_SUPPRESSED_HITS.with(|h| h.set(h.get() + 1));
6010 }
6011 // The mi grid is libaom's own read; the two maps below stay as the
6012 // fallback for cells no block has written (see [`Self::uv_mode_grid`]).
6013 let cell = |grid: &Vec<u8>, row: usize, col: usize| -> Option<usize> {
6014 (col < self.uv_grid_cols)
6015 .then(|| grid.get(row * self.uv_grid_cols + col).copied())
6016 .flatten()
6017 .filter(|&m| m != u8::MAX)
6018 .map(usize::from)
6019 };
6020 let above = match self.uv_mode_col.get(mi_c) {
6021 _ if have_above && let Some(m) = cell(&self.uv_mode_grid, mi_r - 1, mi_c) => m,
6022 Some(&(row, m)) if have_above && row == mi_r - 1 => m,
6023 _ if have_above => self.above_uv_mode[c],
6024 _ => DC_PRED,
6025 };
6026 let left = match self.uv_mode_row.get(mi_r) {
6027 _ if have_left && let Some(m) = cell(&self.uv_mode_grid, mi_r, mi_c - 1) => m,
6028 Some(&(col, m)) if have_left && col == mi_c - 1 => m,
6029 _ if have_left => self.left_uv_mode[r],
6030 _ => DC_PRED,
6031 };
6032 if have_above && cell(&self.uv_mode_grid, mi_r - 1, mi_c).is_some_and(|m| {
6033 !matches!(self.uv_mode_col.get(mi_c), Some(&(row, cm)) if row == mi_r - 1 && cm == m)
6034 }) || have_left && cell(&self.uv_mode_grid, mi_r, mi_c - 1).is_some_and(|m| {
6035 !matches!(self.uv_mode_row.get(mi_r), Some(&(col, cm)) if col == mi_c - 1 && cm == m)
6036 }) {
6037 UV_MODE_GRID_OVERRIDE_HITS.with(|h| h.set(h.get() + 1));
6038 }
6039 // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs
6040 // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would
6041 // have been filtered at the wrong strength by the coarse map alone.
6042 if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] {
6043 UV_MODE_MI_OVERRIDE_HITS.with(|h| h.set(h.get() + 1));
6044 }
6045 if (is_smooth_mode(self.above_uv_mode[c]) && !is_smooth_mode(above))
6046 || (is_smooth_mode(self.left_uv_mode[r]) && !is_smooth_mode(left))
6047 {
6048 INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|h| h.set(h.get() + 1));
6049 }
6050 is_smooth_mode(above) || is_smooth_mode(left)
6051 }
6052
6053 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
6054 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
6055 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
6056 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
6057 /// holding an OLDER, larger block's mode -- it only ever recorded into the
6058 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
6059 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
6060 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
6061 /// a different CDF for the same mode value).
6062 /// lane-rectsplitx r2: availability-correct above/left luma modes for a
6063 /// block whose top-left mi is `(mi_r, mi_c)`. libaom reads `above_mbmi`
6064 /// only when `up_available` and `left_mbmi` only when `left_available`;
6065 /// the coarse [`SUB`] bands cannot express that, and with 8-px strips they
6066 /// actively lie -- four 32x8 strips of one `HORZ_4` share ONE 16x16
6067 /// `left_mode` cell, so the second strip at tile column 0 read the FIRST
6068 /// strip's mode as its "left neighbour" (measured on the band fixture at
6069 /// mi(10,0): mode 2 where libaom has DC, a different `kf_y_mode` row).
6070 fn modes_above_left_mi(
6071 &self,
6072 mi_r: usize,
6073 mi_c: usize,
6074 fallback: (usize, usize),
6075 ) -> (usize, usize) {
6076 let above = if mi_r > self.tile_row0_mi {
6077 self.mode_above_mi(mi_r, mi_c).unwrap_or(fallback.0)
6078 } else {
6079 DC_PRED
6080 };
6081 let left = if mi_c > self.tile_col0_mi {
6082 self.mode_left_mi(mi_r, mi_c).unwrap_or(fallback.1)
6083 } else {
6084 DC_PRED
6085 };
6086 (above, left)
6087 }
6088
6089 /// lane-modectx r1: the coarse-[`SUB`]-grid entry point, now availability
6090 /// correct. The mi-exact lookups already refuse to cross a tile edge, but
6091 /// their FALLBACK (`above_mode`/`left_mode`) did not: `left_mode` is reset
6092 /// per superblock row and never per tile, so the first block column of
6093 /// tile 2..N read the previous tile's mode as its left neighbour, and the
6094 /// above band survives across a tile ROW boundary the same way lane-mtfix's
6095 /// `above_uv_mode` did. libaom reads `above_mbmi`/`left_mbmi` only when
6096 /// `up_available`/`left_available` and uses DC_PRED otherwise
6097 /// ([`Self::modes_above_left_mi`]).
6098 fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
6099 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
6100 let (above, left) =
6101 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));
6102 if above != self.above_mode[c] || left != self.left_mode[r] {
6103 MODE_MI_OVERRIDE_HITS.with(|h| h.set(h.get() + 1));
6104 }
6105 if (is_smooth_mode(self.above_mode[c]) && !is_smooth_mode(above))
6106 || (is_smooth_mode(self.left_mode[r]) && !is_smooth_mode(left))
6107 {
6108 INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|h| h.set(h.get() + 1));
6109 }
6110 // A neighbour the coarse band offered where the tile edge makes it
6111 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).
6112 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)
6113 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)
6114 {
6115 MODE_TILE_EDGE_COARSE_LEAKS.with(|h| h.set(h.get() + 1));
6116 }
6117 (above, left)
6118 }
6119
6120 fn record_rect(
6121 &mut self,
6122 at: (usize, usize),
6123 w: usize,
6124 h: usize,
6125 mode: usize,
6126 uv_mode: usize,
6127 grids: &[Vec<i32>; 3],
6128 ) {
6129 self.record_rect_mi(sub16_to_mi(at), w, h, mode, uv_mode, grids);
6130 }
6131
6132 /// [`Self::record_rect`] in mi (4 px) units -- lane-inter4 r1: a
6133 /// 32x8/8x32 strip of a 32-level 1:4 partition sits at an 8-px offset the
6134 /// [`SUB`]-unit `at` cannot name. The coarse 16-px bands are still keyed
6135 /// by the enclosing cell (a sub-16 extent writes none of them, exactly as
6136 /// the [`SUB`]-unit path does).
6137 fn record_rect_mi(
6138 &mut self,
6139 at_mi: (usize, usize),
6140 w: usize,
6141 h: usize,
6142 mode: usize,
6143 uv_mode: usize,
6144 grids: &[Vec<i32>; 3],
6145 ) {
6146 let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI));
6147 // lane-inter4 r2: a strip whose own footprint runs past the frame's
6148 // last 16-px column/row stamps only the cells that exist (libaom's
6149 // arrays are padded past the frame and those cells are never read).
6150 for cell in 0..w / SUB {
6151 if c + cell >= self.above_mode.len() {
6152 break;
6153 }
6154 self.above_mode[c + cell] = mode;
6155 self.above_uv_mode[c + cell] = uv_mode;
6156 self.above_side[c + cell] = w;
6157 }
6158 for cell in 0..h / SUB {
6159 if r + cell >= self.left_mode.len() {
6160 break;
6161 }
6162 self.left_mode[r + cell] = mode;
6163 self.left_uv_mode[r + cell] = uv_mode;
6164 self.left_side[r + cell] = h;
6165 }
6166 self.record_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, mode);
6167 self.record_uv_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, uv_mode);
6168 self.record_mi_rect(at_mi, w, h, grids);
6169 }
6170
6171 /// The coefficient-context half of [`Self::record`], taking the block's
6172 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
6173 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
6174 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
6175 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
6176 self.record_mi_rect(at_mi, side, side, grids);
6177 }
6178
6179 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
6180 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
6181 fn record_mi_rect(
6182 &mut self,
6183 at_mi: (usize, usize),
6184 w: usize,
6185 h: usize,
6186 grids: &[Vec<i32>; 3],
6187 ) {
6188 let (mi_r, mi_c) = at_mi;
6189 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
6190 let (w_mi, h_mi) = (w / MI, h / MI);
6191 if crate::envflags::env_flag!("EC_ECPUB") {
6192 eprintln!("EC_ECPUB blk mi=({mi_r},{mi_c}) wh=({w},{h}) lvl={}", states[0].level);
6193 }
6194 for cell in 0..h_mi {
6195 if let Some(slot) = self.left_side_mi.get_mut(mi_r + cell) {
6196 *slot = h;
6197 }
6198 }
6199 for cell in 0..w_mi {
6200 if let Some(slot) = self.above_side_mi.get_mut(mi_c + cell) {
6201 *slot = w;
6202 }
6203 }
6204 // A chroma 4x4 unit straddling the true luma edge is still whole in
6205 // chroma's own halved grid, so libaom rounds the luma bound up to the
6206 // plane's own 4x4 unit before clamping a subsampled plane
6207 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
6208 let round_up_even = |n: usize| n.div_ceil(2) * 2;
6209 let bound_h = [
6210 self.mi_rows,
6211 round_up_even(self.mi_rows),
6212 round_up_even(self.mi_rows),
6213 ];
6214 let bound_w = [
6215 self.mi_cols,
6216 round_up_even(self.mi_cols),
6217 round_up_even(self.mi_cols),
6218 ];
6219 for cell in 0..h_mi {
6220 // lane-sb128c r7: a 128x64 at the bottom frame edge names mi rows
6221 // past the padded side arrays (mi_rows 198, block rows 192..208);
6222 // libaom's own arrays are superblock-sized, so those cells simply
6223 // have no reader. Same guard the `left_side_mi` loop above uses.
6224 let Some(left_slot) = self.left.get_mut(mi_r + cell) else {
6225 break;
6226 };
6227 *left_slot = std::array::from_fn(|plane| {
6228 if cell < h_mi.min(bound_h[plane].saturating_sub(mi_r)) {
6229 states[plane]
6230 } else {
6231 Default::default()
6232 }
6233 });
6234 }
6235 for cell in 0..w_mi {
6236 let Some(above_slot) = self.above.get_mut(mi_c + cell) else {
6237 break;
6238 };
6239 *above_slot = std::array::from_fn(|plane| {
6240 if cell < w_mi.min(bound_w[plane].saturating_sub(mi_c)) {
6241 states[plane]
6242 } else {
6243 Default::default()
6244 }
6245 });
6246 }
6247 }
6248
6249 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
6250 /// inside a coded block whose luma transform is smaller than its own
6251 /// side (`TxMode::Select`): the real per-transform-unit coefficient
6252 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
6253 /// coarse per-block `tx_grid`/`fill_lf_grid` state
6254 /// [`Self::record_split_luma`] still writes once for the whole block.
6255 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
6256 /// the caller's own [`Self::record_split_luma`] call sets those once,
6257 /// at the block's own true side, not this TU's.
6258 fn record_mi_luma(&mut self, at_mi: (usize, usize), tx_px: usize, grid: &[i32]) {
6259 self.record_mi_luma_rect(at_mi, tx_px, tx_px, grid);
6260 }
6261
6262 /// [`Self::record_mi_luma`] for ONE CHROMA transform unit of a block whose
6263 /// uv plane block is several units (lane-sb128b r2: a 128x128 block's
6264 /// 64x64 uv plane block is four TX_32X32 units, `av1_get_max_uv_txsize`).
6265 /// `w_px`/`h_px` are the unit's extent in LUMA pixels -- the chroma
6266 /// coefficient-context arrays are indexed by luma mi, the convention
6267 /// [`Self::record_split_luma_rect_mi`] already writes them in, frame-edge
6268 /// clamp included.
6269 fn record_mi_chroma(
6270 &mut self,
6271 (mi_r, mi_c): (usize, usize),
6272 w_px: usize,
6273 h_px: usize,
6274 plane: usize,
6275 grid: &[i32],
6276 ) {
6277 let round_up_even = |n: usize| n.div_ceil(2) * 2;
6278 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
6279 let state = neighbour_state(grid);
6280 for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) {
6281 self.left[mi_r + cell][plane] = state;
6282 }
6283 for cell in 0..(w_px / MI).min(bound_w.saturating_sub(mi_c)) {
6284 self.above[mi_c + cell][plane] = state;
6285 }
6286 }
6287
6288 /// [`Self::record_mi_luma`] for a RECTANGULAR transform unit (lane-rectsplitx
6289 /// r1): the above context spans the unit's width, the left context its
6290 /// height, which for a square unit is the same loop it always was.
6291 fn record_mi_luma_rect(
6292 &mut self,
6293 (mi_r, mi_c): (usize, usize),
6294 w_px: usize,
6295 h_px: usize,
6296 grid: &[i32],
6297 ) {
6298 let state = neighbour_state(grid);
6299 if crate::envflags::env_flag!("EC_ECPUB") {
6300 eprintln!("EC_ECPUB tu mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={}", state.level);
6301 }
6302 for cell in 0..h_px / MI {
6303 if mi_r + cell < self.mi_rows {
6304 self.left[mi_r + cell][0] = state;
6305 }
6306 }
6307 for cell in 0..w_px / MI {
6308 if mi_c + cell < self.mi_cols {
6309 self.above[mi_c + cell][0] = state;
6310 }
6311 }
6312 }
6313
6314 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
6315 /// block whose luma was decoded as several transform units through
6316 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
6317 /// whole-block luma write -- everything [`Self::record`] does except
6318 /// plane 0, which is already correct per-TU by the time this runs.
6319 fn record_split_luma(
6320 &mut self,
6321 at: (usize, usize),
6322 side: usize,
6323 mode: usize,
6324 uv_mode: usize,
6325 chroma_grids: [&[i32]; 2],
6326 ) {
6327 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
6328 }
6329
6330 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
6331 /// extents in pixels (lane-rectsplit r1), the same relationship
6332 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
6333 /// luma transform split into several square units needs exactly this
6334 /// bookkeeping, at its own true rectangular extents.
6335 fn record_split_luma_rect(
6336 &mut self,
6337 at: (usize, usize),
6338 w: usize,
6339 h: usize,
6340 mode: usize,
6341 uv_mode: usize,
6342 chroma_grids: [&[i32]; 2],
6343 ) {
6344 let (r, c) = at;
6345 self.record_split_luma_rect_mi(
6346 (r * (SUB / MI), c * (SUB / MI)),
6347 w,
6348 h,
6349 mode,
6350 uv_mode,
6351 chroma_grids,
6352 );
6353 }
6354
6355 /// [`Self::record_split_luma_rect`] addressed in mi units (lane-rectsplitx
6356 /// r1) -- a strip 8 px tall starts mid-[`SUB`]-cell, which the coarse
6357 /// `(r, c)` form cannot name. The coarse mode/side arrays are stamped for
6358 /// every cell the strip TOUCHES (`div_ceil`), last writer wins, the
6359 /// convention [`decode_block_rect4`] already established for 1:4 strips.
6360 fn record_split_luma_rect_mi(
6361 &mut self,
6362 at_mi: (usize, usize),
6363 w: usize,
6364 h: usize,
6365 mode: usize,
6366 uv_mode: usize,
6367 chroma_grids: [&[i32]; 2],
6368 ) {
6369 let (mi_r, mi_c) = at_mi;
6370 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
6371 for cell in 0..w.div_ceil(SUB) {
6372 if c + cell >= self.above_mode.len() {
6373 break;
6374 }
6375 self.above_mode[c + cell] = mode;
6376 self.above_uv_mode[c + cell] = uv_mode;
6377 self.above_side[c + cell] = w;
6378 }
6379 for cell in 0..h.div_ceil(SUB) {
6380 if r + cell >= self.left_mode.len() {
6381 break;
6382 }
6383 self.left_mode[r + cell] = mode;
6384 self.left_uv_mode[r + cell] = uv_mode;
6385 self.left_side[r + cell] = h;
6386 }
6387
6388 let (w_mi, h_mi) = (w / MI, h / MI);
6389 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
6390 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
6391 for cell in 0..h_mi {
6392 if let Some(slot) = self.left_side_mi.get_mut(mi_r + cell) {
6393 *slot = h;
6394 }
6395 }
6396 for cell in 0..w_mi {
6397 if let Some(slot) = self.above_side_mi.get_mut(mi_c + cell) {
6398 *slot = w;
6399 }
6400 }
6401 let round_up_even = |n: usize| n.div_ceil(2) * 2;
6402 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
6403 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
6404 let plane = plane_idx + 1;
6405 let state = neighbour_state(grid);
6406 for cell in 0..h_mi {
6407 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
6408 self.left[mi_r + cell][plane] = state;
6409 }
6410 }
6411 for cell in 0..w_mi {
6412 if cell < w_mi.min(bound_w.saturating_sub(mi_c)) {
6413 self.above[mi_c + cell][plane] = state;
6414 }
6415 }
6416 }
6417 }
6418}
6419
6420/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
6421/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
6422/// exactly — including its skip context, which the real key-frame writer
6423/// always writes at a fixed context of zero (it never tracks a neighbour-based
6424/// one for intra blocks; that is the inter-frame writer's rule instead).
6425/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
6426/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
6427/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
6428/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
6429/// plain DC chroma.
6430/// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which
6431/// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's
6432/// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode
6433/// instead (the defect commit 1a89ed9 fixed at the square sites).
6434fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize {
6435 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
6436 filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi])
6437}
6438
6439/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
6440/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
6441/// bound (spec `filter_intra_mode_info` never reads a symbol there).
6442fn filter_intra_size_class(side: usize) -> Option<usize> {
6443 match side {
6444 4 => Some(0),
6445 8 => Some(1),
6446 16 => Some(2),
6447 32 => Some(3),
6448 _ => None,
6449 }
6450}
6451
6452/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
6453/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
6454/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
6455/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
6456fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
6457 match (bw, bh) {
6458 (32, 16) => Some(4),
6459 (16, 32) => Some(5),
6460 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
6461 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
6462 // here dropped that symbol on every DC_PRED strip of that size and
6463 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
6464 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
6465 (16, 8) => Some(6),
6466 (8, 16) => Some(7),
6467 // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <=
6468 // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of
6469 // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0.
6470 (4, 8) => Some(8),
6471 (8, 4) => Some(9),
6472 // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair
6473 // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no
6474 // `use_filter_intra` symbol on those strips although aomenc writes
6475 // one for every DC_PRED block of that shape with
6476 // `--enable-filter-intra=1` (its default), silently desyncing the
6477 // tile (class symbol-consumption-gap).
6478 (32, 8) => Some(10),
6479 (8, 32) => Some(11),
6480 // lane-r14: the 16x16-level 1:4 pair (`decode_rect4_16`'s 16x4/4x16
6481 // strips), rows 17/16 of `default_filter_intra_cdfs`.
6482 (16, 4) => Some(12),
6483 (4, 16) => Some(13),
6484 _ if bw == bh => filter_intra_size_class(bw),
6485 _ => None,
6486 }
6487}
6488
6489/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
6490/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
6491/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
6492/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
6493/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
6494fn palette_bsize_ctx(side: usize) -> Option<usize> {
6495 palette_bsize_ctx_wh(side, side)
6496}
6497
6498/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
6499/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
6500/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
6501/// for ANY bsize, not just the square ones a hand-picked table happened to
6502/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
6503/// row breaks the moment its indexing field moves off the diagonal, and a
6504/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
6505/// block dimension is a power of two, so `bw*bh` always is too and
6506/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
6507/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
6508fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
6509 // lane-r14: `av1_allow_palette`'s bound is `sb_type >= BLOCK_8X8` by the
6510 // BLOCK_SIZES_ALL enum INDEX, which the 1:4 shapes BLOCK_4X16 (16) and
6511 // BLOCK_16X4 (17) clear -- a 64-pixel block, so `av1_get_palette_bsize_ctx`
6512 // (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`) is 0 for them, exactly as
6513 // for an 8x8. Reading the dimension bound as "both sides >= 8" dropped
6514 // `palette_y_mode` on every 16x4/4x16 strip of a screen-content frame.
6515 if bw > 64 || bh > 64 || bw * bh < 64 {
6516 return None;
6517 }
6518 Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
6519}
6520
6521/// A just-decoded palette-Y block's own size, base colours (only the first
6522/// `size` entries are real), and per-pixel colour-index map (`side*side`,
6523/// row-major, each entry `< size`).
6524struct PaletteY {
6525 size: usize,
6526 colors: [u16; 8],
6527 map: Vec<u8>,
6528}
6529
6530/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
6531/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
6532/// shared between U and V, both co-located after 4:2:0 subsampling) plus
6533/// each plane's own base colours.
6534struct PaletteUv {
6535 size: usize,
6536 u_colors: [u16; 8],
6537 v_colors: [u16; 8],
6538 map: Vec<u8>,
6539}
6540
6541/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
6542/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
6543/// `get_unsigned_bits`, which is the same formula): smallest `n` with
6544/// `2^n >= x`, `0` for `x <= 1`.
6545fn ceil_log2(x: u32) -> u32 {
6546 if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() }
6547}
6548
6549/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
6550/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
6551fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
6552 let l = ceil_log2(n as u32);
6553 let m = (1usize << l) - n;
6554 let v = dec.literal(l - 1) as usize;
6555 if v < m {
6556 v
6557 } else {
6558 (v << 1) - m + dec.literal(1) as usize
6559 }
6560}
6561
6562/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
6563/// colours (already-known, from the above/left neighbours) with the
6564/// ascending `transmitted` ones (delta-coded off the wire) back into one
6565/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
6566/// value picks the cached copy first, matching the C `<=`.
6567fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
6568 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
6569 let (mut ci, mut ti) = (0, 0);
6570 while ci < cached.len() && ti < transmitted.len() {
6571 if cached[ci] <= transmitted[ti] {
6572 out.push(cached[ci]);
6573 ci += 1;
6574 } else {
6575 out.push(transmitted[ti]);
6576 ti += 1;
6577 }
6578 }
6579 out.extend_from_slice(&cached[ci..]);
6580 out.extend_from_slice(&transmitted[ti..]);
6581 out
6582}
6583
6584/// `read_palette_colors_y` (decodemv.c:478), at the sequence's real
6585/// `bit_depth` -- lane-kf900 r3: every raw literal here (the first colour,
6586/// each delta's width, the `range` bound and the clamp) is sized by
6587/// `bit_depth`, and hardcoding 8 read 2 bits too few per colour on every
6588/// 10-bit palette block. Raw literals are EQUIPROBABLE, and at the ranges
6589/// this stream reaches (e.g. 62728) an equiprobable read is a FIXED POINT of
6590/// the msac range, so a cross-decoder range ladder stays bit-identical
6591/// through the whole miscount -- only the decoded VALUE differs (class
6592/// `compare-range-not-tell`'s blind spot). (this
6593/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
6594/// (one flag bit each, in cache order), then delta-codes the remainder
6595/// (first value raw, each following delta `>= 1` off a shrinking bit width),
6596/// and merges the two ascending lists back together.
6597fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> [u16; 8] {
6598 let mut cached = Vec::with_capacity(n);
6599 for &c in cache {
6600 if cached.len() >= n {
6601 break;
6602 }
6603 if dec.literal(1) == 1 {
6604 cached.push(c);
6605 }
6606 }
6607 let bd = u32::from(bit_depth());
6608 let max_val = (1i32 << bd) - 1;
6609 let mut colors = [0u16; 8];
6610 let n_cached = cached.len();
6611 if n_cached < n {
6612 let mut transmitted = Vec::with_capacity(n - n_cached);
6613 let first = dec.literal(bd) as u16;
6614 transmitted.push(first);
6615 if n_cached + 1 < n {
6616 let min_bits = bd - 3;
6617 let mut bits = min_bits + dec.literal(2);
6618 let mut range = (1i32 << bd) - i32::from(first) - 1;
6619 for _ in (n_cached + 1)..n {
6620 let delta = dec.literal(bits) as i32 + 1;
6621 let prev = *transmitted.last().unwrap();
6622 let val = (i32::from(prev) + delta).clamp(0, max_val) as u16;
6623 range -= i32::from(val) - i32::from(prev);
6624 bits = bits.min(ceil_log2(range.max(0) as u32));
6625 transmitted.push(val);
6626 }
6627 }
6628 let merged = merge_colors(&transmitted, &cached);
6629 colors[..n].copy_from_slice(&merged);
6630 } else {
6631 colors[..n].copy_from_slice(&cached[..n]);
6632 }
6633 colors
6634}
6635
6636/// `read_palette_colors_uv` (decodemv.c:509), at the sequence's real
6637/// `bit_depth` (see [`read_palette_colors_y`]): U reads
6638/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
6639/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
6640/// unbiased by `+1` -- both differences from Y's own reader, matching the C
6641/// side by side). V never uses a cache: a leading bit picks either `n` raw
6642/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
6643/// rather than clamp.
6644fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> ([u16; 8], [u16; 8]) {
6645 let mut cached = Vec::with_capacity(n);
6646 for &c in cache {
6647 if cached.len() >= n {
6648 break;
6649 }
6650 if dec.literal(1) == 1 {
6651 cached.push(c);
6652 }
6653 }
6654 let bd = u32::from(bit_depth());
6655 let max_val = 1i32 << bd;
6656 let mut u_colors = [0u16; 8];
6657 let n_cached = cached.len();
6658 if n_cached < n {
6659 let mut transmitted = Vec::with_capacity(n - n_cached);
6660 let first = dec.literal(bd) as u16;
6661 transmitted.push(first);
6662 if n_cached + 1 < n {
6663 let min_bits = bd - 3;
6664 let mut bits = min_bits + dec.literal(2);
6665 let mut range = max_val - i32::from(first);
6666 for _ in (n_cached + 1)..n {
6667 let delta = dec.literal(bits) as i32;
6668 let prev = *transmitted.last().unwrap();
6669 let val = (i32::from(prev) + delta).clamp(0, max_val - 1) as u16;
6670 range -= i32::from(val) - i32::from(prev);
6671 bits = bits.min(ceil_log2(range.max(0) as u32));
6672 transmitted.push(val);
6673 }
6674 }
6675 let merged = merge_colors(&transmitted, &cached);
6676 u_colors[..n].copy_from_slice(&merged);
6677 } else {
6678 u_colors[..n].copy_from_slice(&cached[..n]);
6679 }
6680 let mut v_colors = [0u16; 8];
6681 if dec.literal(1) == 1 {
6682 let min_bits_v = bd - 4;
6683 let bits = min_bits_v + dec.literal(2);
6684 v_colors[0] = dec.literal(bd) as u16;
6685 for i in 1..n {
6686 let mut delta = dec.literal(bits) as i32;
6687 if delta != 0 && dec.literal(1) == 1 {
6688 delta = -delta;
6689 }
6690 let mut val = i32::from(v_colors[i - 1]) + delta;
6691 if val < 0 {
6692 val += max_val;
6693 }
6694 if val >= max_val {
6695 val -= max_val;
6696 }
6697 v_colors[i] = val as u16;
6698 }
6699 } else {
6700 for i in 0..n {
6701 v_colors[i] = dec.literal(bd) as u16;
6702 }
6703 }
6704 (u_colors, v_colors)
6705}
6706
6707/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
6708/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
6709/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
6710const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
6711
6712/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
6713/// map's own per-pixel context and colour-order permutation, from the
6714/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
6715/// selection sort). `map`'s stride is `side` (this decoder never crops a
6716/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
6717/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
6718/// actual colour index to store.
6719fn palette_color_index_context(
6720 map: &[u8],
6721 side: usize,
6722 row: usize,
6723 col: usize,
6724 n: usize,
6725) -> (usize, [u8; 8]) {
6726 let left = if col >= 1 { Some(map[row * side + col - 1]) } else { None };
6727 let up_left = if col >= 1 && row >= 1 {
6728 Some(map[(row - 1) * side + col - 1])
6729 } else {
6730 None
6731 };
6732 let up = if row >= 1 { Some(map[(row - 1) * side + col]) } else { None };
6733 let mut scores = [0i32; 8];
6734 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
6735 if let Some(v) = neighbour {
6736 scores[v as usize] += weight;
6737 }
6738 }
6739 let mut color_order = [0u8; 8];
6740 for i in 0..8 {
6741 color_order[i] = i as u8;
6742 }
6743 for i in 0..3 {
6744 let mut max = scores[i];
6745 let mut max_idx = i;
6746 for j in (i + 1)..n {
6747 if scores[j] > max {
6748 max = scores[j];
6749 max_idx = j;
6750 }
6751 }
6752 if max_idx != i {
6753 let max_score = scores[max_idx];
6754 let max_color = color_order[max_idx];
6755 for k in (i + 1..=max_idx).rev() {
6756 scores[k] = scores[k - 1];
6757 color_order[k] = color_order[k - 1];
6758 }
6759 scores[i] = max_score;
6760 color_order[i] = max_color;
6761 }
6762 }
6763 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
6764 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
6765 (ctx as usize, color_order)
6766}
6767
6768/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
6769/// map's wavefront decode over a `side x side` grid -- this decoder's
6770/// palette blocks are always square and never straddle the frame's true
6771/// (possibly odd) edge without already allocating the full `side*side`
6772/// region (every other skip/residual path here does the same), so no
6773/// rows/cols-vs-plane_width/height cropping special case is needed, unlike
6774/// libaom's own non-block-aligned split.
6775fn decode_color_index_map(
6776 dec: &mut SymbolDecoder,
6777 cdfs: &mut Cdfs,
6778 n: usize,
6779 side: usize,
6780 uv: bool,
6781) -> Vec<u8> {
6782 decode_color_index_map_wh(dec, cdfs, n, side, side, uv)
6783}
6784
6785/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
6786/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
6787/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
6788/// independently rather than one shared `side` -- the square call above is
6789/// just `bw == bh`.
6790fn decode_color_index_map_wh(
6791 dec: &mut SymbolDecoder,
6792 cdfs: &mut Cdfs,
6793 n: usize,
6794 bw: usize,
6795 bh: usize,
6796 uv: bool,
6797) -> Vec<u8> {
6798 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
6799 let mut map = vec![0u8; bw * bh];
6800 if trace {
6801 let (rng, _) = dec.debug_state();
6802 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
6803 }
6804 map[0] = read_uniform(dec, n) as u8;
6805 if trace {
6806 let (rng, _) = dec.debug_state();
6807 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
6808 }
6809 for i in 1..(bw + bh - 1) {
6810 let j_hi = i.min(bw - 1);
6811 let j_lo = i.saturating_sub(bh - 1);
6812 for j in (j_lo..=j_hi).rev() {
6813 let row = i - j;
6814 let col = j;
6815 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
6816 if trace {
6817 let (rng, _) = dec.debug_state();
6818 let row_cdf = if uv {
6819 &cdfs.palette_uv_color_index[n - 2][ctx]
6820 } else {
6821 &cdfs.palette_y_color_index[n - 2][ctx]
6822 };
6823 eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} cdf0={} cnt={} rng={rng}", row_cdf[0], row_cdf[n]);
6824 }
6825 let symbol = if uv {
6826 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
6827 } else {
6828 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
6829 };
6830 map[row * bw + col] = color_order[symbol];
6831 if trace {
6832 let (rng, _) = dec.debug_state();
6833 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
6834 }
6835 }
6836 }
6837 map
6838}
6839
6840/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
6841/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
6842/// size class comes from [`filter_intra_size_class_rect`] instead of the
6843/// square-only [`filter_intra_size_class`], and the palette read (when
6844/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
6845/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
6846/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
6847/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
6848#[allow(clippy::too_many_arguments)]
6849fn read_intra_mode_rect(
6850 dec: &mut SymbolDecoder,
6851 cdfs: &mut Cdfs,
6852 above_mode: usize,
6853 left_mode: usize,
6854 cfl: bool,
6855 // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall
6856 // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads
6857 // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's
6858 // chroma is coded once, on the closing strip). Every other caller is a
6859 // block big enough to own its chroma and passes `true`.
6860 has_chroma: bool,
6861 bw: usize,
6862 bh: usize,
6863 enable_filter_intra: bool,
6864 skip_ctx: usize,
6865 allow_screen_content_tools: bool,
6866 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
6867 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
6868 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
6869 palette: Option<(usize, &[u16])>,
6870 palette_uv_cache: &[u16],
6871 mi_r: usize,
6872 mi_c: usize,
6873) -> Result<(
6874 bool,
6875 usize,
6876 i32,
6877 usize,
6878 i32,
6879 Option<(i32, i32)>,
6880 Option<usize>,
6881 Option<PaletteY>,
6882 Option<PaletteUv>,
6883)> {
6884 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
6885 if ec_istep {
6886 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
6887 // (decodemv.c:818), printed at the same point: before the first
6888 // mode-info symbol of the block, so a cross-decoder range ladder can
6889 // be keyed on the BLOCK, not just on the symbol sequence.
6890 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);
6891 }
6892 macro_rules! istep {
6893 ($name:literal, $val:expr) => {
6894 if ec_istep {
6895 let (rng, _) = dec.debug_state();
6896 eprintln!(
6897 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
6898 $name, $val
6899 );
6900 }
6901 };
6902 }
6903 // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is
6904 // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at
6905 // the one point every rect caller routes through, so no call site can
6906 // offer the 14-symbol CFL alphabet on a 64-axis block (class
6907 // wrong-alphabet-same-value: same value, wrong interval, silent desync).
6908 let cfl = if cfl && bw.max(bh) > 32 {
6909 NOCFL_UV_MODE_HITS.with(|c| c.set(c.get() + 1));
6910 false
6911 } else {
6912 cfl
6913 };
6914 // lane-intra14 r1: on the INTER block path everything up to and including
6915 // `is_inter` was already read by [`decode_inter_block`], so this reader
6916 // starts at the mode syntax with the `skip` that caller read.
6917 let inter = INTRA_IN_INTER_MODE.with(std::cell::Cell::get);
6918 let skip = if let Some((_, skip)) = inter {
6919 skip
6920 } else {
6921 // Same `intra_segment_id` placement as the square reader above.
6922 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
6923 if seg_id_pre_skip() {
6924 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);
6925 }
6926 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
6927 istep!("skip", skip as i32);
6928 if !seg_id_pre_skip() {
6929 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);
6930 }
6931 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
6932 istep!("cdef", 0);
6933 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
6934 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
6935 // `false`.
6936 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip);
6937 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip);
6938 istep!("dq", 0);
6939 // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after
6940 // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the
6941 // `use_intrabc` symbol is read for EVERY intra block of an `allow_intrabc`
6942 // frame -- `av1_allow_intrabc` is a frame-level test with no shape term, so
6943 // rect strips read it exactly like square leaves ([`read_intra_mode`],
6944 // [`read_intra_mode_sub8`]). Missing it here desynced the arithmetic
6945 // decoder at the FIRST symbol of the first rect block of every
6946 // `--tune-content=screen` key frame. Reconstruction of a real intrabc
6947 // block at this shape is out of scope, so the flag is consumed and
6948 // refused by name when it fires.
6949 if allow_intrabc_frame() {
6950 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
6951 RECT_INTRABC_READS.with(|c| c.set(c.get() + 1));
6952 istep!("intrabc", use_intrabc as i32);
6953 if use_intrabc {
6954 INTRABC_HITS.with(|c| c.set(c.get() + 1));
6955 return Err(unsupported(
6956 "intra block copy on a HORZ/VERT/1:4 rect intra strip (reconstruction is not ported at this shape)",
6957 ));
6958 }
6959 }
6960 skip
6961 };
6962 // libaom `read_intra_block_mode_info` (decodemv.c:1189) vs the key
6963 // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode`
6964 // off `kf_y_mode_cdf[above][left]`).
6965 let mode = if let Some((size_group, _)) = inter {
6966 dec.symbol(&mut cdfs.y_mode[size_group])
6967 } else {
6968 let above_ctx = INTRA_MODE_CTX[above_mode];
6969 let left_ctx = INTRA_MODE_CTX[left_mode];
6970 dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx])
6971 };
6972 istep!("mode", mode as i32);
6973 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
6974 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
6975 } else {
6976 0
6977 };
6978 istep!("angle_y", angle_delta_y);
6979 // lane-sb128c r3 (class sweep): libaom `read_intra_mode_uv(.., is_cfl_allowed(xd), ..)`
6980 // and `is_cfl_allowed` (blockd.h) is `block_size_wide[bsize] <= 32 &&
6981 // block_size_high[bsize] <= 32` on the LUMA bsize. Deciding the alphabet
6982 // here, from the block's own size, is the single point every caller routes
6983 // through -- a caller passing `true` for a >32 strip used to pick the
6984 // 14-symbol CFL CDF, same value but a different range (class
6985 // wrong-alphabet-same-value).
6986 let cfl = cfl && bw <= 32 && bh <= 32;
6987 let uv_mode = if !has_chroma {
6988 DC_PRED
6989 } else if cfl {
6990 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
6991 } else {
6992 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
6993 };
6994 istep!("uv_mode", uv_mode as i32);
6995 let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED {
6996 Some(read_cfl_alphas(dec, cdfs))
6997 } else {
6998 None
6999 };
7000 if has_chroma && (9..=12).contains(&uv_mode) {
7001 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
7002 }
7003 let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) {
7004 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
7005 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
7006 } else {
7007 0
7008 };
7009 istep!("angle_uv", angle_delta_uv);
7010 if angle_delta_uv != 0 {
7011 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
7012 }
7013 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
7014 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
7015 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
7016 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
7017 // colours only here, the colour-index maps deferred past `filter_intra`
7018 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
7019 // runs from the caller, after the whole mode-info read).
7020 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
7021 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
7022 if allow_screen_content_tools
7023 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
7024 {
7025 // r6: this is the exact site the removed blanket refusal used to
7026 // guard -- reached for EVERY rect strip in a screen-content frame,
7027 // independent of whether the block ends up using a palette.
7028 RECT_SCREEN_CONTENT_HITS.with(|c| c.set(c.get() + 1));
7029 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
7030 let use_palette_y =
7031 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
7032 if use_palette_y {
7033 if palette.is_none() {
7034 return Err(unsupported(
7035 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
7036 ));
7037 }
7038 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
7039 let colors = read_palette_colors_y(dec, n, cache);
7040 palette_y_pending = Some((n, colors));
7041 }
7042 let palette_uv_mode_ctx = usize::from(use_palette_y);
7043 // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard.
7044 if has_chroma
7045 && uv_mode == DC_PRED
7046 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
7047 {
7048 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
7049 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache);
7050 palette_uv_pending = Some((n, u_colors, v_colors));
7051 }
7052 }
7053 let mut filter_intra = None;
7054 if crate::envflags::env_flag!("EC_AV1_TRACE") {
7055 let (rng, _) = dec.debug_state();
7056 eprintln!(
7057 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
7058 class={:?} rng={rng}",
7059 enable_filter_intra as i32,
7060 filter_intra_size_class_rect(bw, bh)
7061 );
7062 }
7063 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
7064 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
7065 if mode == DC_PRED
7066 && enable_filter_intra
7067 && palette_y_pending.is_none()
7068 && let Some(class) = filter_intra_size_class_rect(bw, bh)
7069 {
7070 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
7071 if crate::envflags::env_flag!("EC_AV1_TRACE") {
7072 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
7073 }
7074 istep!("use_filter_intra", use_filter_intra as i32);
7075 if use_filter_intra {
7076 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
7077 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
7078 istep!("filter_intra_mode", fi_mode as i32);
7079 filter_intra = Some(fi_mode);
7080 }
7081 }
7082 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
7083 // same order as [`read_intra_mode`]'s own square path.
7084 let palette_y = palette_y_pending.map(|(n, colors)| {
7085 let map = decode_color_index_map_wh(dec, cdfs, n, bw, bh, false);
7086 PALETTE_HITS.with(|c| c.set(c.get() + 1));
7087 PALETTE_RECT_HITS.with(|c| c.set(c.get() + 1));
7088 PaletteY { size: n, colors, map }
7089 });
7090 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
7091 // `av1_get_plane_block_size(bsize, 1, 1)` (`ss_size_lookup`), NOT a
7092 // plain halving: BLOCK_16X4 subsamples to BLOCK_8X4 and BLOCK_4X16 to
7093 // BLOCK_4X8, both floored at the 4-px transform. Halving the short
7094 // axis to 2 read HALF the colour-index symbols of a 1:4 strip's
7095 // chroma palette and desynced the tile from there.
7096 let (cw, ch) = ((bw / 2).max(4), (bh / 2).max(4));
7097 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, true);
7098 PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
7099 PaletteUv { size: n, u_colors, v_colors, map }
7100 });
7101 Ok((
7102 skip,
7103 mode,
7104 angle_delta_y,
7105 uv_mode,
7106 angle_delta_uv,
7107 alpha,
7108 filter_intra,
7109 palette_y,
7110 palette_uv,
7111 ))
7112}
7113
7114/// Stamps a 1:4 strip's palette state into the mi-granular above/left arrays,
7115/// at the strip's REAL mi position. `av1_get_palette_cache` reads
7116/// `xd->above_mbmi`/`xd->left_mbmi`, i.e. the mi cell above/left of the
7117/// block, so each strip owns its own rows and columns and no aliasing rule
7118/// is needed (lane-kf900 r6).
7119#[allow(clippy::too_many_arguments)]
7120fn record_strip_palette(
7121 n: &mut Neighbours,
7122 mi: (usize, usize),
7123 bw: usize,
7124 bh: usize,
7125 y_size: usize,
7126 y_colors: [u16; 8],
7127 uv_size: usize,
7128 uv_colors: [u16; 8],
7129) {
7130 let (r, c) = mi;
7131 // lane-t900 r23 rung: every publication of a block's palette state into
7132 // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode
7133 // path left a stale `left_palette_size` behind when
7134 // `av1_get_palette_mode_ctx` disagrees with libaom's.
7135 if crate::envflags::env_flag!("EC_PALPUB") {
7136 eprintln!("EC_PALPUB strip mi={r},{c} bw={bw} bh={bh} y={y_size} uv={uv_size}");
7137 }
7138 // lane-kf900 r6: the palette side bands are mi-granular now, so a strip
7139 // writes its OWN span on BOTH axes -- the old `last` split-axis rule only
7140 // existed because the 16px [`SUB`] cell held one slot for all the strips
7141 // of a HORZ_4/VERT_4 and leaf 0 zeroing the other axis threw away the
7142 // real neighbour leaf 1 reads.
7143 {
7144 for cell in 0..(bw / MI).max(1) {
7145 if let Some(e) = n.above_palette_size.get_mut(c + cell) {
7146 *e = y_size;
7147 n.above_palette_colors[c + cell] = y_colors;
7148 n.above_palette_uv_size[c + cell] = uv_size;
7149 n.above_palette_uv_colors[c + cell] = uv_colors;
7150 }
7151 }
7152 }
7153 {
7154 for cell in 0..(bh / MI).max(1) {
7155 if n.left_palette_size.get(r + cell).is_none() {
7156 break;
7157 }
7158 n.left_palette_size[r + cell] = y_size;
7159 n.left_palette_colors[r + cell] = y_colors;
7160 n.left_palette_uv_size[r + cell] = uv_size;
7161 n.left_palette_uv_colors[r + cell] = uv_colors;
7162 }
7163 }
7164}
7165
7166/// [`tx_size_context`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
7167/// `get_tx_size_context` (libaom `pred_common.h`) compares the neighbour
7168/// above against this block's own *width* and the neighbour to the left
7169/// against its own *height* -- for a square block those are the same value,
7170/// which is why the square-only version can get away with one `own_side`.
7171fn tx_size_context_rect(
7172 n: &Neighbours,
7173 (mi_r, mi_c): (usize, usize),
7174 own_w: usize,
7175 own_h: usize,
7176) -> usize {
7177 // `get_tx_size_context` compares against `max_txsize_rect_lookup[bsize]`,
7178 // not the block's own side: no transform is wider or taller than 64, so a
7179 // block with a 128 side resolves against 64 (the square path already caps
7180 // this way, lane-sb128b r1). Without the cap the 64x128 half of a 128-root
7181 // VERT reads the tx-depth symbol off row 0 where libaom uses row 1.
7182 let (own_w, own_h) = (own_w.min(64), own_h.min(64));
7183 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w;
7184 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h;
7185 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
7186 eprintln!(
7187 "EC_TXCTX mi_row={mi_r} mi_col={mi_c} w={own_w} h={own_h} above_px={} left_px={} ctx={}",
7188 if mi_r > n.tile_row0_mi { tx_px_at(n, false, mi_r - 1, mi_c) } else { 0 },
7189 if mi_c > n.tile_col0_mi { tx_h_px_at(n, false, mi_r, mi_c - 1) } else { 0 },
7190 usize::from(above) + usize::from(left)
7191 );
7192 }
7193 usize::from(above) + usize::from(left)
7194}
7195
7196/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
7197fn cfl_ac_q3_rect(y: &PlaneBuf, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
7198 let (cw, ch) = (bw / 2, bh / 2);
7199 let mut ac = vec![0i32; cw * ch];
7200 let mut sum = 0i32;
7201 for cy in 0..ch {
7202 for cx in 0..cw {
7203 let (lx, ly) = (px + cx * 2, py + cy * 2);
7204 let q3 = (i32::from(y.data[ly * y.width + lx])
7205 + i32::from(y.data[ly * y.width + lx + 1])
7206 + i32::from(y.data[(ly + 1) * y.width + lx])
7207 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
7208 << 1;
7209 ac[cy * cw + cx] = q3;
7210 sum += q3;
7211 }
7212 }
7213 let num_pel = (cw * ch) as i32;
7214 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
7215 ac.iter_mut().for_each(|v| *v -= avg);
7216 ac
7217}
7218
7219/// Everything a rect strip already read out of the stream before its luma
7220/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
7221/// (nine values that would otherwise be nine more parameters).
7222struct RectStripModes {
7223 skip: bool,
7224 mode: usize,
7225 angle_delta_y: i32,
7226 uv_predict_mode: usize,
7227 angle_delta_uv: i32,
7228 alpha: Option<(i32, i32)>,
7229 filter_intra: Option<usize>,
7230 smooth_neighbor: bool,
7231 smooth_neighbor_uv: bool,
7232 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
7233 /// mapped through the colour table), sliced per transform unit below --
7234 /// palette prediction reads no edge pixels, so a unit's slice of the
7235 /// whole-block map IS its prediction. Without this a palette strip whose
7236 /// transform splits predicted DC and came out flat grey while the entropy
7237 /// stream stayed in sync (the coefficients are read either way).
7238 palette_y: Option<Vec<u16>>,
7239 /// As `palette_y`, for the un-split chroma transform (U, V).
7240 palette_uv: Option<(Vec<u16>, Vec<u16>)>,
7241}
7242
7243/// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth`
7244/// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times
7245/// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the
7246/// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's
7247/// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 ->
7248/// TX_32X16`) and only the second reaches a square -- the reason
7249/// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
7250/// already square) mis-tiled 1:4 strips.
7251fn depth_to_tx_wh(bw: usize, bh: usize, depth: usize) -> (usize, usize) {
7252 let (mut w, mut h) = (bw.min(64), bh.min(64));
7253 for _ in 0..depth {
7254 match w.cmp(&h) {
7255 std::cmp::Ordering::Greater => w /= 2,
7256 std::cmp::Ordering::Less => h /= 2,
7257 std::cmp::Ordering::Equal => {
7258 w /= 2;
7259 h /= 2;
7260 }
7261 }
7262 }
7263 (w, h)
7264}
7265
7266/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
7267/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
7268/// rect path here refused by name until now ("per-unit rect prediction is not
7269/// ported").
7270///
7271/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
7272/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
7273/// strip the very first step already lands on a SQUARE transform
7274/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
7275/// every further step halves a square) -- so each unit is square and reads
7276/// through the ordinary square [`read_plane`]. What is genuinely rectangular
7277/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
7278/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
7279/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
7280/// split by luma's depth.
7281///
7282/// Each unit predicts off whatever the earlier units of this same block
7283/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
7284/// inside `av1_foreach_transformed_block`, raster order), which is exactly
7285/// what predicting the whole strip in one shot got wrong.
7286#[allow(clippy::too_many_arguments)]
7287fn decode_rect_split(
7288 dec: &mut SymbolDecoder,
7289 cdfs: &mut Cdfs,
7290 neighbours: &mut Neighbours,
7291 at_mi: (usize, usize),
7292 bw: usize,
7293 bh: usize,
7294 // The transform unit's own width and height in pixels. Square for every
7295 // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
7296 // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
7297 // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
7298 tx_w: usize,
7299 tx_h: usize,
7300 m: &RectStripModes,
7301 y: &mut PlaneBuf,
7302 u: &mut PlaneBuf,
7303 v: &mut PlaneBuf,
7304 base_q_idx: u8,
7305 reduced_tx_set: bool,
7306) -> Result<()> {
7307 let (mi_r, mi_c) = at_mi;
7308 let (px, py) = (mi_c * MI, mi_r * MI);
7309 let (cpx, cpy) = (px / 2, py / 2);
7310 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
7311 // The chroma transform is picked before any symbol is read, so an
7312 // unsupported chroma shape refuses before this strip desyncs the tile.
7313 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
7314 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
7315 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
7316 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
7317 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
7318 // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32
7319 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx`
7320 // squares a rect transform down to a CDF set by
7321 // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set,
7322 // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets
7323 // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`)
7324 // paths already prove for these same shapes.
7325 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
7326 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
7327 (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])),
7328 (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])),
7329 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
7330 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
7331 _ => None,
7332 };
7333 if !m.skip {
7334 if let Some(i) = match (chroma_w, chroma_h) {
7335 (32, 8) => Some(0),
7336 (8, 32) => Some(1),
7337 (8, 4) => Some(2),
7338 (4, 8) => Some(3),
7339 _ => None,
7340 } {
7341 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
7342 let mut hits = c.get();
7343 hits[i] += 1;
7344 c.set(hits);
7345 });
7346 }
7347 if chroma.is_none() {
7348 // Diagnostic for the next caller that lands here (class
7349 // refusal-names-a-correlate: the message names the tool, not the
7350 // shape); the refusal below keeps its inventory-pinned wording.
7351 eprintln!("EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} chroma={chroma_w}x{chroma_h}");
7352 }
7353 }
7354 // lane-rectsplit r2 (verifier finding): with both callers wired
7355 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
7356 // 64x32/32x64) every shape that reaches here has a table above, so this
7357 // arm is UNREACHABLE today. It stays as the shape guard for the next
7358 // caller -- a new strip size would otherwise hit the `expect` below and
7359 // panic instead of refusing by name -- and so stays in
7360 // `refusal_inventory::REFUSALS`.
7361 if !m.skip && chroma.is_none() {
7362 return Err(unsupported(
7363 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
7364 ));
7365 }
7366 RECT_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
7367 if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 {
7368 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.set(c.get() + 1));
7369 }
7370 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
7371 // A square unit reads through the ordinary square [`read_plane`]; a rect
7372 // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with
7373 // the very tables the unsplit 16x8/32x16 paths use.
7374 let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) {
7375 (w, h) if w == h => None,
7376 (16, 8) | (8, 16) => Some((
7377 if reduced_tx_set {
7378 TxbSet::LumaRect16x8
7379 } else {
7380 TxbSet::LumaRect16x8Set1
7381 },
7382 if tx_w == 16 { &SCAN_16X8[..] } else { &SCAN_8X16[..] },
7383 )),
7384 (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])),
7385 (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])),
7386 // lane-rect64port r1: the un-split TX_64X32/TX_32X64 of a 64-level
7387 // strip, read through the `luma_64corner` arm below instead of a rect
7388 // table -- a 64-length axis codes only its low 32 coefficients
7389 // (`av1_get_max_eob` / the zero-out of `av1_get_adjusted_tx_size`), so
7390 // the coded unit is the 32x32 corner [`decode_block_rect64`]'s own
7391 // depth-0 arm already reads on the key-frame path.
7392 //
7393 // lane-sub8x4 r3: WITNESS FOUND, so this is no longer behind
7394 // `EC_RECT64_SPLIT`. r1's "no witness" was true only while the
7395 // sub-8x8 intra leaves still refused: with those lifted (r2) the
7396 // first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode
7397 // all 33 frames pixel-exact against ffmpeg while this arm fires 90x
7398 // 64x32 + 5x 32x64 -- pinned as `fixtures/reelb_rect64_intra16x4_witness.obu`
7399 // and gated by `a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact`.
7400 // lane-wit16x4 r1 re-measured that fixture on the merged tip: this arm
7401 // fires 64x32=148 32x64=123 (the 90/5 above were counted out of the
7402 // frame-33 desync lane-frame36 r2 fixed), all 33 frames pixel-exact.
7403 (64, 32) | (32, 64) => None,
7404 _ => {
7405 return Err(unsupported(format!(
7406 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \
7407 coefficient tables for that shape here)"
7408 )))
7409 }
7410 };
7411 // The `None` above that is NOT the square arm.
7412 let luma_64corner = tx_w != tx_h;
7413 // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact
7414 // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole
7415 // frame exactly, two sub-16 split strips in it), but the RECT-unit arm --
7416 // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the
7417 // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the
7418 // per-unit rect walk stay wired above/below; the round that finds that
7419 // defect deletes this refusal and nothing else.
7420 let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set);
7421 let luma_scan = default_scan(tx_w.min(tx_h));
7422 let zero_tu = vec![0i32; tx_w * tx_h];
7423 // The strip's OWN edge availability, the fallback for a transform unit
7424 // whose top-right/bottom-left pixels fall outside the strip.
7425 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
7426 for tu_row in 0..bh / tx_h {
7427 for tu_col in 0..bw / tx_w {
7428 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
7429 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
7430 let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h);
7431 // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged):
7432 // libaom clips `av1_foreach_transformed_block_in_plane` to
7433 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
7434 // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose
7435 // TOP-LEFT sample falls outside the frame is never coded. We read
7436 // coefficients for those phantom units and desynced the stream at
7437 // the very next symbol.
7438 if tu_px >= y.true_width || tu_py >= y.true_height {
7439 continue;
7440 }
7441 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
7442 // transform unit INSIDE a block, which is a different rule from
7443 // the standalone-block table [`Reach::of`] applies -- and the
7444 // reason a depth-2 superblock strip came out one sample off
7445 // before this: `Reach::of(tx, ..)` answered as if the unit were
7446 // its own block at that superblock position.
7447 // * top-right: if the unit's right neighbour is still inside the
7448 // strip the pixels are already reconstructed (`col_off +
7449 // tx_wide < plane_bw`); otherwise only the strip's own top row
7450 // of units can reach past it, through the block-level answer.
7451 // * bottom-left: a unit that is not in the strip's left column
7452 // has none (`col_off > 0` returns 0); inside the strip
7453 // (`row_off + tx_high < plane_bh`) they are the left
7454 // neighbour's, already reconstructed; the last row falls back
7455 // to the block-level answer.
7456 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach);
7457 // The unit's own window on the block's palette prediction.
7458 if let Some(buf) = &m.palette_y {
7459 let tu_buf: Vec<u16> = (0..tx_h)
7460 .flat_map(|i| {
7461 let base = (row_off + i) * bw + col_off;
7462 buf[base..base + tx_w].iter().copied()
7463 })
7464 .collect();
7465 set_palette_pred(tu_buf);
7466 }
7467 if m.skip {
7468 y.reconstruct_rect(
7469 tu_px,
7470 tu_py,
7471 tx_w,
7472 tx_h,
7473 m.mode,
7474 m.angle_delta_y,
7475 tu_reach,
7476 &zero_tu,
7477 None,
7478 m.filter_intra,
7479 m.smooth_neighbor,
7480 );
7481 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
7482 } else if luma_64corner && luma_rect.is_none() {
7483 // The un-split 64-level luma transform: `read_coeffs` on the
7484 // 32x32 CDF set [`TxbSet::Luma64`] with `default_scan(TX32)`
7485 // and the real rect shape passed through for
7486 // `av1_nz_map_ctx_offset` -- byte for byte
7487 // [`decode_block_rect64`]'s depth-0 read, which the key-frame
7488 // 64-level strip gate already proves. `tx_type` is not coded
7489 // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once
7490 // the square-up size is TX_64X64), and this unit covers its
7491 // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat.
7492 if crate::envflags::env_flag!("EC_RECT64TU") {
7493 eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode);
7494 }
7495 RECT64_CORNER_TU_HITS.with(|c| {
7496 let mut v = c.get();
7497 v[usize::from(tx_h > tx_w)] += 1;
7498 c.set(v);
7499 });
7500 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
7501 let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra));
7502 let (corner, tu_tx_type) = read_coeffs(
7503 dec,
7504 &mut coding,
7505 &default_scan(TX32),
7506 0,
7507 dc_sign_ctx(tu_around.2),
7508 TxType::DctDct,
7509 Some((tx_w, tx_h)),
7510 )?;
7511 let (cw, ch) = (tx_w.min(TX32), tx_h.min(TX32));
7512 let mut tu_grid = vec![0i32; tx_w * tx_h];
7513 for row in 0..ch {
7514 tu_grid[row * tx_w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
7515 }
7516 let residual = dequant_and_inverse_typed_wh(
7517 &tu_grid,
7518 tx_w,
7519 tx_h,
7520 crate::decode::bit_depth(),
7521 block_q_idx(),
7522 plane_q_delta(0).0,
7523 plane_q_delta(0).1,
7524 tu_tx_type,
7525 );
7526 y.reconstruct_rect(
7527 tu_px,
7528 tu_py,
7529 tx_w,
7530 tx_h,
7531 m.mode,
7532 m.angle_delta_y,
7533 tu_reach,
7534 &residual,
7535 None,
7536 m.filter_intra,
7537 m.smooth_neighbor,
7538 );
7539 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
7540 } else if let Some((rect_set, rect_scan)) = luma_rect {
7541 // The rect-unit twin of the square arm below: same contexts,
7542 // same order, through the rect coefficient reader. The
7543 // `tx_type` CDF row of a filter-intra block is
7544 // `fimode_to_intradir[filter_intra_mode]`, never the block's
7545 // own (always DC_PRED) mode -- [`read_plane`] applies that
7546 // for the square arm, so this one must too.
7547 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
7548 // libaom `get_txb_ctx`: a LUMA transform that covers its whole
7549 // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the
7550 // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the
7551 // neighbour-magnitude table is for a unit SMALLER than its
7552 // block. [`decode_block_rect`]'s own unsplit read passes a
7553 // literal 0 for the same reason; this arm applied the table
7554 // unconditionally and desynced every depth-0 rect strip that
7555 // reached it (lane-intrarect r2: ctx 5 where aomdec read 0).
7556 let tu_skip_ctx = if tx_w == bw && tx_h == bh {
7557 0
7558 } else {
7559 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI)
7560 };
7561 let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra));
7562 let (tu_grid, tu_tx_type) = read_coeffs_rect(
7563 dec,
7564 &mut coding,
7565 rect_scan,
7566 tx_w,
7567 tx_h,
7568 tu_skip_ctx,
7569 dc_sign_ctx(tu_around.2),
7570 TxType::DctDct,
7571 )?;
7572 let residual = dequant_and_inverse_typed_wh(
7573 &tu_grid,
7574 tx_w,
7575 tx_h,
7576 crate::decode::bit_depth(),
7577 block_q_idx(),
7578 plane_q_delta(0).0,
7579 plane_q_delta(0).1,
7580 tu_tx_type,
7581 );
7582 y.reconstruct_rect(
7583 tu_px,
7584 tu_py,
7585 tx_w,
7586 tx_h,
7587 m.mode,
7588 m.angle_delta_y,
7589 tu_reach,
7590 &residual,
7591 None,
7592 m.filter_intra,
7593 m.smooth_neighbor,
7594 );
7595 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
7596 } else {
7597 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
7598 // This unit is smaller than the block it sits in, so
7599 // `txb_skip_ctx` is the neighbour-magnitude table, not the
7600 // lone-TU 0 (spec `get_txb_ctx_general`).
7601 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
7602 let tu_grid = read_plane(
7603 dec,
7604 cdfs,
7605 luma_set,
7606 &luma_scan,
7607 0,
7608 tu_around,
7609 m.mode,
7610 m.mode,
7611 m.angle_delta_y,
7612 tu_reach,
7613 y,
7614 tu_px,
7615 tu_py,
7616 tx_w,
7617 tx_w,
7618 base_q_idx,
7619 None,
7620 m.filter_intra,
7621 Some(tu_skip_ctx),
7622 m.smooth_neighbor,
7623 )?;
7624 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
7625 }
7626 }
7627 }
7628 // CHROMA: one un-split rect transform for the whole strip.
7629 let ac = m.alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
7630 let reach = block_reach;
7631 let (u_grid, v_grid) = if m.skip {
7632 let zero = vec![0i32; chroma_w * chroma_h];
7633 if let Some((ub, _)) = &m.palette_uv {
7634 set_palette_pred(ub.clone());
7635 }
7636 u.reconstruct_rect(
7637 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
7638 m.alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv,
7639 );
7640 if let Some((_, vb)) = &m.palette_uv {
7641 set_palette_pred(vb.clone());
7642 }
7643 v.reconstruct_rect(
7644 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
7645 m.alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv,
7646 );
7647 (zero.clone(), zero)
7648 } else {
7649 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
7650 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
7651 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
7652 // so only the 16x8/8x16 pair takes the mode-indexed default.
7653 let default_tx = if chroma_w.max(chroma_h) >= 32 {
7654 TxType::DctDct
7655 } else {
7656 default_intra_tx_type(m.uv_predict_mode as u8)
7657 };
7658 let around = neighbours.around_mi_rect(at_mi, bw, bh);
7659 let mut grids: Vec<Vec<i32>> = Vec::with_capacity(2);
7660 for plane_idx in 1..=2 {
7661 let skip_ctx =
7662 usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
7663 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
7664 let (levels, tx_type) = read_coeffs_rect(
7665 dec,
7666 &mut coding,
7667 chroma_scan,
7668 chroma_w,
7669 chroma_h,
7670 skip_ctx,
7671 dc_sign_ctx(around[plane_idx].2),
7672 default_tx,
7673 )?;
7674 // The same delta_q proof the unsplit rect64 path records
7675 // (lane-rectsplit r4: lifting the split-transform refusal moved
7676 // superblock strips onto this path, so only counting there would
7677 // leave the delta_q gate's counter silent for them).
7678 if bw.max(bh) == 64 && CURRENT_Q_IDX.with(|c| c.get()) != i32::from(base_q_idx) {
7679 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
7680 }
7681 let residual = dequant_and_inverse_typed_wh(
7682 &levels,
7683 chroma_w,
7684 chroma_h,
7685 crate::decode::bit_depth(),
7686 CURRENT_Q_IDX.with(|c| c.get()),
7687 plane_q_delta(plane_idx).0,
7688 plane_q_delta(plane_idx).1,
7689 tx_type,
7690 );
7691 let cfl = m
7692 .alpha
7693 .zip(ac.as_deref())
7694 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
7695 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
7696 if let Some((ub, vb)) = &m.palette_uv {
7697 let buf = if plane_idx == 1 { ub } else { vb };
7698 set_palette_pred(buf.clone());
7699 }
7700 plane.reconstruct_rect(
7701 cpx,
7702 cpy,
7703 chroma_w,
7704 chroma_h,
7705 m.uv_predict_mode,
7706 m.angle_delta_uv,
7707 reach,
7708 &residual,
7709 cfl,
7710 None,
7711 m.smooth_neighbor_uv,
7712 );
7713 grids.push(levels);
7714 }
7715 let mut it = grids.into_iter();
7716 (it.next().unwrap(), it.next().unwrap())
7717 };
7718 neighbours.record_split_luma_rect_mi(
7719 at_mi,
7720 bw,
7721 bh,
7722 m.mode,
7723 m.uv_predict_mode,
7724 [&u_grid, &v_grid],
7725 );
7726 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
7727 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
7728 if crate::envflags::env_flag!("EC_AV1_TRACE") {
7729 let (rng, _) = dec.debug_state();
7730 eprintln!(
7731 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
7732 tx={tx_w}x{tx_h} rng={rng}"
7733 );
7734 }
7735 Ok(())
7736}
7737
7738/// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect
7739/// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name
7740/// because it predicts squares only. Every pixel here goes through the rect
7741/// machinery the key-frame paths already prove: [`decode_rect_split`], which
7742/// at `depth == 0` is the unsplit strip as a single transform unit and
7743/// beyond it the per-unit walk of [`depth_to_tx_wh`].
7744///
7745/// What is genuinely different from [`decode_block_rect`] is the mode
7746/// syntax: on an inter frame an intra block reads `y_mode[size_group]` and
7747/// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never
7748/// the key frame's `kf_y_mode` above/left pair. This mirrors the square
7749/// intra-in-inter arm's own reads at the rect footprint, including its
7750/// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe
7751/// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the
7752/// square and this arm) and a nonzero luma angle delta refused by name.
7753///
7754/// The strip's own neighbour records (luma per transform unit, chroma, skip
7755/// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the
7756/// inter-side bands and the mi map.
7757#[allow(clippy::too_many_arguments)]
7758/// The `(size_group_lookup, bsize_to_tx_size_cat)` row an INTRA block coded
7759/// inside an inter frame reads its `y_mode` and `tx_depth` symbols from, for
7760/// the rect footprints [`decode_intra_rect_in_inter`] resolves itself (the
7761/// 128-root halves and the 16x4/4x16 strips of a 1:4 partition take their own
7762/// branches before this). libaom `common_data.h:61` / `blockd.h:1347`: the 2:1
7763/// strips keep the group/category diagonal (BLOCK_16X8 -> 1/1, BLOCK_32X16 ->
7764/// 2/2, BLOCK_64X32 -> 3/3), the 1:4 ones break it (BLOCK_32X8 is group 1 but
7765/// category 2, BLOCK_64X16 group 2 and category 3), which is why the row is a
7766/// table here rather than a shift of `bw.min(bh)`.
7767fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> {
7768 Some(match (bw.min(bh), bw.max(bh)) {
7769 (8, 16) => (1usize, 1usize),
7770 (16, 32) => (2, 2),
7771 (32, 64) => (3, 3),
7772 (8, 32) => (1, 2),
7773 (16, 64) => (2, 3),
7774 _ => return None,
7775 })
7776}
7777
7778/// lane-t900 r20, refusal B ("an intra-coded {bw}x{bh} block on the inter
7779/// block path"): the shapes that can reach that arm, enumerated against the
7780/// MEASURED domain of the inter block path
7781/// ([`INTER_BLOCK_SHAPES`], the census the gate
7782/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`
7783/// fills from three real streams).
7784///
7785/// [`decode_intra_rect_in_inter`] is called from one site, under
7786/// `write_w != side || write_h != side`, and only after two earlier arms have
7787/// taken their shapes: a footprint with a side below 8 is either a 16x4/4x16
7788/// strip WITH a chroma-pair record (the `strip16` branch) or refused by name,
7789/// and a 128-px footprint returns from the `bw.max(bh) == 128` branch. What is
7790/// left is every rectangular census shape with `8 <= min` and `max <= 64` --
7791/// and each of those has a row, so the refusal names a shape no measured
7792/// stream can present.
7793#[test]
7794fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() {
7795 let mut checked = 0;
7796 for &(side, w, h) in &INTER_BLOCK_SHAPES {
7797 if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 {
7798 continue;
7799 }
7800 assert!(
7801 intra_in_inter_size_row(w, h).is_some(),
7802 "the inter path decodes {w}x{h} blocks, and an INTRA one of that shape would hit \
7803 the \"no size-group/tx-category row\" refusal"
7804 );
7805 checked += 1;
7806 }
7807 assert_eq!(
7808 checked, 10,
7809 "the block-shape census changed: {checked} rect shapes reach the intra-in-inter row \
7810 lookup, not the 10 this claim was measured over"
7811 );
7812}
7813
7814/// The `motion_mode` / `obmc` CDF row for a block footprint: libaom's
7815/// `motion_mode_cdf[mbmi->bsize]`, in this crate's packed row order (which
7816/// `cdf::MOTION_MODE` documents -- the 128-px rows come last, so they are
7817/// matched before the square arm's `log2` shortcut).
7818///
7819/// `None` is the refusal "a motion_mode symbol for a block shape with no CDF
7820/// row here"; the enumeration below is what proves no conformant block can
7821/// reach it.
7822pub(crate) fn motion_mode_cdf_row(write_w: usize, write_h: usize) -> Option<usize> {
7823 Some(match (write_w, write_h) {
7824 // lane-sb128c r5: the 128 root's own rows come FIRST -- the square arm
7825 // below maps 128 to row 4 (BLOCK_16X32).
7826 (64, 128) => 14,
7827 (128, 64) => 15,
7828 (128, 128) => 16,
7829 (w, h) if w == h => (w.trailing_zeros() - 3) as usize,
7830 (16, 32) => 4,
7831 (32, 16) => 5,
7832 (32, 64) => 6,
7833 (64, 32) => 7,
7834 (8, 32) => 8,
7835 (32, 8) => 9,
7836 (16, 64) => 10,
7837 (64, 16) => 11,
7838 // lane-inter4 r3: the 16x16-level rect inter leaves.
7839 (8, 16) => 12,
7840 (16, 8) => 13,
7841 _ => return None,
7842 })
7843}
7844
7845/// Every `BLOCK_SIZES_ALL` footprint, as `(width, height)` in pixels: the six
7846/// squares, the ten 2:1 shapes and the six 1:4 ones (libaom `common_data.h`,
7847/// `block_size_wide`/`block_size_high`).
7848#[cfg(test)]
7849const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [
7850 (4, 4),
7851 (4, 8),
7852 (8, 4),
7853 (8, 8),
7854 (8, 16),
7855 (16, 8),
7856 (16, 16),
7857 (16, 32),
7858 (32, 16),
7859 (32, 32),
7860 (32, 64),
7861 (64, 32),
7862 (64, 64),
7863 (64, 128),
7864 (128, 64),
7865 (128, 128),
7866 (4, 16),
7867 (16, 4),
7868 (8, 32),
7869 (32, 8),
7870 (16, 64),
7871 (64, 16),
7872];
7873
7874/// lane-t900 r25, enumeration: the refusal "a motion_mode symbol for a block
7875/// shape with no CDF row here" names a shape no conformant stream can present.
7876///
7877/// A `motion_mode`/`obmc` symbol is read only under `motion_mode_eligible`,
7878/// whose `write_w.min(write_h) >= 8` clause is libaom's
7879/// `is_motion_variation_allowed_bsize` (`blockd.h:1455`). So the reachable
7880/// domain of [`motion_mode_cdf_row`] is exactly the `BLOCK_SIZES_ALL`
7881/// footprints with `min(bw, bh) >= 8` -- 17 of the 22 -- and each of those
7882/// must map to a distinct row of the 17-row `Cdfs::motion_mode` table. The
7883/// five it excludes (4x4, 4x8, 8x4, 4x16, 16x4) are the ones the eligibility
7884/// clause rejects before the lookup.
7885#[test]
7886fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() {
7887 let mut rows = std::collections::BTreeSet::new();
7888 let mut excluded = 0;
7889 for (w, h) in BLOCK_SIZES_ALL_WH {
7890 if w.min(h) < 8 {
7891 excluded += 1;
7892 assert!(
7893 w == 4 || h == 4,
7894 "{w}x{h} is not one of the sub-8 shapes is_motion_variation_allowed_bsize rejects"
7895 );
7896 continue;
7897 }
7898 let row = motion_mode_cdf_row(w, h).unwrap_or_else(|| {
7899 panic!(
7900 "a {w}x{h} block passes is_motion_variation_allowed_bsize and reads a motion_mode \
7901 symbol, but has no CDF row -- the refusal is a real gap, not a dead arm"
7902 )
7903 });
7904 assert!(
7905 row < 17,
7906 "{w}x{h} maps to motion_mode row {row}, outside the 17-row table"
7907 );
7908 assert!(rows.insert(row), "{w}x{h} shares motion_mode row {row}");
7909 }
7910 assert_eq!(excluded, 5, "the sub-8 footprint set changed");
7911 assert_eq!(
7912 rows.len(),
7913 17,
7914 "17 eligible footprints must fill all 17 rows of the motion_mode table"
7915 );
7916}
7917
7918fn decode_intra_rect_in_inter(
7919 dec: &mut SymbolDecoder,
7920 cdfs: &mut Cdfs,
7921 neighbours: &mut Neighbours,
7922 at: (usize, usize),
7923 bw: usize,
7924 bh: usize,
7925 skip: bool,
7926 allow_screen_content_tools: bool,
7927 // `(PARTITION_HORZ_4, is_chroma_reference)` when this strip is one of the
7928 // four 16x4 / 4x16 strips of a 16x16-level 1:4 partition (lane-intra16x4).
7929 strip16: Option<(bool, bool)>,
7930 y: &mut PlaneBuf,
7931 u: &mut PlaneBuf,
7932 v: &mut PlaneBuf,
7933 base_q_idx: u8,
7934) -> Result<()> {
7935 // `at` is in MI units (the inter path's own unit since lane-inter4);
7936 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands
7937 // below are still keyed by.
7938 let (mi_r, mi_c) = at;
7939 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
7940 // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat`
7941 // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 /
7942 // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx
7943 // finding -- the category is NOT the same for every strip size).
7944 // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so
7945 // it is refused by name rather than read from the wrong CDF row.
7946 // lane-intra16x4: the 16x16-level 1:4 strip. `size_group_lookup`
7947 // (common_data.h:61) puts BLOCK_16X4/BLOCK_4X16 in group 0 and its
7948 // tx-depth category is 1 -- but nothing here has to know either, because
7949 // the strip decodes through the very body the KEY FRAME path proves for
7950 // this shape ([`decode_rect4_16_strip`]), including the 4:2:0 chroma
7951 // pairing (`is_chroma_reference`: strips 0 and 2 read no chroma at all,
7952 // strips 1 and 3 code one 8x4 (4x8) unit at the PAIR's origin). The only
7953 // inter-frame difference is the mode-info read, which
7954 // [`INTRA_IN_INTER_MODE`] switches to `read_intra_block_mode_info`'s
7955 // `y_mode[0]` plus the `skip` this caller already read.
7956 if let Some((horz, has_chroma)) = strip16 {
7957 // lane-t900 r22: the screen-content refusal here was STALE (class
7958 // stale-premise): [`decode_rect4_16_strip`] takes
7959 // `allow_screen_content_tools` and reads the whole palette syntax
7960 // (mode/size/colours/colour-index map, its own `palette_ctx_and_cache_mi`
7961 // pair) -- the key frame proves that body. Lifted with the 10-bit
7962 // witness `palette_screen_witness_10bit.obu`, whose inter frames carry
7963 // 16x4/4x16 intra strips inside a `--tune-content=screen` frame.
7964 debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) });
7965 INTRA_IN_INTER_MODE.with(|c| c.set(Some((0, skip))));
7966 let res = decode_rect4_16_strip(
7967 dec,
7968 cdfs,
7969 neighbours,
7970 (mi_r, mi_c),
7971 horz,
7972 has_chroma,
7973 // The inter strips of the same partition publish their own
7974 // mi-exact mode, so the key-frame caller's coarse-cell stand-in
7975 // has nothing to add here.
7976 None,
7977 y,
7978 u,
7979 v,
7980 ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get),
7981 allow_screen_content_tools,
7982 base_q_idx,
7983 TX_SELECT_INTER.with(std::cell::Cell::get),
7984 REDUCED_TX_SET_INTER.with(std::cell::Cell::get),
7985 );
7986 INTRA_IN_INTER_MODE.with(|c| c.set(None));
7987 let (mode, uv, (tx_w, tx_h)) = res?;
7988 // lane-intra16x4, the same publication the 2:1 intra-in-inter strip
7989 // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs
7990 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` for EVERY
7991 // block of an inter frame, intra ones included, and
7992 // `txfm_partition_update` for the var-tx context. The key-frame body
7993 // writes neither (a key frame has no var-tx tree and its own readers
7994 // use the deblock grid), so the block AFTER this strip read a stale
7995 // band -- measured: a 128x128 8-bit stream decoded the two intra 16x4
7996 // strips at mi(23,16)/(23,20) exactly and then broke on the very next
7997 // 16x16 row.
7998 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
7999 for i in 0..bw / MI {
8000 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
8001 *cell = tx_w as u8;
8002 }
8003 }
8004 for i in 0..bh / MI {
8005 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
8006 *cell = tx_h as u8;
8007 }
8008 }
8009 // [`decode_rect4_16`]'s own post-loop publication, per strip (the
8010 // coarse 16-px cell holds one entry for the whole 16x16 and the last
8011 // block to write it wins).
8012 neighbours.above_mode[c] = mode;
8013 neighbours.left_mode[r] = mode;
8014 if let Some(uvm) = uv {
8015 neighbours.above_uv_mode[c] = uvm;
8016 neighbours.left_uv_mode[r] = uvm;
8017 }
8018 neighbours.above_side[c] = bw;
8019 neighbours.left_side[r] = bh;
8020 if crate::envflags::env_flag!("EC_INTRA16X4") {
8021 eprintln!(
8022 "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}",
8023 mi_c * MI,
8024 mi_r * MI
8025 );
8026 }
8027 INTRA16X4_IN_INTER_HITS.with(|h| {
8028 let mut v = h.get();
8029 v[usize::from(!horz)] += 1;
8030 v[2] += usize::from(has_chroma);
8031 h.set(v);
8032 });
8033 return Ok(());
8034 }
8035 // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half
8036 // coded INTRA inside an inter frame. `size_group_lookup` (common_data.h:61)
8037 // puts BLOCK_128X64/64X128/128X128 in group 3 and
8038 // `max_txsize_rect_lookup` caps them at TX_64X64, i.e. the same
8039 // `tx_size_cat3` row [`decode_block_128rect`] already reads -- so the whole
8040 // block decodes through the very body the KEY FRAME path proves for this
8041 // shape (square 64x64 luma units, one TX_32X32 chroma unit per 64x64 mu
8042 // chunk on the offset-10 txb_skip rows, per-TU prediction, the mu-chunk
8043 // `Reach` rule and the frame-edge write clip). The only inter-frame
8044 // differences live inside that body: the mode-info read
8045 // ([`INTRA_IN_INTER_MODE`] -> `y_mode[3]` plus the `skip` this caller
8046 // already read), the `tx_depth` context (the real TXFM_CONTEXT bands) and
8047 // the `set_txfm_ctxs` publication. CfL (>32), filter intra (>32) and
8048 // palette (>64) do not exist at this size and are refused by name there.
8049 // lane-t900 r18: the opt-in is LIFTED -- the arm has a witness.
8050 // `intra128_in_inter_witness2.obu` (gate
8051 // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`)
8052 // fires it 3x 128x64 + 6x 64x128 and decodes byte-exact on every plane of
8053 // all 15 frames, so the hits are counted out of exact frames (class
8054 // `counter-from-refused-stream`). What r16/r17 could not find, and what
8055 // that recipe exploits: libaom's RD essentially never PICKS a 128-root
8056 // HORZ/VERT in the interior -- the 512x512 r16 witness and a textured
8057 // 640x384 sweep code 128 roots as NONE or SPLIT only. The shape appears
8058 // where the frame EDGE forces it: a partial last superblock row has
8059 // `has_rows128 == false`, so the 128x64 top half is implied, and a
8060 // partial last column implies the 64x128 left half. Put content no
8061 // reference holds (a fresh smooth ramp) in exactly those two bands of an
8062 // inter frame and the encoder codes those forced halves INTRA.
8063 if bw.max(bh) == 128 {
8064 if allow_screen_content_tools {
8065 return Err(unsupported(
8066 "a HORZ/VERT intra strip in a screen-content frame (palette syntax \
8067 is consumed for square blocks only)",
8068 ));
8069 }
8070 if coeff_trace_on() {
8071 // lane-t900 r16: which decode-order frame this arm fires in --
8072 // interleaved with the `EC_COEFF_FRAME` markers, this is what
8073 // proves the hit is counted out of a frame that compares exact
8074 // (class `counter-from-refused-stream`).
8075 eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}");
8076 }
8077 INTRA_IN_INTER_MODE.with(|c| c.set(Some((3, skip))));
8078 let res = decode_block_128rect(
8079 dec,
8080 cdfs,
8081 neighbours,
8082 (r, c),
8083 bw,
8084 bh,
8085 y,
8086 u,
8087 v,
8088 base_q_idx,
8089 ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get),
8090 allow_screen_content_tools,
8091 TX_SELECT_INTER.with(std::cell::Cell::get),
8092 REDUCED_TX_SET_INTER.with(std::cell::Cell::get),
8093 );
8094 INTRA_IN_INTER_MODE.with(|c| c.set(None));
8095 return res;
8096 }
8097 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {
8098 if crate::envflags::env_flag!("EC_OBMCREC") {
8099 eprintln!(
8100 "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}"
8101 );
8102 }
8103 // lane-obmcrec r1: the message used to name a 16x4/4x16 strip
8104 // (class refusal-names-a-correlate). lane-t900 r20: the shapes that
8105 // can arrive here are enumerated against the measured block-shape
8106 // census ([`INTER_BLOCK_SHAPES`]) by
8107 // [`every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`]
8108 // -- every one of them has a row, so this arm names a shape no stream
8109 // has been able to present.
8110 return Err(unsupported(format!(
8111 "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"
8112 )));
8113 };
8114 // lane-t900 r21: this arm used to refuse EVERY rect strip of a
8115 // screen-content frame ("palette syntax is consumed for square blocks
8116 // only"). It is not: [`read_intra_mode_rect`] generalised the palette read
8117 // to rect blocks on the key-frame path, and the 1:4 arm below goes through
8118 // it, while the 2:1 reader inlined further down now codes the same syntax
8119 // itself. A real `--tune-content=screen` inter stream reached this refusal
8120 // on 8x16 / 16x8 strips (gate
8121 // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`).
8122 // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY
8123 // FRAME path already proves for this shape ([`decode_block_rect4`] at the
8124 // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4
8125 // luma/chroma transform tables, the per-unit split walk and the strip's
8126 // own neighbour records). The ONLY difference on an inter frame is the
8127 // mode-info read, which [`INTRA_IN_INTER_MODE`] switches to
8128 // `read_intra_block_mode_info`'s `y_mode[size_group]` plus the `skip`
8129 // this caller already read. `tx_cat` above is the same category those
8130 // readers hardcode (cat 2 in `decode_block_rect4`, cat 3 in
8131 // `decode_block_rect64`), asserted here so a future shape cannot drift.
8132 if bw.max(bh) == 4 * bw.min(bh) {
8133 debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 });
8134 INTRA_IN_INTER_MODE.with(|c| c.set(Some((size_group, skip))));
8135 let res = if bw.max(bh) == 64 {
8136 decode_block_rect64(
8137 dec,
8138 cdfs,
8139 neighbours,
8140 (mi_r / (SUB / MI), mi_c / (SUB / MI)),
8141 bw,
8142 bh,
8143 y,
8144 u,
8145 v,
8146 ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get),
8147 allow_screen_content_tools,
8148 base_q_idx,
8149 TX_SELECT_INTER.with(std::cell::Cell::get),
8150 REDUCED_TX_SET_INTER.with(std::cell::Cell::get),
8151 )
8152 } else {
8153 decode_block_rect4(
8154 dec,
8155 cdfs,
8156 neighbours,
8157 (mi_r, mi_c),
8158 bw,
8159 bh,
8160 None,
8161 y,
8162 u,
8163 v,
8164 ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get),
8165 allow_screen_content_tools,
8166 base_q_idx,
8167 TX_SELECT_INTER.with(std::cell::Cell::get),
8168 )
8169 .map(|_| ())
8170 };
8171 INTRA_IN_INTER_MODE.with(|c| c.set(None));
8172 res?;
8173 let shape = match (bw, bh) {
8174 (64, 16) => 0,
8175 (16, 64) => 1,
8176 (32, 8) => 2,
8177 _ => 3,
8178 };
8179 INTRA_RECT4_IN_INTER_HITS.with(|h| {
8180 let mut v = h.get();
8181 v[shape] += 1;
8182 h.set(v);
8183 });
8184 return Ok(());
8185 }
8186 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
8187 // lane-t900 r1: this arm read six mode symbols with no ladder rung of its
8188 // own, so a cross-decoder bisection could only see the block's first
8189 // coefficient. Same names/format as [`read_tx_size`]'s rung.
8190 let step_trace = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
8191 if step_trace {
8192 eprintln!(
8193 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}",
8194 dec.debug_state().0
8195 );
8196 }
8197 if mode >= 13 {
8198 return Err(unsupported(
8199 "an intra mode this decoder does not code (round 2)",
8200 ));
8201 }
8202 // lane-angleinter (merged on main for the square intra-in-inter arm):
8203 // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the
8204 // directional predictor; this arm refused a nonzero one before the merge.
8205 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
8206 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
8207 } else {
8208 0
8209 };
8210 if angle_delta_y != 0 {
8211 INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.set(c.get() + 1));
8212 }
8213 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
8214 // superblock-level strip reads the no-CFL alphabet -- the same split
8215 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
8216 let cfl_allowed = bw.max(bh) <= 32;
8217 let uv_mode = if cfl_allowed {
8218 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
8219 } else {
8220 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
8221 };
8222 if step_trace {
8223 eprintln!(
8224 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}",
8225 u8::from(cfl_allowed),
8226 dec.debug_state().0
8227 );
8228 }
8229 if (9..=12).contains(&uv_mode) {
8230 SMOOTH_UV_HITS.with(|h| h.set(h.get() + 1));
8231 }
8232 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
8233 Some(read_cfl_alphas(dec, cdfs))
8234 } else {
8235 None
8236 };
8237 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
8238 DC_PRED
8239 } else {
8240 uv_mode
8241 };
8242 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
8243 DIRECTIONAL_UV_HITS.with(|h| h.set(h.get() + 1));
8244 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
8245 } else {
8246 0
8247 };
8248 if angle_delta_uv != 0 {
8249 UV_ANGLE_DELTA_HITS.with(|h| h.set(h.get() + 1));
8250 INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|h| h.set(h.get() + 1));
8251 }
8252 // `read_palette_mode_info` (spec 5.11.13), in the position
8253 // `read_intra_block_mode_info` writes it: after the chroma mode and
8254 // before `filter_intra`. lane-t900 r21: a `--tune-content=screen` inter
8255 // frame writes `palette_y_mode`/`palette_uv_mode` for every block whose
8256 // shape [`palette_bsize_ctx_wh`] admits, intra strips included, so
8257 // skipping the syntax here desynced the tile at the strip's own symbol.
8258 // lane-t900 r22: reconstructed, not refused -- the strip's real mode
8259 // context and colour cache at its own mi position, and the two
8260 // colour-index maps decoded after `filter_intra` (`av1_visit_palette`),
8261 // exactly as [`read_intra_mode_rect`] does on the key-frame path.
8262 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi((mi_r, mi_c));
8263 let palette_uv_cache = neighbours.palette_uv_cache_mi((mi_r, mi_c));
8264 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
8265 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
8266 if allow_screen_content_tools
8267 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
8268 {
8269 INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(c.get() + 1));
8270 let use_palette_y =
8271 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0;
8272 if use_palette_y {
8273 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
8274 palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache)));
8275 }
8276 // A 2:1 strip of at least 8x8 is always a chroma reference, so
8277 // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here.
8278 let use_palette_uv =
8279 uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
8280 if crate::envflags::env_flag!("EC_PALSYN") {
8281 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);
8282 }
8283 if use_palette_uv {
8284 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
8285 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache);
8286 palette_uv_pending = Some((n, u_colors, v_colors));
8287 }
8288 }
8289 // lane-fiinter (merged on main for the square intra-in-inter arm):
8290 // `read_filter_intra_mode_info` is the tail of
8291 // `read_intra_block_mode_info`, after the palette syntax (refused whole
8292 // above for this shape), and `av1_filter_intra_allowed_bsize` admits the
8293 // 2:1 strips with both sides <= 32 -- their own CDF rows
8294 // ([`filter_intra_size_class_rect`]).
8295 let mut filter_intra = None;
8296 if mode == DC_PRED
8297 && ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get)
8298 // `av1_filter_intra_allowed` excludes a palette-Y block.
8299 && palette_y_pending.is_none()
8300 && let Some(class) = filter_intra_size_class_rect(bw, bh)
8301 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
8302 {
8303 FILTER_INTRA_HITS.with(|h| h.set(h.get() + 1));
8304 INTRA_IN_INTER_FILTER_INTRA_HITS.with(|h| h.set(h.get() + 1));
8305 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
8306 }
8307 // `av1_visit_palette`: Y's colour-index map then the shared chroma one.
8308 let palette_y = palette_y_pending.map(|(n, colors)| {
8309 let map = decode_color_index_map_wh(dec, cdfs, n, bw, bh, false);
8310 PALETTE_HITS.with(|c| c.set(c.get() + 1));
8311 PALETTE_RECT_HITS.with(|c| c.set(c.get() + 1));
8312 INTRA_IN_INTER_PALETTE_Y_HITS.with(|c| c.set(c.get() + 1));
8313 PaletteY { size: n, colors, map }
8314 });
8315 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
8316 let (cw, ch) = ((bw / 2).max(4), (bh / 2).max(4));
8317 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, true);
8318 PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
8319 INTRA_IN_INTER_PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
8320 PaletteUv { size: n, u_colors, v_colors, map }
8321 });
8322 // The intra-edge filter type is the NEIGHBOUR's mode (libaom
8323 // `get_filt_type`), luma's off the luma neighbours and chroma's off the
8324 // chroma ones -- [`decode_block_rect`]'s own pair.
8325 // lane-t900 r4: the coarse pair is keyed on the 16x16 cell's OWN top-left
8326 // mi, so both 8x16 halves of a VERT split read the neighbours of the FIRST
8327 // half. libaom's `above_mbmi`/`left_mbmi` are this block's own
8328 // (`mi[-mi_stride]` / `mi[-1]`) -- take the mi-exact pair over the coarse
8329 // one exactly as [`decode_leaf8`] already does (class
8330 // context-read-from-one-cell).
8331 let coarse_pair = neighbours.modes_above_left(r, c);
8332 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, coarse_pair);
8333 if (nb_above_mode, nb_left_mode) != coarse_pair {
8334 EDGE_FILTER_MI_FIX_HITS.with(|c| c.set(c.get() + 1));
8335 }
8336 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
8337 if smooth_neighbor {
8338 SMOOTH_LUMA_HITS.with(|h| h.set(h.get() + 1));
8339 }
8340 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
8341 let depth = if TX_SELECT_INTER.with(std::cell::Cell::get) {
8342 // The INTER frame's own `TXFM_CONTEXT` bands, not the key frame's
8343 // deblock-grid approximation -- [`tx_size_context_txfm_rect`].
8344 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64));
8345 let d = match tx_cat {
8346 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
8347 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
8348 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
8349 };
8350 if step_trace {
8351 eprintln!(
8352 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}",
8353 dec.debug_state().0
8354 );
8355 }
8356 d
8357 } else {
8358 0
8359 };
8360 if depth != 0 {
8361 TX_DEPTH_HITS.with(|h| h.set(h.get() + 1));
8362 // lane-intrasplit r1: a split intra strip in an inter frame walks the
8363 // key frame's own per-TU path ([`decode_rect_split`] below); what was
8364 // wrong when this refusal was written was the depth SYMBOL, not the walk.
8365 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(|h| {
8366 let mut v = h.get();
8367 v[depth.min(2)] += 1;
8368 h.set(v);
8369 });
8370 }
8371 // lane-intrasplit r3: print EVERY intra strip with its depth, not only the
8372 // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and
8373 // the two are indistinguishable when the diagnostic fires on splits alone.
8374 if crate::envflags::env_flag!("EC_SPLITSTRIP") {
8375 eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}");
8376 }
8377 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
8378 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,
8379 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block
8380 // of an inter frame, intra ones included -- with the skip term 0 it
8381 // memsets `above_txfm_context` to `tx_size_wide` over the block's width
8382 // and `left_txfm_context` to `tx_size_high` over its height. This strip
8383 // wrote neither, so the next block's var-tx `txfm_partition` context read
8384 // a stale band: on a 192x128 8-bit stream the 16x8 intra strip at
8385 // mi(14,0) left 8 where libaom has 16, giving ctx 13 instead of 12 at
8386 // mi(16,0) and desyncing the tile at that symbol.
8387 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
8388 let modes = RectStripModes {
8389 skip,
8390 mode,
8391 angle_delta_y,
8392 uv_predict_mode,
8393 angle_delta_uv,
8394 alpha,
8395 filter_intra,
8396 smooth_neighbor,
8397 smooth_neighbor_uv,
8398 palette_y: palette_y
8399 .as_ref()
8400 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
8401 palette_uv: palette_uv.as_ref().map(|p| {
8402 (
8403 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
8404 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
8405 )
8406 }),
8407 };
8408 decode_rect_split(
8409 dec,
8410 cdfs,
8411 neighbours,
8412 (mi_r, mi_c),
8413 bw,
8414 bh,
8415 tx_w,
8416 tx_h,
8417 &modes,
8418 y,
8419 u,
8420 v,
8421 base_q_idx,
8422 REDUCED_TX_SET_INTER.with(std::cell::Cell::get),
8423 )?;
8424 // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of
8425 // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in
8426 // both `TXFM_CONTEXT` bands -- the above row over the block's width, the
8427 // left column over its height. This arm wrote neither before lane-intrasplit
8428 // r1, so every later block in the frame read a stale `tx_size`/`txfm_split`
8429 // context across the strip's footprint.
8430 for i in 0..bw / MI {
8431 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
8432 *cell = tx_w as u8;
8433 }
8434 }
8435 for i in 0..bh / MI {
8436 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
8437 *cell = tx_h as u8;
8438 }
8439 }
8440 // The strip's own palette state into the mi-granular neighbour bands, so
8441 // the next block's colour cache and `palette_y_mode` context are libaom's.
8442 record_strip_palette(
8443 neighbours,
8444 (mi_r, mi_c),
8445 bw,
8446 bh,
8447 palette_y.as_ref().map_or(0, |p| p.size),
8448 palette_y.as_ref().map_or([0u16; 8], |p| p.colors),
8449 palette_uv.as_ref().map_or(0, |p| p.size),
8450 palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors),
8451 );
8452 let class = match bw.max(bh) {
8453 64 => 0,
8454 32 => 1,
8455 _ => 2,
8456 };
8457 INTRA_RECT_IN_INTER_HITS.with(|h| {
8458 let mut v = h.get();
8459 v[class] += 1;
8460 h.set(v);
8461 });
8462 Ok(())
8463}
8464
8465/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
8466/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
8467/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
8468/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
8469/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
8470/// has no rectangular-transform coefficient reader, and a chroma plane here
8471/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
8472/// with no depth-based square-tiling escape the way luma's own resolved
8473/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
8474/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
8475#[allow(clippy::too_many_arguments)]
8476fn decode_block_rect(
8477 dec: &mut SymbolDecoder,
8478 cdfs: &mut Cdfs,
8479 neighbours: &mut Neighbours,
8480 at: (usize, usize),
8481 bw: usize,
8482 bh: usize,
8483 y: &mut PlaneBuf,
8484 u: &mut PlaneBuf,
8485 v: &mut PlaneBuf,
8486 enable_filter_intra: bool,
8487 allow_screen_content_tools: bool,
8488 base_q_idx: u8,
8489 tx_select: bool,
8490 reduced_tx_set: bool,
8491) -> Result<()> {
8492 let (r, c) = at;
8493 let (px, py) = (c * SUB, r * SUB);
8494 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
8495 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
8496 let palette_uv_cache = neighbours.palette_uv_cache(at);
8497 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
8498 read_intra_mode_rect(
8499 dec,
8500 cdfs,
8501 nb_above_mode,
8502 nb_left_mode,
8503 true,
8504 true,
8505 bw,
8506 bh,
8507 enable_filter_intra,
8508 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
8509 allow_screen_content_tools,
8510 Some((palette_ctx, &palette_cache)),
8511 &palette_uv_cache,
8512 r * (SUB / MI),
8513 c * (SUB / MI),
8514 )?;
8515 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
8516 if smooth_neighbor {
8517 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
8518 }
8519 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
8520 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
8521 // `uv_mode`, not the luma one.
8522 let smooth_neighbor_uv =
8523 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
8524 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
8525 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
8526 // rectangle just as happily), so a `use_filter_intra` strip at this level
8527 // predicts instead of refusing. The below-16x16 leaf arm
8528 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
8529 if filter_intra.is_some() {
8530 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
8531 }
8532 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
8533 DC_PRED
8534 } else {
8535 uv_mode
8536 };
8537 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
8538 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
8539 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
8540 // one did not, so with `--enable-tx-size-search=0` -- which several gate
8541 // recipes use -- the decoder consumed a symbol the encoder never wrote and
8542 // desynced the tile from that point on. That is why both strips of the
8543 // pinned HORZ quadrant were wrong from their very first pixel, and why our
8544 // range after the read equalled the oracle's range for the whole block.
8545 let depth = if tx_select {
8546 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
8547 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
8548 // the 16x4 intra-in-inter strips already do); the key frame's
8549 // deblock-grid approximation is only right where those bands were never
8550 // written. Measured on the 10-bit 1920x792 128-superblock stream,
8551 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
8552 // `tx_size_cat2` row 1 where libaom reads row 2.
8553 let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {
8554 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh)
8555 } else {
8556 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
8557 };
8558 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
8559 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
8560 eprintln!(
8561 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
8562 dec.debug_state().0
8563 );
8564 }
8565 d
8566 } else {
8567 0
8568 };
8569 if depth != 0 {
8570 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
8571 // lane-rectsplit r1: a split transform is predicted and reconstructed
8572 // per transform unit, each unit taking its edges from the previous
8573 // unit's reconstruction inside this same strip (spec 5.11.36) --
8574 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
8575 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
8576 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
8577 eprintln!(
8578 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
8579 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
8580 angle_y={angle_delta_y}"
8581 );
8582 }
8583 let modes = RectStripModes {
8584 skip,
8585 mode,
8586 angle_delta_y,
8587 uv_predict_mode,
8588 angle_delta_uv,
8589 alpha,
8590 filter_intra,
8591 smooth_neighbor,
8592 smooth_neighbor_uv,
8593 palette_y: palette_y
8594 .as_ref()
8595 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
8596 palette_uv: palette_uv.as_ref().map(|p| {
8597 (
8598 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
8599 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
8600 )
8601 }),
8602 };
8603 if palette_y.is_some() || palette_uv.is_some() {
8604 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
8605 }
8606 decode_rect_split(
8607 dec,
8608 cdfs,
8609 neighbours,
8610 (mi_r, mi_c),
8611 bw,
8612 bh,
8613 tx_w,
8614 tx_h,
8615 &modes,
8616 y,
8617 u,
8618 v,
8619 base_q_idx,
8620 reduced_tx_set,
8621 )?;
8622 // This early return skips this fn's own tail, so the palette
8623 // neighbour state has to be stamped HERE too: without it a split-tx
8624 // strip left the above/left palette arrays holding a DEAD block's
8625 // colours, and the next block's colour cache
8626 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
8627 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
8628 // and only those pixels were wrong (lane-palette2 r10).
8629 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
8630 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
8631 let (puv_size, puv_colors) =
8632 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
8633 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
8634 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
8635 return Ok(());
8636 }
8637 let (tx_w, tx_h) = (bw, bh);
8638 let (cpx, cpy) = (px / 2, py / 2);
8639 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
8640 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
8641 if crate::envflags::env_flag!("EC_AV1_TRACE") {
8642 let (rng, _) = dec.debug_state();
8643 eprintln!(
8644 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
8645 skip={} tx={depth} rng={rng}",
8646 skip as i32
8647 );
8648 }
8649 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
8650 // block's prediction is the reconstructed colour-index map, set fresh
8651 // right before each `reconstruct_rect` call below (lane-palette2 r4).
8652 if let Some(ref pyv) = palette_y {
8653 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
8654 set_palette_pred(buf);
8655 }
8656 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
8657 (
8658 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
8659 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
8660 )
8661 });
8662 if skip {
8663 y.reconstruct_rect(
8664 px,
8665 py,
8666 bw,
8667 bh,
8668 mode,
8669 angle_delta_y,
8670 reach,
8671 &vec![0i32; bw * bh],
8672 None,
8673 filter_intra,
8674 smooth_neighbor,
8675 );
8676 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
8677 if let Some((ub, _)) = &palette_uv_bufs {
8678 set_palette_pred(ub.clone());
8679 }
8680 u.reconstruct_rect(
8681 cpx,
8682 cpy,
8683 chroma_w,
8684 chroma_h,
8685 uv_predict_mode,
8686 angle_delta_uv,
8687 reach,
8688 &vec![0i32; chroma_w * chroma_h],
8689 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8690 None,
8691 smooth_neighbor_uv,
8692 );
8693 if let Some((_, vb)) = &palette_uv_bufs {
8694 set_palette_pred(vb.clone());
8695 }
8696 v.reconstruct_rect(
8697 cpx,
8698 cpy,
8699 chroma_w,
8700 chroma_h,
8701 uv_predict_mode,
8702 angle_delta_uv,
8703 reach,
8704 &vec![0i32; chroma_w * chroma_h],
8705 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8706 None,
8707 smooth_neighbor_uv,
8708 );
8709 neighbours.record_rect(
8710 at,
8711 bw,
8712 bh,
8713 mode,
8714 uv_predict_mode,
8715 &[
8716 vec![0i32; bw * bh],
8717 vec![0i32; chroma_w * chroma_h],
8718 vec![0i32; chroma_w * chroma_h],
8719 ],
8720 );
8721 } else {
8722 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
8723 // reduces both size pairs to their square-up CDF sets
8724 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
8725 // doc comments); the scan order and 2D context tables are the real
8726 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
8727 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 32 {
8728 (&SCAN_32X16, &SCAN_16X8)
8729 } else {
8730 (&SCAN_16X32, &SCAN_8X16)
8731 };
8732 // lane-rectwire r3: real coefficients desync a pixel-exact gate
8733 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
8734 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
8735 // pixel (not a subtle context-table off-by-one), while the sibling
8736 // non-rect quadrants of the same frame match. Range-ladder bisection
8737 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
8738 // but the intra key-frame path has no traced symbol between the
8739 // partition read and the first coefficient block (mode/skip/tx_depth
8740 // reads are all untraced in libaom's decodeframe.c intra path, unlike
8741 // the inter EC_TRACE_MODE this round added), so a same-length range
8742 // comparison wasn't reachable within budget -- see
8743 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
8744 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
8745 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
8746 // libaom and match). lane-rectwire r4: range-ladder against the
8747 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
8748 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
8749 // both confirmed in sync -- rng=58692 on both sides right after
8750 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
8751 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
8752 // immediately after: ours moves rng 58692 -> 43570, which cannot be
8753 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
8754 // its own tx_size read) unless oracle's tx symbol is a near-certainty
8755 // CDF that barely narrows the range -- i.e. this decoder's
8756 // `tx_size_context_rect` ctx or `cdfs.tx_size_cat2` CDF selection for
8757 // a 32x16/16x32 strip is the first diverging symbol, not the
8758 // coefficient-context math r3 already cleared. Not confirmed byte-
8759 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
8760 // `read_tx_size`'s own rng, not attempted this round -- budget), so
8761 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
8762 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
8763 // it unconditionally where both square paths gate on `tx_select`. With
8764 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
8765 // decoder consumed one that was never there.
8766 {
8767 let around = neighbours.around_rect(at, bw, bh);
8768 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
8769 let (luma_levels, luma_tx_type) = read_coeffs_rect(
8770 dec,
8771 &mut luma_coding,
8772 luma_scan,
8773 bw,
8774 bh,
8775 0,
8776 dc_sign_ctx(around[0].2),
8777 TxType::DctDct,
8778 )?;
8779 if crate::envflags::env_flag!("EC_AV1_TRACE") {
8780 let (rng, _) = dec.debug_state();
8781 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
8782 }
8783 let luma_residual = dequant_and_inverse_typed_wh(
8784 &luma_levels,
8785 bw,
8786 bh,
8787 crate::decode::bit_depth(),
8788 block_q_idx(),
8789 plane_q_delta(0).0,
8790 plane_q_delta(0).1,
8791 luma_tx_type,
8792 );
8793 y.reconstruct_rect(
8794 px,
8795 py,
8796 bw,
8797 bh,
8798 mode,
8799 angle_delta_y,
8800 reach,
8801 &luma_residual,
8802 None,
8803 filter_intra,
8804 smooth_neighbor,
8805 );
8806 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
8807 if let Some((ub, _)) = &palette_uv_bufs {
8808 set_palette_pred(ub.clone());
8809 }
8810 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
8811 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
8812 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
8813 let (u_levels, u_tx_type) = read_coeffs_rect(
8814 dec,
8815 &mut u_coding,
8816 chroma_scan,
8817 chroma_w,
8818 chroma_h,
8819 u_skip_ctx,
8820 dc_sign_ctx(around[1].2),
8821 u_default_tx,
8822 )?;
8823 if crate::envflags::env_flag!("EC_AV1_TRACE") {
8824 let (rng, _) = dec.debug_state();
8825 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
8826 }
8827 let u_residual = dequant_and_inverse_typed_wh(
8828 &u_levels,
8829 chroma_w,
8830 chroma_h,
8831 crate::decode::bit_depth(),
8832 block_q_idx(),
8833 plane_q_delta(1).0,
8834 plane_q_delta(1).1,
8835 u_tx_type,
8836 );
8837 u.reconstruct_rect(
8838 cpx,
8839 cpy,
8840 chroma_w,
8841 chroma_h,
8842 uv_predict_mode,
8843 angle_delta_uv,
8844 reach,
8845 &u_residual,
8846 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8847 None,
8848 smooth_neighbor_uv,
8849 );
8850 if let Some((_, vb)) = &palette_uv_bufs {
8851 set_palette_pred(vb.clone());
8852 }
8853 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
8854 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
8855 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
8856 let (v_levels, v_tx_type) = read_coeffs_rect(
8857 dec,
8858 &mut v_coding,
8859 chroma_scan,
8860 chroma_w,
8861 chroma_h,
8862 v_skip_ctx,
8863 dc_sign_ctx(around[2].2),
8864 v_default_tx,
8865 )?;
8866 if crate::envflags::env_flag!("EC_AV1_TRACE") {
8867 let (rng, _) = dec.debug_state();
8868 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
8869 }
8870 let v_residual = dequant_and_inverse_typed_wh(
8871 &v_levels,
8872 chroma_w,
8873 chroma_h,
8874 crate::decode::bit_depth(),
8875 block_q_idx(),
8876 plane_q_delta(2).0,
8877 plane_q_delta(2).1,
8878 v_tx_type,
8879 );
8880 v.reconstruct_rect(
8881 cpx,
8882 cpy,
8883 chroma_w,
8884 chroma_h,
8885 uv_predict_mode,
8886 angle_delta_uv,
8887 reach,
8888 &v_residual,
8889 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8890 None,
8891 smooth_neighbor_uv,
8892 );
8893 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
8894 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
8895 }
8896 }
8897 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
8898 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
8899 let (puv_size, puv_colors) =
8900 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
8901 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
8902 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
8903 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
8904 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
8905 if crate::envflags::env_flag!("EC_AV1_TRACE") {
8906 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
8907 }
8908 Ok(())
8909}
8910
8911/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
8912/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
8913/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
8914/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
8915/// the second strip of a HORZ/VERT split sits offset by half the 16x16
8916/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
8917/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
8918/// previous strip is directly above (same column, `mi_h` rows up) or
8919/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
8920/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
8921/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
8922/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
8923/// this strip's real position, never the coarse `record_rect` (which the
8924/// caller uses once, after both strips, exactly like the `VERT_B` arm next
8925/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
8926/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
8927/// chroma half (`TxbSet::ChromaRect8x4`), the two size classes one level
8928/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
8929#[allow(clippy::too_many_arguments)]
8930fn decode_leaf_rect(
8931 dec: &mut SymbolDecoder,
8932 cdfs: &mut Cdfs,
8933 neighbours: &mut Neighbours,
8934 outer_at: (usize, usize),
8935 leaf_mi: (usize, usize),
8936 bw: usize,
8937 bh: usize,
8938 prev_leaf: Option<((usize, usize), usize)>,
8939 y: &mut PlaneBuf,
8940 u: &mut PlaneBuf,
8941 v: &mut PlaneBuf,
8942 enable_filter_intra: bool,
8943 allow_screen_content_tools: bool,
8944 base_q_idx: u8,
8945 tx_select: bool,
8946 reduced_tx_set: bool,
8947) -> Result<usize> {
8948 let _ = base_q_idx;
8949 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
8950 eprintln!(
8951 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
8952 dec.debug_state().0
8953 );
8954 }
8955 let (r, c) = outer_at;
8956 let mut above_mode = neighbours.above_mode[c];
8957 let mut left_mode = neighbours.left_mode[r];
8958 let (mi_w, mi_h) = (bw / MI, bh / MI);
8959 if let Some(((pr, pc), pmode)) = prev_leaf {
8960 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
8961 above_mode = pmode;
8962 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
8963 left_mode = pmode;
8964 }
8965 }
8966 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
8967 // cannot hold the modes a split (or a pair of strips) leaves behind, so
8968 // when the map holds the block at exactly this strip's above/left mi it
8969 // is the neighbour libaom's `above_mi`/`left_mi` reads.
8970 // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND
8971 // availability-correct -- four 16x8 strips share one coarse 16x16
8972 // `left_mode` cell too, so the fallback must not stand in for an absent
8973 // tile-edge neighbour.
8974 let (above_mode, left_mode) =
8975 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
8976 let smooth_neighbor =
8977 is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
8978 if smooth_neighbor {
8979 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
8980 }
8981 // The palette-Y mode CDF row is picked by the neighbours' palette use
8982 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
8983 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
8984 // a palette narrows the wrong interval and desyncs the tile even when the
8985 // decoded bit is the same. The cell is the 16px-SUB cell containing the
8986 // leaf (the palette neighbour arrays have no finer granularity).
8987 // lane-kf900 r6: the leaf's REAL mi position -- the second leaf of a 16x8
8988 // pair sits 8 px into the 16px cell, and both the cache's superblock-top-row
8989 // exclusion and the neighbour palette lookup itself are mi-granular
8990 // (see [`Neighbours::palette_ctx_and_cache_mi`]).
8991 let pal_at = leaf_mi;
8992 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
8993 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
8994 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
8995 read_intra_mode_rect(
8996 dec,
8997 cdfs,
8998 above_mode,
8999 left_mode,
9000 true,
9001 true,
9002 bw,
9003 bh,
9004 enable_filter_intra,
9005 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
9006 allow_screen_content_tools,
9007 Some((palette_ctx, &palette_cache)),
9008 &palette_uv_cache,
9009 leaf_mi.0,
9010 leaf_mi.1,
9011 )?;
9012 // lane-kf900 r4: palette prediction on this shape, the same colour-index
9013 // map -> base colours buffer [`decode_block_rect`] hands each
9014 // `reconstruct_rect` through [`set_palette_pred`].
9015 if palette_y.is_some() || palette_uv.is_some() {
9016 RECT4_PALETTE_HITS.with(|c| c.set(c.get() + 1));
9017 }
9018 let palette_y_buf: Option<Vec<u16>> = palette_y
9019 .as_ref()
9020 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
9021 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
9022 (
9023 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
9024 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
9025 )
9026 });
9027 let (pal_y_size, pal_y_colors) =
9028 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
9029 let (pal_uv_size, pal_uv_colors) =
9030 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
9031 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
9032 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
9033 }
9034 if filter_intra.is_some() {
9035 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
9036 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
9037 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
9038 // below already makes; this refusal was square-only prose.
9039 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
9040 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.set(c.get() + 1));
9041 }
9042 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
9043 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
9044 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
9045 // a constant `false`.
9046 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
9047 let depth = if tx_select {
9048 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read
9049 // every other rect reader now does -- a no-op on a key frame.
9050 let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {
9051 tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh)
9052 } else {
9053 tx_size_context_rect(neighbours, leaf_mi, bw, bh)
9054 };
9055 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
9056 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
9057 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
9058 // count (3), different CDF row: a wrong-table read of a real symbol,
9059 // the class that cost lane-rectsplit r1 its 64x32 depth.
9060 // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's
9061 // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and
9062 // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this
9063 // function also decodes) sit at depth 2, so they read
9064 // `tx_size_cdf[1]` -- the same table a 16x16 square block reads --
9065 // while `tx_size_cat2` belongs to the 32-level shapes
9066 // ([`decode_block_rect`]). Both tables carry three symbols, so the
9067 // wrong one decodes a plausible depth from the wrong probabilities:
9068 // the range diverges silently at the first such leaf and every later
9069 // symbol in the tile is read from the wrong place (class
9070 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
9071 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
9072 } else {
9073 0
9074 };
9075 if depth != 0 {
9076 // The same per-transform-unit walk the bigger strips take
9077 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
9078 // depth 2), addressed at this leaf's own mi position.
9079 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
9080 SUB16_SPLIT_HITS.with(|c| c.set(c.get() + 1));
9081 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
9082 let modes = RectStripModes {
9083 skip,
9084 mode,
9085 angle_delta_y,
9086 uv_predict_mode,
9087 angle_delta_uv,
9088 alpha,
9089 filter_intra,
9090 smooth_neighbor,
9091 // lane-rectsplitx r3: the split arm hard-coded `false` here while
9092 // the unsplit arm below passes the real neighbour answer -- chroma
9093 // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type.
9094 smooth_neighbor_uv,
9095 palette_y: palette_y_buf.clone(),
9096 palette_uv: palette_uv_bufs.clone(),
9097 };
9098 if palette_y.is_some() || palette_uv.is_some() {
9099 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
9100 }
9101 decode_rect_split(
9102 dec,
9103 cdfs,
9104 neighbours,
9105 leaf_mi,
9106 bw,
9107 bh,
9108 tx_w,
9109 tx_h,
9110 &modes,
9111 y,
9112 u,
9113 v,
9114 base_q_idx,
9115 reduced_tx_set,
9116 )?;
9117 record_strip_palette(
9118 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
9119 );
9120 return Ok(mode);
9121 }
9122 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
9123 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
9124 let (cpx, cpy) = (px / 2, py / 2);
9125 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
9126 let (luma_levels, u_levels, v_levels);
9127 if skip {
9128 luma_levels = vec![0i32; bw * bh];
9129 u_levels = vec![0i32; chroma_w * chroma_h];
9130 v_levels = vec![0i32; chroma_w * chroma_h];
9131 if let Some(b) = &palette_y_buf {
9132 set_palette_pred(b.clone());
9133 }
9134 y.reconstruct_rect(
9135 px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra,
9136 smooth_neighbor,
9137 );
9138 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
9139 if let Some((ub, _)) = &palette_uv_bufs {
9140 set_palette_pred(ub.clone());
9141 }
9142 u.reconstruct_rect(
9143 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels,
9144 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv,
9145 );
9146 if let Some((_, vb)) = &palette_uv_bufs {
9147 set_palette_pred(vb.clone());
9148 }
9149 v.reconstruct_rect(
9150 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels,
9151 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv,
9152 );
9153 } else {
9154 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
9155 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
9156 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
9157 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
9158 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
9159 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
9160 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 16 {
9161 (&SCAN_16X8, &SCAN_8X4)
9162 } else {
9163 (&SCAN_8X16, &SCAN_4X8)
9164 };
9165 let around = neighbours.around_mi_rect(leaf_mi, bw, bh);
9166 let luma_set = if reduced_tx_set {
9167 TxbSet::LumaRect16x8
9168 } else {
9169 TxbSet::LumaRect16x8Set1
9170 };
9171 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
9172 let (l_levels, luma_tx_type) = read_coeffs_rect(
9173 dec, &mut luma_coding, luma_scan, bw, bh, 0, dc_sign_ctx(around[0].2), TxType::DctDct,
9174 )?;
9175 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
9176 let nz: Vec<(usize, i32)> = l_levels.iter().copied().enumerate().filter(|(_, v)| *v != 0).collect();
9177 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
9178 }
9179 luma_levels = l_levels;
9180 let luma_residual = dequant_and_inverse_typed_wh(
9181 &luma_levels, bw, bh, crate::decode::bit_depth(),
9182 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(0).0, plane_q_delta(0).1, luma_tx_type,
9183 );
9184 if let Some(b) = &palette_y_buf {
9185 set_palette_pred(b.clone());
9186 }
9187 y.reconstruct_rect(
9188 px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra,
9189 smooth_neighbor,
9190 );
9191 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
9192 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
9193 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
9194 let mut u_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
9195 let (u_l, u_tx_type) = read_coeffs_rect(
9196 dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx,
9197 dc_sign_ctx(around[1].2), u_default_tx,
9198 )?;
9199 u_levels = u_l;
9200 let u_residual = dequant_and_inverse_typed_wh(
9201 &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(),
9202 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(1).0, plane_q_delta(1).1, u_tx_type,
9203 );
9204 if let Some((ub, _)) = &palette_uv_bufs {
9205 set_palette_pred(ub.clone());
9206 }
9207 u.reconstruct_rect(
9208 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual,
9209 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv,
9210 );
9211 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
9212 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
9213 let mut v_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
9214 let (v_l, v_tx_type) = read_coeffs_rect(
9215 dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx,
9216 dc_sign_ctx(around[2].2), v_default_tx,
9217 )?;
9218 v_levels = v_l;
9219 let v_residual = dequant_and_inverse_typed_wh(
9220 &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(),
9221 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(2).0, plane_q_delta(2).1, v_tx_type,
9222 );
9223 if let Some((_, vb)) = &palette_uv_bufs {
9224 set_palette_pred(vb.clone());
9225 }
9226 v.reconstruct_rect(
9227 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual,
9228 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv,
9229 );
9230 RECT_LEAF_COEFF_HITS.with(|c| c.set(c.get() + 1));
9231 }
9232 neighbours.record_mi_rect(leaf_mi, bw, bh, &[luma_levels, u_levels, v_levels]);
9233 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
9234 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0);
9235 // The leaf's own palette state (`0` clears, as this site always did
9236 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT
9237 // AXIS only until the pair's closing leaf: the coarse cell holds one
9238 // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the
9239 // real left neighbour leaf 1 reads (lane-kf900 r4).
9240 record_strip_palette(
9241 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
9242 );
9243 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
9244 // rows -- record the whole span, not one cell.
9245 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
9246 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
9247 Ok(mode)
9248}
9249
9250/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
9251/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
9252/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
9253/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
9254/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
9255/// strip's mode so this one's mode context sees its true above/left
9256/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
9257///
9258/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
9259/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
9260/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
9261/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
9262/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
9263/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
9264/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
9265///
9266/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
9267/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
9268/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
9269/// unexamined.
9270#[allow(clippy::too_many_arguments)]
9271fn decode_block_rect4(
9272 dec: &mut SymbolDecoder,
9273 cdfs: &mut Cdfs,
9274 neighbours: &mut Neighbours,
9275 strip_mi: (usize, usize),
9276 bw: usize,
9277 bh: usize,
9278 prev_strip: Option<((usize, usize), usize)>,
9279 y: &mut PlaneBuf,
9280 u: &mut PlaneBuf,
9281 v: &mut PlaneBuf,
9282 enable_filter_intra: bool,
9283 allow_screen_content_tools: bool,
9284 base_q_idx: u8,
9285 tx_select: bool,
9286) -> Result<(usize, usize)> {
9287 let _ = base_q_idx;
9288 let (mi_r, mi_c) = strip_mi;
9289 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
9290 let (mi_w, mi_h) = (bw / MI, bh / MI);
9291 let mut above_mode = neighbours.above_mode[c];
9292 let mut left_mode = neighbours.left_mode[r];
9293 if let Some(((pr, pc), pmode)) = prev_strip {
9294 if pc == mi_c && mi_r == pr + mi_h {
9295 above_mode = pmode;
9296 } else if pr == mi_r && mi_c == pc + mi_w {
9297 left_mode = pmode;
9298 }
9299 }
9300 // lane-rectsplitx r2, ROOT CAUSE of the 1:4 mismatch: mi-exact +
9301 // availability-correct neighbour modes (see
9302 // [`Neighbours::modes_above_left_mi`]). The coarse 16x16 bands alias every
9303 // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell.
9304 let (above_mode, left_mode) =
9305 neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode));
9306 // lane-kf900 r4: this strip's own palette-Y mode ctx and colour cache.
9307 // Passing `None`/`&[]` read `palette_y_mode` off CDF row 0 and every
9308 // `palette_colors_y` cache hit off an EMPTY cache -- right symbol count,
9309 // wrong interval, so a screen-content tile desynced at the first strip
9310 // whose neighbour used a palette (class [[cdf-row-held-constant]]).
9311 let pal_at = (mi_r, mi_c);
9312 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
9313 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
9314 let (
9315 skip,
9316 mode,
9317 angle_delta_y,
9318 uv_mode,
9319 angle_delta_uv,
9320 alpha,
9321 filter_intra,
9322 palette_y,
9323 palette_uv,
9324 ) = read_intra_mode_rect(
9325 dec,
9326 cdfs,
9327 above_mode,
9328 left_mode,
9329 true,
9330 true,
9331 bw,
9332 bh,
9333 enable_filter_intra,
9334 neighbours.skip_txfm_ctx(mi_r, mi_c),
9335 allow_screen_content_tools,
9336 Some((palette_ctx, &palette_cache)),
9337 &palette_uv_cache,
9338 mi_r,
9339 mi_c,
9340 )?;
9341 // lane-kf900 r4: palette prediction on this shape, exactly as
9342 // [`decode_block_rect`] does one aspect ratio up -- the colour-index map
9343 // mapped through the base colours IS the prediction (it reads no edge
9344 // pixels), handed to each `reconstruct_rect` through [`set_palette_pred`].
9345 if palette_y.is_some() || palette_uv.is_some() {
9346 RECT4_PALETTE_HITS.with(|c| c.set(c.get() + 1));
9347 }
9348 let palette_y_buf: Option<Vec<u16>> = palette_y
9349 .as_ref()
9350 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
9351 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
9352 (
9353 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
9354 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
9355 )
9356 });
9357 let (pal_y_size, pal_y_colors) =
9358 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
9359 let (pal_uv_size, pal_uv_colors) =
9360 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
9361 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
9362 if smooth_neighbor {
9363 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
9364 }
9365 // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's
9366 // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so
9367 // `r * (SUB / MI)` names a different mi column and the chroma
9368 // edge-filter strength was read from the wrong neighbour (measured:
9369 // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch
9370 // with luma bit-exact).
9371 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
9372 if filter_intra.is_some() {
9373 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
9374 if bw > bh {
9375 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.set(c.get() + 1));
9376 } else {
9377 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.set(c.get() + 1));
9378 }
9379 }
9380 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
9381 DC_PRED
9382 } else {
9383 uv_mode
9384 };
9385 let depth = if tx_select {
9386 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
9387 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
9388 // the 16x4 intra-in-inter strips already do); the key frame's
9389 // deblock-grid approximation is only right where those bands were never
9390 // written. Measured on the 10-bit 1920x792 128-superblock stream,
9391 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
9392 // `tx_size_cat2` row 1 where libaom reads row 2.
9393 let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {
9394 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh)
9395 } else {
9396 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
9397 };
9398 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
9399 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
9400 eprintln!(
9401 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
9402 dec.debug_state().0
9403 );
9404 }
9405 d
9406 } else {
9407 0
9408 };
9409 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
9410 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
9411 publish_txfm_bands_if_in_inter(
9412 neighbours,
9413 (mi_r, mi_c),
9414 depth_to_tx_wh(bw, bh, depth),
9415 (bw, bh),
9416 );
9417 if depth != 0 {
9418 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
9419 // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a
9420 // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16
9421 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8;
9422 // both interleave in every real stream.
9423 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
9424 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
9425 // lane-rectsplitx r2: both depths ship together, as the r1 handoff
9426 // predicted -- depth 1 fires FIRST in every attempt that splits at
9427 // all, so a depth-2-only lift could never be gated. The r1 mismatch
9428 // was never the rect unit: it was the neighbour MODE the strip reads
9429 // (see `modes_above_left_mi`).
9430 let which = if depth == 1 {
9431 &RECT4_SPLIT_DEPTH1_HITS
9432 } else {
9433 &RECT4_SPLIT_DEPTH2_HITS
9434 };
9435 which.with(|c| c.set(c.get() + 1));
9436 let modes = RectStripModes {
9437 skip,
9438 mode,
9439 angle_delta_y,
9440 uv_predict_mode,
9441 angle_delta_uv,
9442 alpha,
9443 filter_intra,
9444 smooth_neighbor,
9445 smooth_neighbor_uv,
9446 palette_y: palette_y_buf.clone(),
9447 palette_uv: palette_uv_bufs.clone(),
9448 };
9449 if palette_y.is_some() || palette_uv.is_some() {
9450 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
9451 }
9452 decode_rect_split(
9453 dec,
9454 cdfs,
9455 neighbours,
9456 (mi_r, mi_c),
9457 bw,
9458 bh,
9459 tx_w,
9460 tx_h,
9461 &modes,
9462 y,
9463 u,
9464 v,
9465 base_q_idx,
9466 false,
9467 )?;
9468 record_strip_palette(
9469 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
9470 pal_uv_colors,
9471 );
9472 if bw > bh {
9473 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
9474 } else {
9475 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
9476 }
9477 if !skip {
9478 RECT4_COEFF_HITS.with(|c| c.set(c.get() + 1));
9479 }
9480 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
9481 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
9482 // frame, so this 1:4 strip -- which is also the INTER frame's reader
9483 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
9484 // transform size in both TXFM_CONTEXT bands. Without it the next block
9485 // reads the row's stale value.
9486 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
9487 return Ok((mode, uv_predict_mode));
9488 }
9489 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
9490 // that is 8 px tall, so each strip stamps every cell it touches and the
9491 // LAST strip wins -- which is the right answer for the block below/right
9492 // of the 32x32, the only reader outside it. Written after this strip's
9493 // own context read above, never before.
9494 for cell in 0..bw.div_ceil(SUB) {
9495 neighbours.above_mode[c + cell] = mode;
9496 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
9497 neighbours.above_side[c + cell] = bw;
9498 }
9499 for cell in 0..bh.div_ceil(SUB) {
9500 neighbours.left_mode[r + cell] = mode;
9501 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
9502 neighbours.left_side[r + cell] = bh;
9503 }
9504 // ...and the mi-EXACT maps the coarse cells alias away, exactly as
9505 // [`decode_leaf_rect`] does (the split arm above records these through
9506 // `record_mi_luma_rect`). Without this an unsplit 32x8 strip left
9507 // `sub8_mode_row` holding the previous block, and the next 32x32's
9508 // strips read a stale `kf_y_mode` row (measured: mi(4,8) on the band
9509 // fixture).
9510 neighbours.record_mode_mi(mi_r, mi_c, mi_w, mi_h, mode);
9511 neighbours.record_uv_mode_mi(mi_r, mi_c, mi_w, mi_h, uv_predict_mode);
9512 let (px, py) = (mi_c * MI, mi_r * MI);
9513 let (cpx, cpy) = (px / 2, py / 2);
9514 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
9515 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
9516 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw > bh {
9517 (&SCAN_32X8, &SCAN_16X4)
9518 } else {
9519 (&SCAN_8X32, &SCAN_4X16)
9520 };
9521 let (luma_levels, u_levels, v_levels) = if skip {
9522 (
9523 vec![0i32; bw * bh],
9524 vec![0i32; chroma_w * chroma_h],
9525 vec![0i32; chroma_w * chroma_h],
9526 )
9527 } else {
9528 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
9529 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
9530 let (luma_levels, luma_tx_type) = read_coeffs_rect(
9531 dec,
9532 &mut luma_coding,
9533 luma_scan,
9534 bw,
9535 bh,
9536 0,
9537 dc_sign_ctx(around[0].2),
9538 TxType::DctDct,
9539 )?;
9540 let mut planes = Vec::with_capacity(2);
9541 for plane in 1..3 {
9542 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
9543 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
9544 let mut coding = cdfs.txb(TxbSet::Chroma8, uv_predict_mode);
9545 let (levels, tx_type) = read_coeffs_rect(
9546 dec,
9547 &mut coding,
9548 chroma_scan,
9549 chroma_w,
9550 chroma_h,
9551 skip_ctx,
9552 dc_sign_ctx(around[plane].2),
9553 default_tx,
9554 )?;
9555 planes.push((levels, tx_type));
9556 }
9557 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
9558 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
9559 RECT4_COEFF_HITS.with(|c| c.set(c.get() + 1));
9560 let luma_residual = dequant_and_inverse_typed_wh(
9561 &luma_levels,
9562 bw,
9563 bh,
9564 crate::decode::bit_depth(),
9565 block_q_idx(),
9566 plane_q_delta(0).0,
9567 plane_q_delta(0).1,
9568 luma_tx_type,
9569 );
9570 if let Some(b) = &palette_y_buf {
9571 set_palette_pred(b.clone());
9572 }
9573 y.reconstruct_rect(
9574 px,
9575 py,
9576 bw,
9577 bh,
9578 mode,
9579 angle_delta_y,
9580 reach,
9581 &luma_residual,
9582 None,
9583 filter_intra,
9584 smooth_neighbor,
9585 );
9586 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
9587 for (plane, buf, levels, tx_type) in [
9588 (1usize, &mut *u, &u_levels, u_tx_type),
9589 (2, &mut *v, &v_levels, v_tx_type),
9590 ] {
9591 let residual = dequant_and_inverse_typed_wh(
9592 levels,
9593 chroma_w,
9594 chroma_h,
9595 crate::decode::bit_depth(),
9596 block_q_idx(),
9597 plane_q_delta(plane).0,
9598 plane_q_delta(plane).1,
9599 tx_type,
9600 );
9601 if let Some((ub, vb)) = &palette_uv_bufs {
9602 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() });
9603 }
9604 buf.reconstruct_rect(
9605 cpx,
9606 cpy,
9607 chroma_w,
9608 chroma_h,
9609 uv_predict_mode,
9610 angle_delta_uv,
9611 reach,
9612 &residual,
9613 alpha
9614 .zip(ac.as_deref())
9615 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
9616 None,
9617 smooth_neighbor_uv,
9618 );
9619 }
9620 neighbours.record_mi_rect(
9621 (mi_r, mi_c),
9622 bw,
9623 bh,
9624 &[luma_levels, u_levels, v_levels],
9625 );
9626 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
9627 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0);
9628 record_strip_palette(
9629 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
9630 pal_uv_colors,
9631 );
9632 if bw > bh {
9633 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
9634 } else {
9635 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
9636 }
9637 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
9638 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
9639 // frame, so this 1:4 strip -- which is also the INTER frame's reader
9640 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
9641 // transform size in both TXFM_CONTEXT bands. Without it the next block
9642 // reads the row's stale value.
9643 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
9644 return Ok((mode, uv_predict_mode));
9645 };
9646 if let Some(b) = &palette_y_buf {
9647 set_palette_pred(b.clone());
9648 }
9649 y.reconstruct_rect(
9650 px,
9651 py,
9652 bw,
9653 bh,
9654 mode,
9655 angle_delta_y,
9656 reach,
9657 &luma_levels,
9658 None,
9659 filter_intra,
9660 smooth_neighbor,
9661 );
9662 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
9663 if let Some((ub, _)) = &palette_uv_bufs {
9664 set_palette_pred(ub.clone());
9665 }
9666 u.reconstruct_rect(
9667 cpx,
9668 cpy,
9669 chroma_w,
9670 chroma_h,
9671 uv_predict_mode,
9672 angle_delta_uv,
9673 reach,
9674 &u_levels,
9675 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
9676 None,
9677 smooth_neighbor_uv,
9678 );
9679 if let Some((_, vb)) = &palette_uv_bufs {
9680 set_palette_pred(vb.clone());
9681 }
9682 v.reconstruct_rect(
9683 cpx,
9684 cpy,
9685 chroma_w,
9686 chroma_h,
9687 uv_predict_mode,
9688 angle_delta_uv,
9689 reach,
9690 &v_levels,
9691 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
9692 None,
9693 smooth_neighbor_uv,
9694 );
9695 neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[luma_levels.to_vec(), u_levels, v_levels]);
9696 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
9697 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0);
9698 record_strip_palette(
9699 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
9700 );
9701 if bw > bh {
9702 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
9703 } else {
9704 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
9705 }
9706 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
9707 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
9708 // frame, so this 1:4 strip -- which is also the INTER frame's reader
9709 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
9710 // transform size in both TXFM_CONTEXT bands. Without it the next block
9711 // reads the row's stale value.
9712 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
9713 Ok((mode, uv_predict_mode))
9714}
9715
9716/// Decodes the four 16x4 / 4x16 strips of a 16x16-level `PARTITION_HORZ_4` /
9717/// `PARTITION_VERT_4` (lane-r14) -- [`decode_block_rect4`]'s pair one level
9718/// down, and the first shape here whose luma block is a single mi row (or
9719/// column).
9720///
9721/// What is new at this size is CHROMA. `is_chroma_reference`
9722/// (`av1_common_int.h`) is false for a 4:2:0 block one mi tall (wide) on an
9723/// EVEN mi row (column), so strips 0 and 2 read no `uv_mode`/`cfl_alpha`/
9724/// `angle_delta_uv` at all and code no chroma residual; strips 1 and 3 close
9725/// the pair and carry the chroma of the whole 16x8 (8x16) luma pair --
9726/// `setup_pred_plane`'s own `if (subsampling_y && (mi_row & 1) &&
9727/// mi_size_high[bsize] == 1) mi_row -= 1` offset, i.e. an 8x4 (4x8) chroma
9728/// transform at the PAIR's origin, with CfL averaging over the pair's luma.
9729///
9730/// Tables: LUMA `TX_16X4`/`TX_4X16` averages to the 8x8 entropy context
9731/// ((0 + 2 + 1) >> 1 = 1) with 64 coded positions, so its CDF set is
9732/// [`TxbSet::LumaRect16x4`] (`Luma8`'s tables, the `TX_4X4` `tx_type` row);
9733/// scans are [`SCAN_16X4`]/[`SCAN_4X16`]. CHROMA `TX_8X4`/`TX_4X8` is
9734/// [`TxbSet::ChromaRect8x4`] with [`SCAN_8X4`]/[`SCAN_4X8`]. Angle deltas ARE
9735/// coded (`av1_use_angle_delta` compares the BLOCK_SIZES_ALL enum index, and
9736/// BLOCK_16X4 is 17), and so is `use_filter_intra` (both sides <= 32) off this
9737/// shape's own CDF row.
9738///
9739/// A split transform (`tx_depth != 0`, `sub_tx_size_map[TX_16X4] == TX_8X4`)
9740/// refuses by name rather than guess-decode.
9741#[allow(clippy::too_many_arguments)]
9742fn decode_rect4_16(
9743 dec: &mut SymbolDecoder,
9744 cdfs: &mut Cdfs,
9745 neighbours: &mut Neighbours,
9746 at16: (usize, usize),
9747 horz: bool,
9748 y: &mut PlaneBuf,
9749 u: &mut PlaneBuf,
9750 v: &mut PlaneBuf,
9751 enable_filter_intra: bool,
9752 allow_screen_content_tools: bool,
9753 base_q_idx: u8,
9754 tx_select: bool,
9755 reduced_tx_set: bool,
9756) -> Result<()> {
9757 let (r, c) = at16;
9758 let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI));
9759 let (bw, bh) = if horz { (16, 4) } else { (4, 16) };
9760 let (mi_w, mi_h) = (bw / MI, bh / MI);
9761 let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
9762 let chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
9763 let mut prev: Option<((usize, usize), usize)> = None;
9764 let mut last_mode = DC_PRED;
9765 let mut last_uv_mode = DC_PRED;
9766 for i in 0..4usize {
9767 let lmi = if horz {
9768 (mi_row0 + i, mi_col0)
9769 } else {
9770 (mi_row0, mi_col0 + i)
9771 };
9772 let has_chroma = i % 2 == 1;
9773 let (mode, uv, _tx) = decode_rect4_16_strip(
9774 dec,
9775 cdfs,
9776 neighbours,
9777 lmi,
9778 horz,
9779 has_chroma,
9780 prev,
9781 y,
9782 u,
9783 v,
9784 enable_filter_intra,
9785 allow_screen_content_tools,
9786 base_q_idx,
9787 tx_select,
9788 reduced_tx_set,
9789 )?;
9790 if let Some(m) = uv {
9791 last_uv_mode = m;
9792 }
9793 last_mode = mode;
9794 prev = Some((lmi, mode));
9795 }
9796 // The coarse 16-px cell holds one entry for the whole 16x16: the last
9797 // strip is what a block below (right) sees through it, the mi-exact maps
9798 // above answering everything finer.
9799 neighbours.above_mode[c] = last_mode;
9800 neighbours.left_mode[r] = last_mode;
9801 neighbours.above_uv_mode[c] = last_uv_mode;
9802 neighbours.left_uv_mode[r] = last_uv_mode;
9803 neighbours.above_side[c] = bw;
9804 neighbours.left_side[r] = bh;
9805 Ok(())
9806}
9807
9808/// One 16x4 / 4x16 strip of a 16x16-level 1:4 partition, intra-coded --
9809/// [`decode_rect4_16`]'s per-strip body, lifted (lane-intra16x4) so the INTER
9810/// block path can decode a SINGLE intra strip of a partition whose other
9811/// strips are inter. `prev` is the previous strip's `(mi, mode)` (the
9812/// key-frame caller's coarse-cell stand-in; `None` on the inter path, where
9813/// every strip publishes its own mi-exact mode). Returns
9814/// `(y_mode, uv_predict_mode when this strip closes the 4:2:0 chroma pair)`.
9815#[allow(clippy::too_many_arguments)]
9816fn decode_rect4_16_strip(
9817 dec: &mut SymbolDecoder,
9818 cdfs: &mut Cdfs,
9819 neighbours: &mut Neighbours,
9820 lmi: (usize, usize),
9821 horz: bool,
9822 has_chroma: bool,
9823 prev: Option<((usize, usize), usize)>,
9824 y: &mut PlaneBuf,
9825 u: &mut PlaneBuf,
9826 v: &mut PlaneBuf,
9827 enable_filter_intra: bool,
9828 allow_screen_content_tools: bool,
9829 base_q_idx: u8,
9830 tx_select: bool,
9831 reduced_tx_set: bool,
9832) -> Result<(usize, Option<usize>, (usize, usize))> {
9833 let (r, c) = (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI));
9834 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
9835 let (mi_w, mi_h) = (bw / MI, bh / MI);
9836 let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
9837 let chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
9838 let mut last_uv_mode: Option<usize> = None;
9839 // `decode_block_rect4`'s own neighbour rule: the coarse 16-px cell
9840 // aliases all four strips onto one entry, so the mi-exact map wins and
9841 // the previous strip stands in on the split axis.
9842 let mut above_mode = neighbours.above_mode[c];
9843 let mut left_mode = neighbours.left_mode[r];
9844 if let Some(((pr, pc), pmode)) = prev {
9845 if pc == lmi.1 && lmi.0 == pr + mi_h {
9846 above_mode = pmode;
9847 } else if pr == lmi.0 && lmi.1 == pc + mi_w {
9848 left_mode = pmode;
9849 }
9850 }
9851 let (above_mode, left_mode) =
9852 neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode));
9853 // lane-kf900 r4: the strip's real palette ctx + colour cache (see
9854 // [`decode_block_rect4`]); `None`/`&[]` here read `palette_y_mode`
9855 // off CDF row 0 and every cache hit off an empty cache.
9856 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(lmi);
9857 let palette_uv_cache = neighbours.palette_uv_cache_mi(lmi);
9858 let (
9859 skip,
9860 mode,
9861 angle_delta_y,
9862 uv_mode,
9863 angle_delta_uv,
9864 alpha,
9865 filter_intra,
9866 palette_y,
9867 palette_uv,
9868 ) = read_intra_mode_rect(
9869 dec,
9870 cdfs,
9871 above_mode,
9872 left_mode,
9873 true,
9874 has_chroma,
9875 bw,
9876 bh,
9877 enable_filter_intra,
9878 neighbours.skip_txfm_ctx(lmi.0, lmi.1),
9879 allow_screen_content_tools,
9880 Some((palette_ctx, &palette_cache)),
9881 &palette_uv_cache,
9882 lmi.0,
9883 lmi.1,
9884 )?;
9885 if palette_y.is_some() || palette_uv.is_some() {
9886 RECT4_PALETTE_HITS.with(|h| h.set(h.get() + 1));
9887 }
9888 // The colour-index map through the base colours IS the prediction.
9889 // Chroma's map is the PAIR's 8x4 (4x8) block, matching the one
9890 // chroma transform this closing strip codes.
9891 let palette_y_buf: Option<Vec<u16>> = palette_y
9892 .as_ref()
9893 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
9894 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
9895 (
9896 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
9897 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
9898 )
9899 });
9900 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
9901 if smooth_neighbor {
9902 SMOOTH_LUMA_HITS.with(|h| h.set(h.get() + 1));
9903 }
9904 if filter_intra.is_some() {
9905 FILTER_INTRA_RECT_HITS.with(|h| h.set(h.get() + 1));
9906 }
9907 // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is
9908 // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the
9909 // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol
9910 // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does.
9911 let depth = if tx_select {
9912 // lane-intra16x4: on an INTER frame `get_tx_size_context` reads the
9913 // real `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what
9914 // the 2:1 intra-in-inter strip already does); the key frame's
9915 // deblock-grid approximation is only right where those bands were
9916 // never written.
9917 let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {
9918 tx_size_context_txfm_rect(neighbours, lmi, bw, bh)
9919 } else {
9920 tx_size_context_rect(neighbours, lmi, bw, bh)
9921 };
9922 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
9923 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
9924 eprintln!(
9925 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
9926 lmi.0,
9927 lmi.1,
9928 dec.debug_state().0
9929 );
9930 }
9931 d
9932 } else {
9933 0
9934 };
9935 if depth != 0 {
9936 TX_DEPTH_HITS.with(|h| h.set(h.get() + 1));
9937 RECT4_16_SPLIT_HITS.with(|h| h.set(h.get() + 1));
9938 }
9939 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
9940 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
9941 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
9942 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode);
9943 if depth != 0 {
9944 // [`decode_rect_split`]'s per-unit walk, inlined because the
9945 // CHROMA of this shape belongs to the strip's 4:2:0 pair, not to
9946 // the strip (that function codes one chroma transform per block).
9947 // depth 1 is the 2:1 rect unit TX_8X4/TX_4X8
9948 // (`sub_tx_size_map[TX_16X4]`), depth 2 the square TX_4X4; each
9949 // unit predicts off the units before it in raster order.
9950 let rect_unit = tx_w != tx_h;
9951 let zero_tu = vec![0i32; tx_w * tx_h];
9952 for tu_row in 0..bh / tx_h {
9953 for tu_col in 0..bw / tx_w {
9954 let tu_mi = (lmi.0 + tu_row * (tx_h / MI), lmi.1 + tu_col * (tx_w / MI));
9955 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
9956 let tu_reach = Reach::of_tu(
9957 bw,
9958 bh,
9959 tu_col * tx_w,
9960 tu_row * tx_h,
9961 tx_w,
9962 tx_h,
9963 reach,
9964 );
9965 if let Some(b) = &palette_y_buf {
9966 let tu_buf: Vec<u16> = (0..tx_h)
9967 .flat_map(|i| {
9968 let base = (tu_row * tx_h + i) * bw + tu_col * tx_w;
9969 b[base..base + tx_w].iter().copied()
9970 })
9971 .collect();
9972 set_palette_pred(tu_buf);
9973 }
9974 if skip {
9975 y.reconstruct_rect(
9976 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &zero_tu,
9977 None, filter_intra, smooth_neighbor,
9978 );
9979 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
9980 } else if rect_unit {
9981 // `get_txsize_entropy_ctx(TX_8X4)` is the 8x8 class with
9982 // 32 coded positions and the `TX_4X4` `tx_type` row:
9983 // exactly [`TxbSet::LumaRect4x8`].
9984 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
9985 let tu_skip_ctx =
9986 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI);
9987 let set = if reduced_tx_set {
9988 TxbSet::LumaRect4x8
9989 } else {
9990 TxbSet::LumaRect4x8Set1
9991 };
9992 let tu_scan: &[u16] = if tx_w > tx_h { &SCAN_8X4 } else { &SCAN_4X8 };
9993 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
9994 let (tu_grid, tu_tx_type) = read_coeffs_rect(
9995 dec,
9996 &mut coding,
9997 tu_scan,
9998 tx_w,
9999 tx_h,
10000 tu_skip_ctx,
10001 dc_sign_ctx(tu_around.2),
10002 TxType::DctDct,
10003 )?;
10004 let residual = dequant_and_inverse_typed_wh(
10005 &tu_grid,
10006 tx_w,
10007 tx_h,
10008 crate::decode::bit_depth(),
10009 block_q_idx(),
10010 plane_q_delta(0).0,
10011 plane_q_delta(0).1,
10012 tu_tx_type,
10013 );
10014 y.reconstruct_rect(
10015 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &residual,
10016 None, filter_intra, smooth_neighbor,
10017 );
10018 if tu_grid.iter().any(|&l| l != 0) {
10019 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));
10020 }
10021 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
10022 } else {
10023 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
10024 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
10025 let tu_grid = read_plane(
10026 dec,
10027 cdfs,
10028 txbset_for(tx_w, reduced_tx_set),
10029 &default_scan(tx_w),
10030 0,
10031 tu_around,
10032 mode,
10033 mode,
10034 angle_delta_y,
10035 tu_reach,
10036 y,
10037 tu_px,
10038 tu_py,
10039 tx_w,
10040 tx_w,
10041 base_q_idx,
10042 None,
10043 filter_intra,
10044 Some(tu_skip_ctx),
10045 smooth_neighbor,
10046 )?;
10047 if tu_grid.iter().any(|&l| l != 0) {
10048 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));
10049 }
10050 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
10051 }
10052 }
10053 }
10054 } else {
10055 let levels = if skip {
10056 let zeros = vec![0i32; bw * bh];
10057 if let Some(b) = &palette_y_buf {
10058 set_palette_pred(b.clone());
10059 }
10060 y.reconstruct_rect(
10061 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
10062 smooth_neighbor,
10063 );
10064 zeros
10065 } else {
10066 // The strip's luma TU *is* the strip (`plane_bsize ==
10067 // txsize_to_bsize[tx_size]`), so `get_txb_ctx` fixes
10068 // `txb_skip_ctx` at 0.
10069 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
10070 let set = if reduced_tx_set {
10071 TxbSet::LumaRect16x4
10072 } else {
10073 TxbSet::LumaRect16x4Set1
10074 };
10075 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
10076 let (levels, tx_type) = read_coeffs_rect(
10077 dec,
10078 &mut coding,
10079 scan,
10080 bw,
10081 bh,
10082 0,
10083 dc_sign_ctx(around.2),
10084 TxType::DctDct,
10085 )?;
10086 let residual = dequant_and_inverse_typed_wh(
10087 &levels,
10088 bw,
10089 bh,
10090 crate::decode::bit_depth(),
10091 block_q_idx(),
10092 plane_q_delta(0).0,
10093 plane_q_delta(0).1,
10094 tx_type,
10095 );
10096 if let Some(b) = &palette_y_buf {
10097 set_palette_pred(b.clone());
10098 }
10099 y.reconstruct_rect(
10100 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
10101 smooth_neighbor,
10102 );
10103 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));
10104 levels
10105 };
10106 neighbours.record_mi_luma_rect(lmi, bw, bh, &levels);
10107 }
10108 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
10109 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0);
10110 // `update_partition_context` writes `partition_context_lookup[
10111 // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on
10112 // the left (mirrored under VERT_4).
10113 for cell in 0..mi_w {
10114 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
10115 *slot = bw;
10116 }
10117 }
10118 for cell in 0..mi_h {
10119 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
10120 *slot = bh;
10121 }
10122 }
10123 if has_chroma {
10124 RECT4_16_CHROMA_HITS.with(|h| h.set(h.get() + 1));
10125 let pair_mi = if horz {
10126 (lmi.0 - 1, lmi.1)
10127 } else {
10128 (lmi.0, lmi.1 - 1)
10129 };
10130 let (pw, ph) = if horz { (16, 8) } else { (8, 16) };
10131 let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI);
10132 let (cpx, cpy) = (ppx / 2, ppy / 2);
10133 let (cw, ch) = (pw / 2, ph / 2);
10134 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
10135 if (V_PRED..=D67_PRED).contains(&uv_predict_mode) {
10136 RECT4_16_CHROMA_DIR_HITS.with(|h| h.set(h.get() + 1));
10137 }
10138 let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height);
10139 // lane-kf1200 r1: the chroma edge-filter type reads the neighbours
10140 // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s
10141 // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/
10142 // `chroma_left_mbmi` from `mi[-((mi_row & ss_y) * stride + (mi_col
10143 // & ss_x))]` (`set_mi_offsets`, av1/common/blockd.h ~1050), i.e.
10144 // the pair's top-left luma mi, never this leaf's odd row/column.
10145 // Reading `lmi` here named the leaf directly above (a non-chroma
10146 // -reference 4-row block, `uv_mode == UV_DC_PRED`) and so lost a
10147 // SMOOTH neighbour: filt_type 0 instead of 1 turned
10148 // `av1_use_intra_edge_upsample` on (blk_wh 12 <= 16) for a
10149 // directional chroma strip, moving 4 samples by 1.
10150 let smooth_neighbor_uv =
10151 neighbours.smooth_uv_neighbour(pair_mi.0, pair_mi.1, r, c);
10152 if smooth_neighbor_uv != neighbours.smooth_uv_neighbour_unsnapped(lmi.0, lmi.1, r, c)
10153 {
10154 RECT4_16_UV_PAIR_FILT_HITS.with(|h| h.set(h.get() + 1));
10155 }
10156 let (u_levels, v_levels) = if skip {
10157 let zeros = vec![0i32; cw * ch];
10158 // libaom `predict_and_reconstruct_intra_block` (decodeframe.c
10159 // ~1000) predicts EVERY plane and only guards the residual on
10160 // `mbmi->skip_txfm`, so a skipped `UV_CFL_PRED` block is still
10161 // DC + alpha * luma-AC. Dropping the CfL term here left a
10162 // chroma-only bounded box on ReelC's key frames.
10163 let ac = alpha.map(|_| cfl_ac_q3_rect(y, ppx, ppy, pw, ph));
10164 if alpha.is_some() {
10165 CHROMA_SKIP_CFL_HITS.with(|h| h.set(h.get() + 1));
10166 }
10167 for (buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] {
10168 if let Some((ub, vb)) = &palette_uv_bufs {
10169 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() });
10170 }
10171 buf.reconstruct_rect(
10172 cpx,
10173 cpy,
10174 cw,
10175 ch,
10176 uv_predict_mode,
10177 angle_delta_uv,
10178 pair_reach,
10179 &zeros,
10180 alpha
10181 .zip(ac.as_deref())
10182 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
10183 None,
10184 smooth_neighbor_uv,
10185 );
10186 }
10187 (zeros.clone(), zeros)
10188 } else {
10189 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
10190 let mut planes = Vec::with_capacity(2);
10191 for plane in 1..3 {
10192 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
10193 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
10194 let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
10195 let (levels, tx_type) = read_coeffs_rect(
10196 dec,
10197 &mut coding,
10198 chroma_scan,
10199 cw,
10200 ch,
10201 skip_ctx,
10202 dc_sign_ctx(around[plane].2),
10203 default_tx,
10204 )?;
10205 planes.push((levels, tx_type));
10206 }
10207 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
10208 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
10209 // CfL averages the luma of the WHOLE pair, the region this one
10210 // chroma transform covers.
10211 let ac = alpha.map(|_| cfl_ac_q3_rect(y, ppx, ppy, pw, ph));
10212 for (plane, buf, levels, tx_type) in [
10213 (1usize, &mut *u, &u_levels, u_tx_type),
10214 (2, &mut *v, &v_levels, v_tx_type),
10215 ] {
10216 let residual = dequant_and_inverse_typed_wh(
10217 levels,
10218 cw,
10219 ch,
10220 crate::decode::bit_depth(),
10221 block_q_idx(),
10222 plane_q_delta(plane).0,
10223 plane_q_delta(plane).1,
10224 tx_type,
10225 );
10226 if let Some((ub, vb)) = &palette_uv_bufs {
10227 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() });
10228 }
10229 buf.reconstruct_rect(
10230 cpx,
10231 cpy,
10232 cw,
10233 ch,
10234 uv_predict_mode,
10235 angle_delta_uv,
10236 pair_reach,
10237 &residual,
10238 alpha
10239 .zip(ac.as_deref())
10240 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
10241 None,
10242 smooth_neighbor_uv,
10243 );
10244 }
10245 (u_levels, v_levels)
10246 };
10247 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, uv_predict_mode);
10248 // The chroma planes' coefficient context, over the PAIR's mi span
10249 // (`decode_leaf_rect8`'s own rule: a subsampled plane's bound is
10250 // the luma one rounded up to its 4x4 unit).
10251 let u_state = neighbour_state(&u_levels);
10252 let v_state = neighbour_state(&v_levels);
10253 let round_up_even = |n: usize| n.div_ceil(2) * 2;
10254 let bound_h = round_up_even(neighbours.mi_rows);
10255 let bound_w = round_up_even(neighbours.mi_cols);
10256 for cell in 0..(ph / MI) {
10257 if pair_mi.0 + cell < bound_h
10258 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
10259 {
10260 slot[1] = u_state;
10261 slot[2] = v_state;
10262 }
10263 }
10264 for cell in 0..(pw / MI) {
10265 if pair_mi.1 + cell < bound_w
10266 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
10267 {
10268 slot[1] = u_state;
10269 slot[2] = v_state;
10270 }
10271 }
10272 last_uv_mode = Some(uv_predict_mode);
10273 }
10274 if horz {
10275 RECT4_16_HORZ_HITS.with(|h| h.set(h.get() + 1));
10276 } else {
10277 RECT4_16_VERT_HITS.with(|h| h.set(h.get() + 1));
10278 }
10279 let (pal_y_size, pal_y_colors) =
10280 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
10281 let (pal_uv_size, pal_uv_colors) =
10282 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
10283 record_strip_palette(
10284 neighbours, lmi, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
10285 );
10286 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
10287 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
10288 // frame): the above row records `tx_size_wide` over the block's width and
10289 // the left column `tx_size_high` over its height. This 1:4 strip reader is
10290 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
10291 // and it published neither band -- so the block after a 64x16 strip read
10292 // the row's init value 64 as its left transform height and took
10293 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
10294 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
10295 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
10296 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
10297 Ok((mode, last_uv_mode, (tx_w, tx_h)))
10298}
10299
10300
10301/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
10302/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
10303/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
10304/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
10305/// cap, so LUMA needs the same corner truncation [`decode_block`] already
10306/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
10307/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
10308/// this function's own charter/report), so both strips read a real 32x32
10309/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
10310/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
10311/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
10312/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
10313/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
10314/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
10315/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
10316/// that function, only the single-transform-unit (`tx_depth == 0`) case is
10317/// supported: a split transform refuses by name rather than guess-decode.
10318#[allow(clippy::too_many_arguments)]
10319fn decode_block_rect64(
10320 dec: &mut SymbolDecoder,
10321 cdfs: &mut Cdfs,
10322 neighbours: &mut Neighbours,
10323 at: (usize, usize),
10324 bw: usize,
10325 bh: usize,
10326 y: &mut PlaneBuf,
10327 u: &mut PlaneBuf,
10328 v: &mut PlaneBuf,
10329 enable_filter_intra: bool,
10330 allow_screen_content_tools: bool,
10331 base_q_idx: u8,
10332 tx_select: bool,
10333 reduced_tx_set: bool,
10334) -> Result<()> {
10335 let (r, c) = at;
10336 let (px, py) = (c * SUB, r * SUB);
10337 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
10338 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
10339 let palette_uv_cache = neighbours.palette_uv_cache(at);
10340 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
10341 read_intra_mode_rect(
10342 dec,
10343 cdfs,
10344 nb_above_mode,
10345 nb_left_mode,
10346 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
10347 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
10348 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
10349 // correct), CFL must never be offered here -- passing `true`
10350 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
10351 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
10352 // from this block's very first symbol (lane-sbpart r3 bisect).
10353 false,
10354 true,
10355 bw,
10356 bh,
10357 enable_filter_intra,
10358 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
10359 allow_screen_content_tools,
10360 Some((palette_ctx, &palette_cache)),
10361 &palette_uv_cache,
10362 r * (SUB / MI),
10363 c * (SUB / MI),
10364 )?;
10365 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
10366 // The luma coefficient path here is the corner-cropped 32x32 real
10367 // transform embedded in a 64x32/32x64 grid ([`decode_block_rect64`]'s
10368 // own doc comment) -- a real (non-skip) palette block's residual
10369 // needs the plain, uncropped rect reader [`decode_block_rect`] already
10370 // has, not this one's truncation. `skip` (no residual at all) is
10371 // still supported below (lane-palette2 r4).
10372 //
10373 // lane-pal8 r1 MEASURED the lift and it is NOT free: dropping this
10374 // refusal decodes `testsrc2` 128x128 10-bit cq55 `--enable-palette=1
10375 // --min-partition-size=8 --tile-columns=1` with a whole-frame pixel
10376 // mismatch (the arm the gate below counts). Something in this shape's
10377 // palette prediction or its corner-cropped residual is wrong, and the
10378 // refusal stays until that is found -- it is counted, never skipped.
10379 PALETTE_SB_STRIP_HITS.with(|c| c.set(c.get() + 1));
10380 return Err(unsupported(
10381 "a palette block with a real transform on a superblock-level HORZ/VERT \
10382 strip (corner-cropped luma coefficients not ported for palette)",
10383 ));
10384 }
10385 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
10386 if smooth_neighbor {
10387 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
10388 }
10389 let smooth_neighbor_uv =
10390 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
10391 if filter_intra.is_some() {
10392 // `filter_intra_size_class_rect` already returns `None` for both
10393 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
10394 // 32 on both axes), so this symbol is never read at this level --
10395 // kept only as the same defensive refusal [`decode_block_rect`] has.
10396 return Err(unsupported(
10397 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
10398 av1_filter_intra_allowed_bsize caps at 32x32)",
10399 ));
10400 }
10401 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
10402 DC_PRED
10403 } else {
10404 uv_mode
10405 };
10406 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
10407 let depth = if tx_select {
10408 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
10409 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
10410 // the 16x4 intra-in-inter strips already do); the key frame's
10411 // deblock-grid approximation is only right where those bands were never
10412 // written. Measured on the 10-bit 1920x792 128-superblock stream,
10413 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
10414 // `tx_size_cat2` row 1 where libaom reads row 2.
10415 let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {
10416 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh)
10417 } else {
10418 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
10419 };
10420 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
10421 // counts `sub_tx_size_map` steps from the block's own max rect
10422 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
10423 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
10424 // steps, so this level's category is 3 (the same one a 64x64 square
10425 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
10426 // here was a wrong-table read of a real symbol.
10427 let d = dec.symbol(&mut cdfs.tx_size_cat3[ctx]);
10428 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
10429 eprintln!(
10430 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=3 rng={}",
10431 dec.debug_state().0
10432 );
10433 }
10434 d
10435 } else {
10436 0
10437 };
10438 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
10439 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
10440 publish_txfm_bands_if_in_inter(
10441 neighbours,
10442 (mi_r, mi_c),
10443 depth_to_tx_wh(bw, bh, depth),
10444 (bw, bh),
10445 );
10446 if depth != 0 {
10447 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
10448 // lane-rectsplit r1/r4: the superblock-level strip splits its
10449 // transform through the very same per-unit path as its 32x32-level
10450 // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64
10451 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
10452 // measured the old square formula mis-tiling exactly that strip).
10453 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
10454 if bw.max(bh) / bw.min(bh) == 4 {
10455 let which = if depth == 1 {
10456 &RECT4_SPLIT_DEPTH1_HITS
10457 } else {
10458 &RECT4_SPLIT_DEPTH2_HITS
10459 };
10460 which.with(|c| c.set(c.get() + 1));
10461 }
10462 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
10463 eprintln!(
10464 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
10465 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
10466 angle_y={angle_delta_y}"
10467 );
10468 }
10469 let modes = RectStripModes {
10470 skip,
10471 mode,
10472 angle_delta_y,
10473 uv_predict_mode,
10474 angle_delta_uv,
10475 alpha,
10476 filter_intra,
10477 smooth_neighbor,
10478 smooth_neighbor_uv,
10479 palette_y: palette_y
10480 .as_ref()
10481 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
10482 palette_uv: palette_uv.as_ref().map(|p| {
10483 (
10484 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
10485 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
10486 )
10487 }),
10488 };
10489 if palette_y.is_some() || palette_uv.is_some() {
10490 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
10491 }
10492 decode_rect_split(
10493 dec,
10494 cdfs,
10495 neighbours,
10496 (mi_r, mi_c),
10497 bw,
10498 bh,
10499 tx_w,
10500 tx_h,
10501 &modes,
10502 y,
10503 u,
10504 v,
10505 base_q_idx,
10506 reduced_tx_set,
10507 )?;
10508 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
10509 // (lane-palette2 r10): this return skips the fn's own tail, so a
10510 // split-tx superblock strip would otherwise leave the above/left
10511 // palette arrays holding a dead block's colours.
10512 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
10513 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
10514 let (puv_size, puv_colors) =
10515 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
10516 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
10517 // lane-frame36 r2: `set_txfm_ctxs` runs for EVERY block and this early
10518 // return skips the fn's own tail, so a SPLIT superblock-level strip
10519 // published no TXFM_CONTEXT band and the next block read the row's init
10520 // value 64 as its left transform height. Measured on the 10-bit
10521 // 3840x1608 stream, decode-order frame 33: after the split 16x64 strip
10522 // at mi(192,140) (`tx_depth=1` -> TX_16X32) the 32x64 block at
10523 // mi(192,144) took `tx_size_cat3` row 2 where libaom takes row 1. The
10524 // bands carry the SPLIT unit's size, not the block's.
10525 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
10526 RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.set(c.get() + 1));
10527 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
10528 return Ok(());
10529 }
10530 let (tx_w, tx_h) = (bw, bh);
10531 let (cpx, cpy) = (px / 2, py / 2);
10532 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
10533 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
10534 if let Some(ref pyv) = palette_y {
10535 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
10536 set_palette_pred(buf);
10537 }
10538 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
10539 (
10540 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
10541 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
10542 )
10543 });
10544 if skip {
10545 y.reconstruct_rect(
10546 px,
10547 py,
10548 bw,
10549 bh,
10550 mode,
10551 angle_delta_y,
10552 reach,
10553 &vec![0i32; bw * bh],
10554 None,
10555 filter_intra,
10556 smooth_neighbor,
10557 );
10558 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
10559 if let Some((ub, _)) = &palette_uv_bufs {
10560 set_palette_pred(ub.clone());
10561 }
10562 u.reconstruct_rect(
10563 cpx,
10564 cpy,
10565 chroma_w,
10566 chroma_h,
10567 uv_predict_mode,
10568 angle_delta_uv,
10569 reach,
10570 &vec![0i32; chroma_w * chroma_h],
10571 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
10572 None,
10573 smooth_neighbor_uv,
10574 );
10575 if let Some((_, vb)) = &palette_uv_bufs {
10576 set_palette_pred(vb.clone());
10577 }
10578 v.reconstruct_rect(
10579 cpx,
10580 cpy,
10581 chroma_w,
10582 chroma_h,
10583 uv_predict_mode,
10584 angle_delta_uv,
10585 reach,
10586 &vec![0i32; chroma_w * chroma_h],
10587 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
10588 None,
10589 smooth_neighbor_uv,
10590 );
10591 neighbours.record_rect(
10592 at,
10593 bw,
10594 bh,
10595 mode,
10596 uv_predict_mode,
10597 &[
10598 vec![0i32; bw * bh],
10599 vec![0i32; chroma_w * chroma_h],
10600 vec![0i32; chroma_w * chroma_h],
10601 ],
10602 );
10603 } else {
10604 let around = neighbours.around_rect(at, bw, bh);
10605 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
10606 // (see this function's own doc comment). A 64-length axis codes only
10607 // its low 32 coefficients, so the corner is `min(bw, 32)` x
10608 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
10609 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
10610 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
10611 let scan32 = default_scan(TX32);
10612 if coeff_trace_on() {
10613 let (rng, _) = dec.debug_state();
10614 eprintln!("EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}");
10615 }
10616 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
10617 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
10618 read_coeffs(
10619 dec,
10620 &mut luma_coding,
10621 &scan32,
10622 0,
10623 dc_sign_ctx(around[0].2),
10624 TxType::DctDct,
10625 Some((bw, bh)),
10626 )?
10627 } else {
10628 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
10629 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
10630 // (`scan.c`) gives both the very same `default_scan_32x16` /
10631 // `default_scan_16x32` the 2:1 sizes use ("Half of the
10632 // coefficients of tx64 at higher frequencies are set to zeros. So
10633 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
10634 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
10635 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
10636 // 512-position eob group) -- BOTH identical to TX_32X16, so the
10637 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
10638 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
10639 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
10640 // what `base_ctx_rect` computes at (32, 16).
10641 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
10642 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
10643 read_coeffs_rect(
10644 dec,
10645 &mut luma_coding,
10646 luma_scan,
10647 luma_cw,
10648 luma_ch,
10649 0,
10650 dc_sign_ctx(around[0].2),
10651 TxType::DctDct,
10652 )?
10653 };
10654 if coeff_trace_on() {
10655 let (rng, _) = dec.debug_state();
10656 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
10657 }
10658 let mut luma_levels = vec![0i32; bw * bh];
10659 for row in 0..luma_ch {
10660 luma_levels[row * bw..][..luma_cw]
10661 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
10662 }
10663 {
10664 let cur = block_q_idx();
10665 if cur != i32::from(base_q_idx) {
10666 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
10667 }
10668 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10669 eprintln!(
10670 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
10671 );
10672 }
10673 }
10674 let luma_residual = dequant_and_inverse_typed_wh(
10675 &luma_levels,
10676 bw,
10677 bh,
10678 crate::decode::bit_depth(),
10679 block_q_idx(),
10680 plane_q_delta(0).0,
10681 plane_q_delta(0).1,
10682 luma_tx_type,
10683 );
10684 y.reconstruct_rect(
10685 px,
10686 py,
10687 bw,
10688 bh,
10689 mode,
10690 angle_delta_y,
10691 reach,
10692 &luma_residual,
10693 None,
10694 filter_intra,
10695 smooth_neighbor,
10696 );
10697 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
10698 let leftcol: Vec<u16> = if px > 0 {
10699 (py..py + bh).map(|row| y.data[row * y.width + px - 1]).collect()
10700 } else {
10701 vec![]
10702 };
10703 eprintln!(
10704 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
10705 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
10706 luma_corner.iter().any(|&v| v != 0),
10707 &y.data[py * y.width + px..][..bw],
10708 leftcol,
10709 );
10710 }
10711 // CHROMA: a real, untruncated chroma_w x chroma_h transform -- no
10712 // corner crop needed (see doc comment).
10713 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
10714 // The chroma plane is never truncated (both axes <= 32 after
10715 // subsampling). Under a 1:4 strip it is a true 32x8/8x32:
10716 // `get_txsize_entropy_ctx(TX_32X8)` = (TX_8X8 + TX_32X32 + 1) >> 1 =
10717 // TX_16X16 and `txsize_log2_minus4[TX_32X8]` = 4 (256 positions),
10718 // both identical to TX_16X16 -- so [`TxbSet::Chroma16`] is the exact
10719 // set, and only the scan is new (lane-tx64x16).
10720 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (bw, bh) {
10721 (64, 16) => (TxbSet::Chroma16, &SCAN_32X8),
10722 (16, 64) => (TxbSet::Chroma16, &SCAN_8X32),
10723 (64, _) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
10724 _ => (TxbSet::ChromaRect32x16, &SCAN_16X32),
10725 };
10726 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
10727 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
10728 if coeff_trace_on() {
10729 let (rng, _) = dec.debug_state();
10730 eprintln!("EC_COEFF plane=1 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
10731 }
10732 let (u_levels, u_tx_type) = read_coeffs_rect(
10733 dec,
10734 &mut u_coding,
10735 chroma_scan,
10736 chroma_w,
10737 chroma_h,
10738 u_skip_ctx,
10739 dc_sign_ctx(around[1].2),
10740 TxType::DctDct,
10741 )?;
10742 if coeff_trace_on() {
10743 let (rng, _) = dec.debug_state();
10744 eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}");
10745 }
10746 {
10747 let cur = block_q_idx();
10748 if cur != i32::from(base_q_idx) {
10749 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
10750 }
10751 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10752 eprintln!(
10753 "TRACE rect64_dequant plane=1 base_q_idx={base_q_idx} current_q_idx={cur}"
10754 );
10755 }
10756 }
10757 let u_residual = dequant_and_inverse_typed_wh(
10758 &u_levels,
10759 chroma_w,
10760 chroma_h,
10761 crate::decode::bit_depth(),
10762 block_q_idx(),
10763 plane_q_delta(1).0,
10764 plane_q_delta(1).1,
10765 u_tx_type,
10766 );
10767 u.reconstruct_rect(
10768 cpx,
10769 cpy,
10770 chroma_w,
10771 chroma_h,
10772 uv_predict_mode,
10773 angle_delta_uv,
10774 reach,
10775 &u_residual,
10776 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
10777 None,
10778 smooth_neighbor_uv,
10779 );
10780 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
10781 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
10782 if coeff_trace_on() {
10783 let (rng, _) = dec.debug_state();
10784 eprintln!("EC_COEFF plane=2 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
10785 }
10786 let (v_levels, v_tx_type) = read_coeffs_rect(
10787 dec,
10788 &mut v_coding,
10789 chroma_scan,
10790 chroma_w,
10791 chroma_h,
10792 v_skip_ctx,
10793 dc_sign_ctx(around[2].2),
10794 TxType::DctDct,
10795 )?;
10796 if coeff_trace_on() {
10797 let (rng, _) = dec.debug_state();
10798 eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}");
10799 }
10800 {
10801 let cur = block_q_idx();
10802 if cur != i32::from(base_q_idx) {
10803 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
10804 }
10805 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10806 eprintln!(
10807 "TRACE rect64_dequant plane=2 base_q_idx={base_q_idx} current_q_idx={cur}"
10808 );
10809 }
10810 }
10811 let v_residual = dequant_and_inverse_typed_wh(
10812 &v_levels,
10813 chroma_w,
10814 chroma_h,
10815 crate::decode::bit_depth(),
10816 block_q_idx(),
10817 plane_q_delta(2).0,
10818 plane_q_delta(2).1,
10819 v_tx_type,
10820 );
10821 v.reconstruct_rect(
10822 cpx,
10823 cpy,
10824 chroma_w,
10825 chroma_h,
10826 uv_predict_mode,
10827 angle_delta_uv,
10828 reach,
10829 &v_residual,
10830 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
10831 None,
10832 smooth_neighbor_uv,
10833 );
10834 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
10835 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
10836 }
10837 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
10838 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
10839 let (puv_size, puv_colors) =
10840 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
10841 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
10842 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
10843 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
10844 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
10845 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
10846 // frame): the above row records `tx_size_wide` over the block's width and
10847 // the left column `tx_size_high` over its height. This 1:4 strip reader is
10848 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
10849 // and it published neither band -- so the block after a 64x16 strip read
10850 // the row's init value 64 as its left transform height and took
10851 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
10852 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
10853 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
10854 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
10855 SB_RECT_HITS.with(|c| c.set(c.get() + 1));
10856 match (bw, bh) {
10857 (64, 16) => SB_RECT4_HORZ_HITS.with(|c| c.set(c.get() + 1)),
10858 (16, 64) => SB_RECT4_VERT_HITS.with(|c| c.set(c.get() + 1)),
10859 _ => {}
10860 }
10861 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10862 let (rng, _) = dec.debug_state();
10863 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
10864 }
10865 Ok(())
10866}
10867
10868/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
10869/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
10870/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
10871/// it lands away from zero, for gate tests to prove a real stream fired one.
10872fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
10873 let symbol = dec.symbol(cdf);
10874 if symbol != ANGLE_DELTA_ZERO {
10875 ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
10876 }
10877 symbol as i32 - ANGLE_DELTA_ZERO as i32
10878}
10879
10880#[allow(clippy::too_many_arguments)]
10881fn read_intra_mode(
10882 dec: &mut SymbolDecoder,
10883 cdfs: &mut Cdfs,
10884 above_mode: usize,
10885 left_mode: usize,
10886 cfl: bool,
10887 side: usize,
10888 enable_filter_intra: bool,
10889 skip_ctx: usize,
10890 allow_screen_content_tools: bool,
10891 allow_intrabc: bool,
10892 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
10893 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
10894 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
10895 // `None` at the excluded call sites (the 8x8-leaf path), which still read
10896 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
10897 // decoder reads either way -- but refuse by name the moment it fires,
10898 // exactly the old behaviour.
10899 palette: Option<(usize, &[u16])>,
10900 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
10901 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
10902 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
10903 // `use_palette_y`, not a neighbour lookup).
10904 palette_uv_cache: &[u16],
10905 mi_r: usize,
10906 mi_c: usize,
10907) -> Result<(
10908 bool,
10909 usize,
10910 i32,
10911 usize,
10912 i32,
10913 Option<(i32, i32)>,
10914 Option<usize>,
10915 Option<PaletteY>,
10916 Option<PaletteUv>,
10917)> {
10918 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
10919 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
10920 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
10921 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
10922 // line against the instrumented aomdec, not just `tell()`.
10923 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
10924 if ec_istep {
10925 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
10926 // (decodemv.c:818), printed at the same point: before the first
10927 // mode-info symbol of the block, so a cross-decoder range ladder can
10928 // be keyed on the BLOCK, not just on the symbol sequence.
10929 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}", dec.debug_state().0);
10930 }
10931 macro_rules! istep {
10932 ($name:literal, $val:expr) => {
10933 if ec_istep {
10934 let (rng, _) = dec.debug_state();
10935 eprintln!(
10936 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
10937 $name, $val
10938 );
10939 }
10940 };
10941 }
10942 // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single
10943 // point every square caller routes through (see `read_intra_mode_rect`).
10944 let cfl = if cfl && side > 32 {
10945 NOCFL_UV_MODE_HITS.with(|c| c.set(c.get() + 1));
10946 false
10947 } else {
10948 cfl
10949 };
10950 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
10951 // `skip` when `SegIdPreSkip`, and after it otherwise.
10952 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
10953 if seg_id_pre_skip() {
10954 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);
10955 }
10956 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
10957 if trace {
10958 eprintln!("TRACE skip value={} rng={}", skip as i32, dec.debug_state().0);
10959 }
10960 istep!("skip", skip as i32);
10961 if !seg_id_pre_skip() {
10962 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);
10963 }
10964 // spec order (see the comment below on `read_intrabc_info`): `skip`,
10965 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
10966 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
10967 istep!("cdef", 0);
10968 // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not
10969 // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole
10970 // superblock and skips `delta_q` exactly like a 64 one under a 64 root.
10971 let whole_sb = side == sb_mi_cur() as usize * 4;
10972 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, whole_sb, skip);
10973 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, whole_sb, skip);
10974 istep!("dq", 0);
10975 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
10976 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
10977 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
10978 // intra frame whose header set `allow_intrabc`. Actual intra block copy
10979 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
10980 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
10981 // draws the line at consuming this one flag symbol and refusing by name
10982 // when it fires, so the arithmetic decoder still resyncs for a stream
10983 // that merely allows (but never uses) intrabc.
10984 if allow_intrabc {
10985 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
10986 if trace {
10987 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
10988 }
10989 if use_intrabc {
10990 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, side);
10991 if trace {
10992 eprintln!("TRACE intrabc dv={dv:?}");
10993 }
10994 INTRABC_DV.with(|c| c.set(Some(dv)));
10995 INTRABC_HITS.with(|c| c.set(c.get() + 1));
10996 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
10997 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
10998 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
10999 // `DC_PRED` (which is also what the neighbour mode contexts and
11000 // the loop filter then see).
11001 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
11002 }
11003 }
11004 let above_ctx = INTRA_MODE_CTX[above_mode];
11005 let left_ctx = INTRA_MODE_CTX[left_mode];
11006 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
11007 if trace {
11008 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
11009 }
11010 istep!("mode", mode as i32);
11011 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
11012 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
11013 if trace {
11014 eprintln!(
11015 "TRACE angle_delta value={}",
11016 delta + ANGLE_DELTA_ZERO as i32
11017 );
11018 }
11019 delta
11020 } else {
11021 0
11022 };
11023 istep!("angle_y", angle_delta_y);
11024 // lane-sb128c r3 (class sweep): `is_cfl_allowed` on the luma bsize, decided
11025 // here so every `decode_block` caller (64x64 and 128x128 roots included)
11026 // picks the right alphabet -- see [`read_intra_mode_rect`]'s twin.
11027 let cfl = cfl && side <= 32;
11028 let uv_mode = if cfl {
11029 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
11030 } else {
11031 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
11032 };
11033 if trace {
11034 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}", dec.debug_state().0);
11035 }
11036 istep!("uv_mode", uv_mode as i32);
11037 let alpha = if cfl && uv_mode == UV_CFL_PRED {
11038 Some(read_cfl_alphas(dec, cdfs))
11039 } else {
11040 None
11041 };
11042 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
11043 // from this lane's directional chroma: a corner block with neither
11044 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
11045 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
11046 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
11047 // bug in that fallback this lane's own scope does not cover. Keep it
11048 // refused here rather than ship a silently-wrong decode.
11049 if (9..=12).contains(&uv_mode) {
11050 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
11051 }
11052 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
11053 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
11054 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
11055 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
11056 // the `else` branch below and never reads one either way.
11057 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
11058 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
11059 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
11060 } else {
11061 0
11062 };
11063 istep!("angle_uv", angle_delta_uv);
11064 if angle_delta_uv != 0 {
11065 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
11066 }
11067 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
11068 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
11069 // gated by `av1_allow_palette` (blockd.h -- size bound only,
11070 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
11071 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
11072 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
11073 // read the same CDF row whenever every neighbour really is non-palette).
11074 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
11075 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
11076 // neighbour lookup at all), so it is exact even at the excluded call
11077 // sites once Y decodes real syntax there too.
11078 //
11079 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
11080 // inline from `read_palette_mode_info` -- it runs later, from
11081 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
11082 // after the WHOLE mode-info read for the block, including UV palette
11083 // mode_info (`read_palette_mode_info`'s own second half, right below)
11084 // and `read_filter_intra_mode_info`. So this branch now only reads
11085 // mode/size/colours for both planes (deferring the two colour-index-map
11086 // decodes to after `filter_intra`, below) -- r6's range trace pinned
11087 // this exact ordering bug (`compare-range-not-tell`: ranges matched
11088 // bit-for-bit through the Y colours, diverged only at the old inline
11089 // `decode_color_index_map` call).
11090 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
11091 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
11092 if allow_screen_content_tools
11093 && let Some(bsize_ctx) = palette_bsize_ctx(side)
11094 {
11095 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
11096 if mode == DC_PRED {
11097 if trace {
11098 let (rng, _) = dec.debug_state();
11099 eprintln!(
11100 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
11101 );
11102 }
11103 }
11104 let use_palette_y =
11105 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
11106 if mode == DC_PRED && trace {
11107 let (rng, _) = dec.debug_state();
11108 eprintln!("TRACE palette_y_mode value={} rng={rng}", use_palette_y as i32);
11109 }
11110 if use_palette_y {
11111 if palette.is_none() {
11112 return Err(unsupported(
11113 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
11114 ));
11115 }
11116 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
11117 if trace {
11118 let (rng, _) = dec.debug_state();
11119 eprintln!("TRACE palette_y_size n={n} rng={rng}");
11120 }
11121 let colors = read_palette_colors_y(dec, n, cache);
11122 if trace {
11123 let (rng, _) = dec.debug_state();
11124 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
11125 }
11126 palette_y_pending = Some((n, colors));
11127 }
11128 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
11129 // unconditionally at this bit position whenever `uv_mode ==
11130 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
11131 // scope always reconstructs chroma alongside luma (`decode_block`
11132 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
11133 // is always true here and does not need threading in.
11134 let palette_uv_mode_ctx = usize::from(use_palette_y);
11135 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
11136 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
11137 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache);
11138 palette_uv_pending = Some((n, u_colors, v_colors));
11139 }
11140 }
11141 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
11142 // `use_filter_intra` symbol this decoder never read at all until
11143 // lane-av1real r10 -- silently skipping it left every bit past a
11144 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
11145 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
11146 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
11147 // symbol's bits were never consumed).
11148 let mut filter_intra = None;
11149 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
11150 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
11151 // `use_filter_intra` symbol for a Y-palette block, and reading one here
11152 // desynced every screen-content stream from the first palette block on
11153 // (it surfaced as a bogus "partition below 8x8" refusal further down the
11154 // tile).
11155 if mode == DC_PRED
11156 && enable_filter_intra
11157 && palette_y_pending.is_none()
11158 && let Some(class) = filter_intra_size_class(side)
11159 {
11160 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
11161 if trace {
11162 eprintln!(
11163 "TRACE use_filter_intra side={side} rng={} value={}", dec.debug_state().0,
11164 use_filter_intra as i32
11165 );
11166 }
11167 istep!("use_filter_intra", use_filter_intra as i32);
11168 if use_filter_intra {
11169 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
11170 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
11171 if trace {
11172 eprintln!("TRACE filter_intra_mode value={fi_mode}");
11173 }
11174 istep!("filter_intra_mode", fi_mode as i32);
11175 filter_intra = Some(fi_mode);
11176 }
11177 }
11178 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
11179 // shared U/V map) -- the same order libaom's own loop visits them in.
11180 let palette_y = palette_y_pending.map(|(n, colors)| {
11181 let map = decode_color_index_map(dec, cdfs, n, side, false);
11182 PALETTE_HITS.with(|c| c.set(c.get() + 1));
11183 if trace {
11184 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
11185 }
11186 PaletteY { size: n, colors, map }
11187 });
11188 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
11189 let map = decode_color_index_map(dec, cdfs, n, side / 2, true);
11190 PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
11191 if trace {
11192 eprintln!(
11193 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
11194 &u_colors[..n],
11195 &v_colors[..n]
11196 );
11197 }
11198 PaletteUv { size: n, u_colors, v_colors, map }
11199 });
11200 Ok((
11201 skip,
11202 mode,
11203 angle_delta_y,
11204 uv_mode,
11205 angle_delta_uv,
11206 alpha,
11207 filter_intra,
11208 palette_y,
11209 palette_uv,
11210 ))
11211}
11212
11213/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
11214/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
11215/// intra modes.
11216const UV_CFL_PRED: usize = 13;
11217
11218/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
11219/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
11220/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
11221/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
11222/// joint sign the same way. Returns each plane's final signed `alpha_q3`
11223/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
11224fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
11225 CFL_BLOCK_HITS.with(|c| c.set(c.get() + 1));
11226 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
11227 let sign_u = ((joint_sign + 1) * 11) >> 5;
11228 let sign_v = (joint_sign + 1) - 3 * sign_u;
11229 let alpha_u = if sign_u == 0 {
11230 0
11231 } else {
11232 let ctx_u = (joint_sign + 1 - 3) as usize;
11233 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
11234 if sign_u == 2 { mag } else { -mag }
11235 };
11236 let alpha_v = if sign_v == 0 {
11237 0
11238 } else {
11239 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
11240 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
11241 if sign_v == 2 { mag } else { -mag }
11242 };
11243 (alpha_u, alpha_v)
11244}
11245
11246/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
11247/// the reconstructed luma samples under a `side`-square block, subsampled
11248/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
11249/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
11250/// to give the AC values [`cfl_scaled`] scales by alpha.
11251fn cfl_ac_q3(y: &PlaneBuf, px: usize, py: usize, side: usize) -> Vec<i32> {
11252 let cside = side / 2;
11253 let mut ac = vec![0i32; cside * cside];
11254 let mut sum = 0i32;
11255 for cy in 0..cside {
11256 for cx in 0..cside {
11257 let (lx, ly) = (px + cx * 2, py + cy * 2);
11258 let q3 = (i32::from(y.data[ly * y.width + lx])
11259 + i32::from(y.data[ly * y.width + lx + 1])
11260 + i32::from(y.data[(ly + 1) * y.width + lx])
11261 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
11262 << 1;
11263 ac[cy * cside + cx] = q3;
11264 sum += q3;
11265 }
11266 }
11267 let num_pel = (cside * cside) as i32;
11268 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
11269 ac.iter_mut().for_each(|v| *v -= avg);
11270 ac
11271}
11272
11273/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
11274/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
11275/// ties away from zero on the shifted-out sign).
11276fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
11277 let v = alpha_q3 * ac_q3;
11278 if v >= 0 {
11279 (v + 32) >> 6
11280 } else {
11281 -((-v + 32) >> 6)
11282 }
11283}
11284
11285/// One plane's reconstruction buffer, `width * height` samples, and the
11286/// prediction/residual reads and writes into it — the decode-side twin of
11287/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
11288/// (own-edge and reach clamps both), passing what it gathers straight to
11289/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
11290/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
11291/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
11292/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of
11293/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) --
11294/// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE).
11295/// lane-mc64 r1: the decode-order index the stage dumps below key their file
11296/// name on. `PREFILT_PICTURE_IDX` is bumped once per frame just BEFORE the
11297/// deblock/CDEF stages run, so the frame being dumped here is `idx - 1` --
11298/// without this every frame overwrote `.f0` and a per-frame bisection silently
11299/// compared the LAST decoded frame (ledger, class stale-output-faked-measurement).
11300fn stage_dump_idx() -> usize {
11301 PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst).saturating_sub(1)
11302}
11303
11304fn dump_stage16(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf, fw: usize, fh: usize) {
11305 use std::io::Write;
11306 // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by
11307 // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed
11308 // `.f0` name kept only the LAST frame, so a mid-sequence divergence could
11309 // not be read out at all.
11310 if let Ok(path) = crate::envflags::var(var)
11311 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
11312 {
11313 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))] {
11314 for row in 0..h {
11315 let mut bytes = Vec::with_capacity(w * 2);
11316 for &s in &p.data[row * p.width..][..w] {
11317 bytes.extend_from_slice(&s.to_le_bytes());
11318 }
11319 let _ = f.write_all(&bytes);
11320 }
11321 }
11322 }
11323}
11324
11325/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a
11326/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so
11327/// every frame overwrote the previous one and only the LAST frame survived,
11328/// which silently defeats any per-frame filter-stage bisection.
11329fn dump_stage_idx(var: &str) -> usize {
11330 use std::collections::HashMap;
11331 use std::sync::{Mutex, OnceLock};
11332 static IDX: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new();
11333 let mut m = IDX.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap();
11334 let e = m.entry(var.to_string()).or_insert(0);
11335 let i = *e;
11336 *e += 1;
11337 i
11338}
11339
11340fn dump_stage(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf) {
11341 use std::io::Write;
11342 if let Ok(path) = crate::envflags::var(var)
11343 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
11344 {
11345 for p in [y, u, v] {
11346 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
11347 let _ = f.write_all(&narrow);
11348 }
11349 }
11350}
11351
11352#[derive(Clone)]
11353struct PlaneBuf {
11354 data: Vec<u16>,
11355 width: usize,
11356 height: usize,
11357 /// The frame's true, decodable extent in this plane's own units — past
11358 /// this, samples are the padded coding surface's invented tail, never a
11359 /// real decoder's edge or reach reads.
11360 true_width: usize,
11361 true_height: usize,
11362 /// This plane's own tile's top-left pixel origin (spec: intra prediction
11363 /// never reaches across a tile boundary even though an earlier-decoded
11364 /// tile's real pixels sit right there in the shared buffer) — set via
11365 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
11366 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
11367 /// is threaded (the two-tile column-split stage 1 fixture's tile always
11368 /// ends at the frame's own right/bottom edge); a non-last tile's own
11369 /// right/bottom reach bound is still open, tracked in the report.
11370 tile_x0: usize,
11371 tile_y0: usize,
11372 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
11373 /// (exclusive) -- a non-last tile column/row's own reach must stop at
11374 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
11375 /// full padded extent) for the single-tile/last-tile case, matching the
11376 /// old unclipped behaviour exactly.
11377 tile_x1: usize,
11378 tile_y1: usize,
11379}
11380
11381/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
11382/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
11383/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
11384/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
11385/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
11386/// `ALTREF2`/`ALTREF`).
11387type RefSlots<'a> = [Option<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)>; 8];
11388
11389impl PlaneBuf {
11390 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
11391 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
11392 /// are already in this plane's own units (luma pixels for `y`, chroma
11393 /// pixels — halved — for `u`/`v`).
11394 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
11395 self.tile_x0 = x0;
11396 self.tile_y0 = y0;
11397 self.tile_x1 = x1;
11398 self.tile_y1 = y1;
11399 }
11400
11401 fn edges(
11402 &self,
11403 x: usize,
11404 y: usize,
11405 side: usize,
11406 reach: Reach,
11407 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
11408 let own_across = x + side.min(self.true_width.saturating_sub(x));
11409 let across = if reach.above_right {
11410 own_across + side.min(self.true_width.saturating_sub(own_across))
11411 } else {
11412 own_across
11413 }
11414 .min(self.width)
11415 .min(self.tile_x1);
11416 let own_down = y + side.min(self.true_height.saturating_sub(y));
11417 let down = if reach.below_left {
11418 own_down + side.min(self.true_height.saturating_sub(own_down))
11419 } else {
11420 own_down
11421 }
11422 .min(self.height)
11423 .min(self.tile_y1);
11424 let above = (y > self.tile_y0 && across > x)
11425 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
11426 let left = (x > self.tile_x0 && down > y).then(|| {
11427 (y..down)
11428 .map(|row| self.data[row * self.width + x - 1])
11429 .collect::<Vec<_>>()
11430 });
11431 let corner =
11432 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
11433 (above, left, corner)
11434 }
11435
11436 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
11437 /// the above/left reach each extend by their OWN axis (`bw` across,
11438 /// `bh` down), not one shared `side`.
11439 fn edges_rect(
11440 &self,
11441 x: usize,
11442 y: usize,
11443 bw: usize,
11444 bh: usize,
11445 reach: Reach,
11446 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
11447 let own_across = x + bw.min(self.true_width.saturating_sub(x));
11448 let across = if reach.above_right {
11449 own_across + bw.min(self.true_width.saturating_sub(own_across))
11450 } else {
11451 own_across
11452 }
11453 .min(self.width)
11454 .min(self.tile_x1);
11455 let own_down = y + bh.min(self.true_height.saturating_sub(y));
11456 let down = if reach.below_left {
11457 own_down + bh.min(self.true_height.saturating_sub(own_down))
11458 } else {
11459 own_down
11460 }
11461 .min(self.height)
11462 .min(self.tile_y1);
11463 let above = (y > self.tile_y0 && across > x)
11464 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
11465 let left = (x > self.tile_x0 && down > y).then(|| {
11466 (y..down)
11467 .map(|row| self.data[row * self.width + x - 1])
11468 .collect::<Vec<_>>()
11469 });
11470 let corner =
11471 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
11472 if matches!((bw, bh), (16, 8) | (8, 16)) {
11473 RECT_STRIP_PRED_HITS.with(|h| h.set(h.get() + 1));
11474 if across > own_across || down > own_down {
11475 RECT_STRIP_REACH_HITS.with(|h| h.set(h.get() + 1));
11476 }
11477 }
11478 (above, left, corner)
11479 }
11480
11481 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
11482 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
11483 /// already-rect-capable `(bw, bh)` pair.
11484 #[allow(clippy::too_many_arguments)]
11485 #[track_caller]
11486 fn reconstruct_rect(
11487 &mut self,
11488 x: usize,
11489 y: usize,
11490 bw: usize,
11491 bh: usize,
11492 mode: usize,
11493 angle_delta: i32,
11494 reach: Reach,
11495 residual: &[i32],
11496 cfl: Option<(i32, &[i32])>,
11497 filter_intra: Option<usize>,
11498 smooth_neighbor: bool,
11499 ) {
11500 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
11501 // (lane-palette2 r4): a palette block's prediction is the
11502 // reconstructed colour-index map, needing no edge pixels at all.
11503 let prediction = if let Some(buf) = take_palette_pred() {
11504 buf
11505 } else {
11506 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
11507 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
11508 eprintln!(
11509 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
11510 above.as_ref().map(|a| (a.len(), a[0])),
11511 left.as_ref().map(|l| l.len()),
11512 left.as_ref().map(|l| l[0]),
11513 self.tile_x0, self.tile_y0, self.true_width, self.true_height
11514 );
11515 }
11516 let mut prediction = vec![0u16; bw * bh];
11517 if let Some(fi_mode) = filter_intra {
11518 crate::intra::predict_filter_intra(
11519 fi_mode,
11520 above.as_deref(),
11521 left.as_deref(),
11522 corner,
11523 bw,
11524 bh,
11525 &mut prediction,
11526 );
11527 } else {
11528 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
11529 predict(
11530 mode as u8,
11531 angle_delta,
11532 above.as_deref(),
11533 left.as_deref(),
11534 corner,
11535 bw,
11536 bh,
11537 enable_edge_filter,
11538 smooth_neighbor,
11539 &mut prediction,
11540 );
11541 }
11542 prediction
11543 };
11544 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
11545 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
11546 if crate::envflags::env_flag!("EC_PRED") {
11547 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
11548 let row0: Vec<u16> = prediction[..bw.min(8)].to_vec();
11549 let col0: Vec<u16> = (0..bh.min(8)).map(|r| prediction[r * bw]).collect();
11550 eprintln!(
11551 "@{} 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)
11552 );
11553 }
11554 for row in 0..bh {
11555 // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s
11556 // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame
11557 // whose padded width is not superblock aligned hangs past it.
11558 if y + row >= self.height {
11559 break;
11560 }
11561 for col in 0..bw {
11562 if x + col >= self.width {
11563 break;
11564 }
11565 let idx = row * bw + col;
11566 let mut base = i32::from(prediction[idx]);
11567 if let Some((alpha_q3, ac_q3)) = cfl {
11568 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max());
11569 }
11570 let sample = (base + residual[idx]).clamp(0, sample_max()) as u16;
11571 self.data[(y + row) * self.width + x + col] = sample;
11572 }
11573 }
11574 }
11575
11576 /// Predicts under `mode` then adds `residual` (side*side, raster),
11577 /// writing the clamped reconstruction back into the plane at `(x, y)`.
11578 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
11579 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
11580 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
11581 /// order (cfl.c).
11582 #[track_caller]
11583 fn reconstruct(
11584 &mut self,
11585 x: usize,
11586 y: usize,
11587 side: usize,
11588 mode: usize,
11589 angle_delta: i32,
11590 reach: Reach,
11591 residual: &[i32],
11592 cfl: Option<(i32, &[i32])>,
11593 filter_intra: Option<usize>,
11594 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
11595 // libaom `get_filt_type`): true when the block's above OR left
11596 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
11597 // Callers pass their own plane's neighbour-mode check
11598 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
11599 // callers until a smooth/paeth `uv_mode` can reach this call at all
11600 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
11601 // keeps `false` exact for chroma without this fn needing to know why.
11602 smooth_neighbor: bool,
11603 ) {
11604 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
11605 // takes priority over `predict()`/`predict_filter_intra` entirely --
11606 // palette prediction needs no edge pixels at all.
11607 let prediction = if let Some(buf) = take_palette_pred() {
11608 buf
11609 } else {
11610 let (above, left, corner) = self.edges(x, y, side, reach);
11611 let mut prediction = vec![0u16; side * side];
11612 if let Some(fi_mode) = filter_intra {
11613 crate::intra::predict_filter_intra(
11614 fi_mode,
11615 above.as_deref(),
11616 left.as_deref(),
11617 corner,
11618 side,
11619 side,
11620 &mut prediction,
11621 );
11622 } else {
11623 // `enable_intra_edge_filter` is the sequence header's own flag
11624 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
11625 // call, never per-block) -- threading it through every
11626 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
11627 // dozen sites for a value that never changes mid-decode, so it
11628 // rides a thread-local instead (this decoder is single-threaded
11629 // per stream).
11630 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
11631 predict(
11632 mode as u8,
11633 angle_delta,
11634 above.as_deref(),
11635 left.as_deref(),
11636 corner,
11637 side,
11638 side,
11639 enable_edge_filter,
11640 smooth_neighbor,
11641 &mut prediction,
11642 );
11643 }
11644 prediction
11645 };
11646 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
11647 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
11648 if crate::envflags::env_flag!("EC_PRED") {
11649 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
11650 let row0: Vec<u16> = prediction[..side.min(8)].to_vec();
11651 let col0: Vec<u16> = (0..side.min(8)).map(|r| prediction[r * side]).collect();
11652 eprintln!(
11653 "@{} 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)
11654 );
11655 }
11656 for row in 0..side {
11657 // lane-sb128c r8: libaom's frame buffer is superblock
11658 // aligned; ours is padded to 32 (`block_grid`), so a 64x64
11659 // transform unit of a 128x64 block at the BOTTOM frame edge
11660 // can hang past the last padded row (1920x792: a unit at
11661 // y=768 wants 832 rows of an 800-row buffer, which panicked
11662 // the film's key frames). Those samples are outside the
11663 // frame: never output, and no block below ever references
11664 // them.
11665 if y + row >= self.height {
11666 break;
11667 }
11668 for col in 0..side {
11669 if x + col >= self.width {
11670 break;
11671 }
11672 let idx = row * side + col;
11673 let mut base = i32::from(prediction[idx]);
11674 if let Some((alpha_q3, ac_q3)) = cfl {
11675 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max());
11676 }
11677 let sample = (base + residual[idx]).clamp(0, sample_max()) as u16;
11678 self.data[(y + row) * self.width + x + col] = sample;
11679 }
11680 }
11681 }
11682}
11683
11684/// Reads one plane's transform block, reconstructs it into `plane` at
11685/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
11686#[allow(clippy::too_many_arguments)]
11687fn read_plane(
11688 dec: &mut SymbolDecoder,
11689 cdfs: &mut Cdfs,
11690 set: TxbSet,
11691 scan: &[u16],
11692 plane_idx: usize,
11693 around: (bool, bool, i32),
11694 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
11695 // it for every plane's `txb` lookup (it is what an intra transform type's
11696 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
11697 tx_mode: usize,
11698 predict_mode: usize,
11699 angle_delta: i32,
11700 reach: Reach,
11701 plane: &mut PlaneBuf,
11702 x: usize,
11703 y: usize,
11704 side: usize,
11705 tx_side: usize,
11706 base_q_idx: u8,
11707 cfl: Option<(i32, &[i32])>,
11708 filter_intra: Option<usize>,
11709 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
11710 // smaller than its own block (spec `get_txb_ctx_general`'s
11711 // `plane_bsize != tx_size` branch), carrying the already-looked-up
11712 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
11713 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
11714 // formula below.
11715 luma_skip_ctx: Option<usize>,
11716 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
11717 smooth_neighbor: bool,
11718) -> Result<Vec<i32>> {
11719 let skip_ctx = if plane_idx == 0 {
11720 luma_skip_ctx.unwrap_or(0)
11721 } else {
11722 // libaom `get_txb_ctx`: a chroma unit's context is
11723 // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the
11724 // plane block is bigger than the transform. Our chroma tables hold the
11725 // offset-7 rows first, so the caller adds 3 for the bigger-block case
11726 // (only a 128x128 block's TX_32X32 chroma units, lane-sb128b r3).
11727 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
11728 };
11729 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
11730 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
11731 // not by the block's ordinary `mode` (which is always DC_PRED whenever
11732 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
11733 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
11734 // filter-intra in AV1).
11735 let tx_mode = if plane_idx == 0 { fi_tx_row(tx_mode, filter_intra) } else { tx_mode };
11736 let mut coding = cdfs.txb(set, tx_mode);
11737 // Luma's `default_tx_type` is only a fallback for the sizes whose
11738 // `TxbSet` carries no symbol at all (32-point and up), which the spec
11739 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
11740 // *never* its own coded symbol (`coding.tx_type` is always `None` for
11741 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
11742 // the plane's own predicted mode (`default_intra_tx_type`) -- except
11743 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
11744 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
11745 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
11746 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
11747 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
11748 // narrows there — only `Chroma32` and up do).
11749 let default_tx_type = if plane_idx == 0 || side >= 32 {
11750 TxType::DctDct
11751 } else if let Some(inherited) = INTRABC_CHROMA_TX.with(std::cell::Cell::get) {
11752 // See [`INTRABC_CHROMA_TX`]: an intrabc block is an inter block for
11753 // `av1_get_tx_type`, so chroma inherits luma's coded type (the
11754 // `side >= 32` arm above is already libaom's `EXT_TX_SET_DCTONLY`
11755 // clamp at `tx_size_sqr_up >= TX_32X32`, matching
11756 // [`read_inter_plane`]'s own `side < 32` guard).
11757 inherited
11758 } else {
11759 default_intra_tx_type(predict_mode as u8)
11760 };
11761 let (grid, tx_type) = read_coeffs(
11762 dec,
11763 &mut coding,
11764 scan,
11765 skip_ctx,
11766 dc_sign_ctx(around.2),
11767 default_tx_type,
11768 None,
11769 )?;
11770 note_chroma_class1(plane_idx, tx_type);
11771 if plane_idx == 0 {
11772 LUMA_TX_TYPE.with(|c| c.set(tx_type));
11773 }
11774 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
11775 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
11776 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
11777 // guard also assumes.
11778 let levels = if tx_side == side {
11779 grid
11780 } else {
11781 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
11782 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
11783 // keyed by that true size, not the coded corner's -- so the corner
11784 // goes into the top-left of a `side`-sized grid, not the reverse.
11785 let mut full = vec![0i32; side * side];
11786 for row in 0..tx_side {
11787 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
11788 }
11789 full
11790 };
11791 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
11792 let residual = dequant_and_inverse_typed(&levels, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type);
11793 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11794 eprintln!(
11795 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={levels:?} residual={residual:?}",
11796 );
11797 }
11798 plane.reconstruct(
11799 x,
11800 y,
11801 side,
11802 predict_mode,
11803 angle_delta,
11804 reach,
11805 &residual,
11806 cfl,
11807 filter_intra,
11808 smooth_neighbor,
11809 );
11810 Ok(if tx_side == side {
11811 residual_grid_placeholder(&levels, side)
11812 } else {
11813 levels
11814 })
11815}
11816
11817/// `record`'s neighbour state only reads whether *the coded grid* (not the
11818/// residual) has nonzero entries, so the levels this function already built
11819/// are what it wants back; this helper exists only to name that clearly at
11820/// the one call site where `tx_side == side`.
11821fn residual_grid_placeholder(levels: &[i32], _tx_side: usize) -> Vec<i32> {
11822 levels.to_vec()
11823}
11824
11825/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
11826/// three planes, reconstructing them into `y`/`u`/`v` and updating
11827/// `neighbours`.
11828#[allow(clippy::too_many_arguments)]
11829fn decode_block(
11830 dec: &mut SymbolDecoder,
11831 cdfs: &mut Cdfs,
11832 neighbours: &mut Neighbours,
11833 at: (usize, usize),
11834 side: usize,
11835 luma_set: TxbSet,
11836 chroma_set: TxbSet,
11837 luma_tx: usize,
11838 chroma_tx: usize,
11839 scans: (&[u16], &[u16]),
11840 cfl: bool,
11841 y: &mut PlaneBuf,
11842 u: &mut PlaneBuf,
11843 v: &mut PlaneBuf,
11844 base_q_idx: u8,
11845 enable_filter_intra: bool,
11846 allow_screen_content_tools: bool,
11847 allow_intrabc: bool,
11848 scan32: &[u16],
11849 scan16: &[u16],
11850 scan8: &[u16],
11851 scan4: &[u16],
11852 tx_select: bool,
11853 reduced_tx_set: bool,
11854) -> Result<()> {
11855 let (r, c) = at;
11856 let (px, py) = (c * SUB, r * SUB);
11857 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
11858 let palette_uv_cache = neighbours.palette_uv_cache(at);
11859 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
11860 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
11861 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
11862 read_intra_mode(
11863 dec,
11864 cdfs,
11865 nb_above_mode,
11866 nb_left_mode,
11867 cfl,
11868 side,
11869 enable_filter_intra,
11870 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
11871 allow_screen_content_tools,
11872 allow_intrabc,
11873 Some((palette_ctx, &palette_cache)),
11874 &palette_uv_cache,
11875 r * (SUB / MI),
11876 c * (SUB / MI),
11877 )?;
11878 if at_tile_left && palette_y.is_some() {
11879 PALETTE_TILE_LEFT_HITS.with(|c| c.set(c.get() + 1));
11880 }
11881 let intrabc_dv = INTRABC_DV.with(|c| c.take());
11882 // libaom `parse_decode_block`: an intrabc block is `inter_block_tx`, so
11883 // under `TX_MODE_SELECT` its transform size comes from the inter var-tx
11884 // partition tree (`read_var_tx_size`), a syntax element this decoder has
11885 // nowhere -- reading the intra `tx_depth` symbol instead would desync.
11886 if intrabc_dv.is_some() && tx_select && !skip {
11887 return Err(unsupported(
11888 "an intrabc block under TxMode::Select (its transform size is coded by the inter var-tx partition tree, which this decoder never reads)",
11889 ));
11890 }
11891 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
11892 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
11893 // actual chroma-from-luma correlation, same as this decoder always did.
11894 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
11895 DC_PRED
11896 } else {
11897 uv_mode
11898 };
11899 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
11900 if smooth_neighbor {
11901 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
11902 }
11903 let smooth_neighbor_uv =
11904 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
11905 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11906 eprintln!(
11907 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
11908 angle_delta_uv={angle_delta_uv}"
11909 );
11910 }
11911 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
11912 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
11913 // block, skipped or not. `logical_tx` is what the loop filter's edge
11914 // lookup and the next block's own `tx_size_context` want (the *nominal*
11915 // transform size -- 64 even for the 64x64 corner-scanned case, spec
11916 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
11917 // which only differs from it at that one corner case.
11918 let (logical_tx, coeff_tx_side) = if tx_select {
11919 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, None);
11920 (resolved, if resolved == 64 { 32 } else { resolved })
11921 } else {
11922 // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is
11923 // TX_64X64, so a 128x128 block is always FOUR luma transform units
11924 // even with `tx_select` off -- the TU loop below, never the
11925 // single-unit path.
11926 (side.min(64), luma_tx)
11927 };
11928 if tx_select && logical_tx < side && uv_mode != DC_PRED {
11929 SQ_CHROMA_TX_HITS.with(|c| c.set(c.get() + 1));
11930 }
11931 let luma_set = if tx_select {
11932 txbset_for(logical_tx, reduced_tx_set)
11933 } else {
11934 luma_set
11935 };
11936 let luma_set = if intrabc_dv.is_some() {
11937 txbset_for_inter(logical_tx, reduced_tx_set)
11938 } else {
11939 luma_set
11940 };
11941 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
11942 let reach = Reach::of(side, px, py, y.width, y.height);
11943 let (cpx, cpy) = (px / 2, py / 2);
11944 let chroma_side = side / 2;
11945 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
11946 // frame's own pre-loop-filter reconstruction (all loop filters are off
11947 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
11948 // block vector, with the BILINEAR kernel libaom forces for intrabc --
11949 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
11950 // odd, which is exactly what the bilinear taps then interpolate.
11951 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
11952 let mut yb = vec![0u16; side * side];
11953 mc::predict_with_filter(
11954 &y.data, y.width, y.true_width, y.true_height,
11955 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
11956 side, side, mc::InterpFilterKind::Bilinear, &mut yb,
11957 );
11958 let mut ub = vec![0u16; chroma_side * chroma_side];
11959 mc::predict_with_filter(
11960 &u.data, u.width, u.true_width, u.true_height,
11961 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
11962 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut ub,
11963 );
11964 let mut vb = vec![0u16; chroma_side * chroma_side];
11965 mc::predict_with_filter(
11966 &v.data, v.width, v.true_width, v.true_height,
11967 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
11968 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut vb,
11969 );
11970 (yb, ub, vb)
11971 });
11972 if let Some((yb, _, _)) = &intrabc_bufs {
11973 set_palette_pred(yb.clone());
11974 }
11975 // A palette-Y block's own prediction is the reconstructed colour-index
11976 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
11977 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
11978 // parameter through this function's dozen `y.reconstruct`/`read_plane`
11979 // sites. A split luma transform (`tx_select && logical_tx != side`)
11980 // would need the map sliced per-TU -- untested against a real
11981 // `--enable-palette=1` stream this round, so refuse by name rather than
11982 // guess at the slicing (charter's own named-acceptable fallback).
11983 let palette_y_buf: Option<Vec<u16>> = palette_y.as_ref().map(|py| {
11984 py.map
11985 .iter()
11986 .map(|&idx| py.colors[idx as usize])
11987 .collect()
11988 });
11989 // With one luma transform unit the whole `side`x`side` map is the
11990 // prediction; with several (`logical_tx != side`) each unit takes its own
11991 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
11992 // below (lane-palette2 r7) -- setting the full-block buffer here would be
11993 // taken by the FIRST unit and indexed at the wrong stride.
11994 if let Some(buf) = &palette_y_buf
11995 && logical_tx == side
11996 {
11997 set_palette_pred(buf.clone());
11998 }
11999 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
12000 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
12001 // plane's own `reconstruct`/`read_plane` call below (never both planes at
12002 // once), since Y's own set-then-take already emptied the slot by the time
12003 // either of these run.
12004 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
12005 (
12006 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
12007 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
12008 )
12009 });
12010 // The chroma half of the intrabc prediction rides the same per-plane
12011 // override slot the UV-palette buffers do (set fresh before each plane's
12012 // own `reconstruct`/`read_plane` call below).
12013 let palette_uv_bufs = match &intrabc_bufs {
12014 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
12015 None => palette_uv_bufs,
12016 };
12017 if skip {
12018 // A skipped block codes no residual syntax at all (spec 5.11.34):
12019 // straight prediction, on every plane.
12020 //
12021 // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it
12022 // is skipped (only an INTER skip forces the largest transform), and
12023 // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts
12024 // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units
12025 // already written left/above of it inside this same block. Predicting
12026 // the whole `side`x`side` at once gives a different (uniformly off by
12027 // ~1) answer, which is exactly the residue this lane was chasing.
12028 // The palette/intrabc override path keeps the single-call shape (its
12029 // per-TU windowing is the non-skip loop's own `palette_y_buf` slice,
12030 // untested for skip and unreachable in these streams).
12031 // lane-sb128b r2: a 128x128 block's transform is TX_64X64 even with
12032 // `tx_select` off (`max_txsize_rect_lookup[BLOCK_128X128]`), so the
12033 // per-unit prediction is keyed on the transform being smaller than
12034 // the block, not on the tx-depth syntax. The counter keeps lane-hgkf's
12035 // narrower meaning (a READ split tx depth).
12036 let split_tx_skip =
12037 logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none();
12038 if split_tx_skip {
12039 if tx_select {
12040 SKIP_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
12041 }
12042 let n_axis = side / logical_tx;
12043 for tu_row in 0..n_axis {
12044 for tu_col in 0..n_axis {
12045 let tu_px = px + tu_col * logical_tx;
12046 let tu_py = py + tu_row * logical_tx;
12047 if tu_px >= y.true_width || tu_py >= y.true_height {
12048 continue;
12049 }
12050 let tu_reach = tu_reach(
12051 side,
12052 side,
12053 tu_col * logical_tx,
12054 tu_row * logical_tx,
12055 logical_tx,
12056 reach,
12057 px,
12058 py,
12059 y.width,
12060 y.height,
12061 );
12062 y.reconstruct(
12063 tu_px,
12064 tu_py,
12065 logical_tx,
12066 mode,
12067 angle_delta_y,
12068 tu_reach,
12069 &vec![0i32; logical_tx * logical_tx],
12070 None,
12071 filter_intra,
12072 smooth_neighbor,
12073 );
12074 }
12075 }
12076 } else {
12077 y.reconstruct(
12078 px,
12079 py,
12080 side,
12081 mode,
12082 angle_delta_y,
12083 reach,
12084 &vec![0i32; side * side],
12085 None,
12086 filter_intra,
12087 smooth_neighbor,
12088 );
12089 }
12090 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
12091 let cn = (chroma_side / chroma_tx).max(1);
12092 for cu_row in 0..cn {
12093 for cu_col in 0..cn {
12094 let luma_span = chroma_tx * 2;
12095 let cu_r = if cn == 1 {
12096 reach
12097 } else {
12098 tu_reach(
12099 side, side,
12100 cu_col * luma_span, cu_row * luma_span, luma_span,
12101 reach, px, py, y.width, y.height,
12102 )
12103 };
12104 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
12105 if let Some((ub, _)) = &palette_uv_bufs {
12106 set_palette_pred(ub.clone());
12107 }
12108 u.reconstruct(
12109 cu_x,
12110 cu_y,
12111 chroma_tx,
12112 uv_predict_mode,
12113 angle_delta_uv,
12114 cu_r,
12115 &vec![0i32; chroma_tx * chroma_tx],
12116 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
12117 None,
12118 smooth_neighbor_uv,
12119 );
12120 if let Some((_, vb)) = &palette_uv_bufs {
12121 set_palette_pred(vb.clone());
12122 }
12123 v.reconstruct(
12124 cu_x,
12125 cu_y,
12126 chroma_tx,
12127 uv_predict_mode,
12128 angle_delta_uv,
12129 cu_r,
12130 &vec![0i32; chroma_tx * chroma_tx],
12131 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
12132 None,
12133 smooth_neighbor_uv,
12134 );
12135 }
12136 }
12137 let luma_grid = vec![0i32; side * side];
12138 let u_grid = vec![0i32; chroma_side * chroma_side];
12139 let v_grid = vec![0i32; chroma_side * chroma_side];
12140 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
12141 } else if logical_tx == side {
12142 // lane-sb128b r1: the test used to be `!tx_select || logical_tx == side`.
12143 // Without `tx_select` `logical_tx` IS `side` at every size <= 64, so
12144 // that arm was redundant -- and wrong at 128, where
12145 // `max_txsize_rect_lookup` caps the block's transform at 64 and the
12146 // block is four units whether or not `tx_select` is on.
12147 // A single luma transform unit -- the old path, unchanged (including
12148 // the 64x64 corner case, `logical_tx == side == 64` with
12149 // `coeff_tx_side == 32`).
12150 let around = neighbours.around(at, side);
12151 let luma_grid = read_plane(
12152 dec,
12153 cdfs,
12154 luma_set,
12155 luma_scan,
12156 0,
12157 around[0],
12158 mode,
12159 mode,
12160 angle_delta_y,
12161 reach,
12162 y,
12163 px,
12164 py,
12165 side,
12166 coeff_tx_side,
12167 base_q_idx,
12168 None,
12169 filter_intra,
12170 None,
12171 smooth_neighbor,
12172 )?;
12173 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
12174 // Armed for exactly this block's two chroma reads (see
12175 // [`INTRABC_CHROMA_TX`]); the luma call above just set
12176 // [`LUMA_TX_TYPE`] to the type it coded.
12177 if intrabc_dv.is_some() {
12178 INTRABC_CHROMA_TX.with(|c| c.set(Some(LUMA_TX_TYPE.with(std::cell::Cell::get))));
12179 }
12180 if let Some((ub, _)) = &palette_uv_bufs {
12181 set_palette_pred(ub.clone());
12182 }
12183 let u_grid = read_plane(
12184 dec,
12185 cdfs,
12186 chroma_set,
12187 scans.1,
12188 1,
12189 around[1],
12190 mode,
12191 uv_predict_mode,
12192 angle_delta_uv,
12193 reach,
12194 u,
12195 cpx,
12196 cpy,
12197 chroma_side,
12198 chroma_tx,
12199 base_q_idx,
12200 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
12201 None,
12202 None,
12203 smooth_neighbor_uv,
12204 )?;
12205 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12206 eprintln!(
12207 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
12208 &u.data[cpy * u.width + cpx..][..chroma_side]
12209 );
12210 }
12211 if let Some((_, vb)) = &palette_uv_bufs {
12212 set_palette_pred(vb.clone());
12213 }
12214 let v_grid = read_plane(
12215 dec,
12216 cdfs,
12217 chroma_set,
12218 scans.1,
12219 2,
12220 around[2],
12221 mode,
12222 uv_predict_mode,
12223 angle_delta_uv,
12224 reach,
12225 v,
12226 cpx,
12227 cpy,
12228 chroma_side,
12229 chroma_tx,
12230 base_q_idx,
12231 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
12232 None,
12233 None,
12234 smooth_neighbor_uv,
12235 )?;
12236 INTRABC_CHROMA_TX.with(|c| c.set(None));
12237 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
12238 } else {
12239 // Several luma transform units, raster order (spec
12240 // `transform_block`'s loop): the block's resolved transform is
12241 // genuinely smaller than its own side, so each tile of it predicts
12242 // and codes independently, its own context read fresh off whatever
12243 // the earlier tiles in this same block already wrote -- the same
12244 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
12245 let n_axis = side / logical_tx;
12246 let cn = (chroma_side / chroma_tx).max(1);
12247 // libaom's transform-block loop is over 64x64 luma "mu" chunks
12248 // (`decode_token_recon_block`: `mu_blocks_wide/high` =
12249 // `mi_size_wide[BLOCK_64X64]`), and it codes EVERY PLANE of a chunk
12250 // before moving to the next one. Below 128 a block is a single chunk,
12251 // so this is byte-for-byte the all-luma-then-all-chroma order that has
12252 // always run; at 128 the four quadrants interleave Y,U,V per quadrant
12253 // and reading all four luma units first desyncs the tile at the second
12254 // one (lane-sb128b r3, measured against aomdec's `EC_TRACE_COEFF`).
12255 let nchunk = (side / 64).max(1);
12256 // `cn > 1` means the uv plane block is larger than the uv transform,
12257 // which moves libaom's chroma `txb_skip_ctx` offset from 7 to 10.
12258 let chroma_ctx_offset = if cn > 1 { Some(3) } else { None };
12259 let tpc = (n_axis / nchunk).max(1);
12260 let cpc = (cn / nchunk).max(1);
12261 let mut last_grids = [Vec::new(), Vec::new()];
12262 let mut units: Vec<((usize, usize), usize, Vec<i32>, Vec<i32>)> = Vec::new();
12263 for ch_row in 0..nchunk {
12264 for ch_col in 0..nchunk {
12265 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
12266 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
12267 let tu_mi = (
12268 mi_r + tu_row * (logical_tx / MI),
12269 mi_c + tu_col * (logical_tx / MI),
12270 );
12271 let tu_px = px + tu_col * logical_tx;
12272 let tu_py = py + tu_row * logical_tx;
12273 // Same libaom clip as `decode_rect_split`'s loop above; a
12274 // square block only hangs off the frame when the frame's mi
12275 // dimensions are odd at the block's own level.
12276 if tu_px >= y.true_width || tu_py >= y.true_height {
12277 continue;
12278 }
12279 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
12280 // A transform unit inside a block is NOT a block at that
12281 // position (lane-palette2 r12): `Reach::of` granted the
12282 // top-right 8x8 unit of a 16x16 D203 block bottom-left
12283 // pixels libaom refuses outright (`col_off > 0`), which is
12284 // the diagonal wedge seed 46 reconstructed wrong.
12285 let tu_reach = tu_reach(
12286 side,
12287 side,
12288 tu_col * logical_tx,
12289 tu_row * logical_tx,
12290 logical_tx,
12291 reach,
12292 px,
12293 py,
12294 y.width,
12295 y.height,
12296 );
12297 // This transform unit's own bsize (`logical_tx`) is smaller
12298 // than the block it sits in (`side`), so `txb_skip_ctx` is
12299 // the neighbour-magnitude table, not the lone-TU 0 (spec
12300 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
12301 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
12302 if let Some(buf) = &palette_y_buf {
12303 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
12304 let mut window = vec![0u16; logical_tx * logical_tx];
12305 for row in 0..logical_tx {
12306 let src = (tu_row * logical_tx + row) * side + tu_col * logical_tx;
12307 window[row * logical_tx..][..logical_tx]
12308 .copy_from_slice(&buf[src..][..logical_tx]);
12309 }
12310 set_palette_pred(window);
12311 }
12312 let tu_grid = read_plane(
12313 dec,
12314 cdfs,
12315 luma_set,
12316 luma_scan,
12317 0,
12318 tu_around,
12319 mode,
12320 mode,
12321 angle_delta_y,
12322 tu_reach,
12323 y,
12324 tu_px,
12325 tu_py,
12326 logical_tx,
12327 // The unit's own COEFFICIENT grid, half its side at
12328 // TX_64X64 (a 64-point transform codes nothing past 32);
12329 // identical to `logical_tx` at every smaller size
12330 // (lane-sb128b r1).
12331 coeff_tx_side,
12332 base_q_idx,
12333 None,
12334 filter_intra,
12335 Some(tu_skip_ctx),
12336 smooth_neighbor,
12337 )?;
12338 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12339 eprintln!(
12340 "TRACE tu_bitpos mi=({},{}) tell={}",
12341 tu_mi.0,
12342 tu_mi.1,
12343 dec.debug_bitpos()
12344 );
12345 }
12346 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
12347 }
12348 }
12349 // CfL is only allowed up to 32x32, i.e. only at `nchunk == 1`, where
12350 // this still runs after every luma unit of the block.
12351 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
12352 // The block's uv plane block is `chroma_side` across but its uv
12353 // transform is `chroma_tx` (`av1_get_max_uv_txsize` =
12354 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[uv_plane_bsize])`):
12355 // identical at every size up to 64x64, but a 128x128 block's 64x64 uv
12356 // plane block adjusts TX_64X64 down to TX_32X32, so each plane is
12357 // FOUR units (lane-sb128b r2) -- one per mu chunk.
12358 for cu_row in ch_row * cpc..(ch_row + 1) * cpc {
12359 for cu_col in ch_col * cpc..(ch_col + 1) * cpc {
12360 // The chroma context arrays are indexed in LUMA mi, so this
12361 // unit's anchor is its own luma quadrant: `chroma_tx` chroma
12362 // pixels span `2 * chroma_tx` luma ones.
12363 let luma_span = chroma_tx * 2;
12364 let cu_mi = (
12365 mi_r + cu_row * (luma_span / MI),
12366 mi_c + cu_col * (luma_span / MI),
12367 );
12368 let cu_around = neighbours.around_mi(cu_mi, luma_span);
12369 let cu_reach = if cn == 1 {
12370 reach
12371 } else {
12372 tu_reach(
12373 side, side,
12374 cu_col * luma_span, cu_row * luma_span, luma_span,
12375 reach, px, py, y.width, y.height,
12376 )
12377 };
12378 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
12379 if let Some((ub, _)) = &palette_uv_bufs {
12380 set_palette_pred(ub.clone());
12381 }
12382 let u_grid = read_plane(
12383 dec, cdfs, chroma_set, scans.1, 1, cu_around[1], mode,
12384 uv_predict_mode, angle_delta_uv, cu_reach, u, cu_x, cu_y,
12385 chroma_tx, chroma_tx, base_q_idx,
12386 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
12387 None, chroma_ctx_offset, smooth_neighbor_uv,
12388 )?;
12389 if let Some((_, vb)) = &palette_uv_bufs {
12390 set_palette_pred(vb.clone());
12391 }
12392 let v_grid = read_plane(
12393 dec, cdfs, chroma_set, scans.1, 2, cu_around[2], mode,
12394 uv_predict_mode, angle_delta_uv, cu_reach, v, cu_x, cu_y,
12395 chroma_tx, chroma_tx, base_q_idx,
12396 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
12397 None, chroma_ctx_offset, smooth_neighbor_uv,
12398 )?;
12399 if cn > 1 {
12400 CHROMA_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
12401 // Immediately, so the NEXT unit of this same block reads
12402 // this one's coefficient context (libaom's chroma
12403 // `txb_skip_ctx` for the second quadrant is 11, i.e. base
12404 // 1 from this left neighbour -- measured against aomdec).
12405 // The same writes are replayed after `record_split_luma`
12406 // below, which would otherwise clobber them whole-block.
12407 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 1, &u_grid);
12408 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 2, &v_grid);
12409 units.push((cu_mi, luma_span, u_grid.clone(), v_grid.clone()));
12410 }
12411 last_grids = [u_grid, v_grid];
12412 }
12413 }
12414 }
12415 }
12416 // Mode/side bookkeeping plus, at `cn == 1`, the whole-plane chroma
12417 // context write; at `cn > 1` the per-unit writes above are what the
12418 // next block reads, so they run after this (last writer wins).
12419 neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&last_grids[0], &last_grids[1]]);
12420 for (cu_mi, luma_span, u_grid, v_grid) in &units {
12421 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 1, u_grid);
12422 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 2, v_grid);
12423 }
12424 }
12425 // Unconditional, `size == 0` for a non-palette block: clears any stale
12426 // neighbour palette state the same way [`Neighbours::record`] always
12427 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
12428 // (the split-luma-TU branch above always refuses before reaching here
12429 // when `palette_y` is `Some`, so it is never live for that branch).
12430 let (py_size, py_colors) = palette_y
12431 .as_ref()
12432 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12433 neighbours.record_palette_y(at, side, py_size, py_colors);
12434 let (puv_size, puv_colors) = palette_uv
12435 .as_ref()
12436 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12437 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
12438 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
12439 neighbours.fill_lf_grid(
12440 (r * (SUB / MI), c * (SUB / MI)),
12441 side / MI,
12442 logical_tx as u8,
12443 0,
12444 );
12445 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv);
12446 Ok(())
12447}
12448
12449thread_local! {
12450 /// lane-sb128c r8: INTRA (key-frame) 128x64 blocks decoded at the 128
12451 /// root's HORZ arm, and 64x128 ones at its VERT arm.
12452 pub(crate) static INTRA_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
12453 pub(crate) static INTRA_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
12454 /// Those blocks by resolved intra `tx_depth` (0 = TX_64X64 units,
12455 /// 1 = TX_32X32, 2 = TX_16X16) -- proof the depth symbol is really read.
12456 pub(crate) static INTRA_SB128_DEPTH_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
12457 /// lane-inter128intra r1: the same shapes decoded on the INTER block path
12458 /// (an intra-coded PARTITION_HORZ/VERT half of a 128 superblock inside an
12459 /// inter frame) -- (128x64, 64x128).
12460 pub(crate) static INTRA128_IN_INTER_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
12461 /// lane-t900 r17: skipped INTER blocks whose `read_block_tx_size` still
12462 /// handed back var-tx leaves, so the per-transform-unit luma publication
12463 /// loop never ran and the block has to clear its own luma coefficient
12464 /// contexts (libaom `av1_reset_entropy_context`). Every 128 root under
12465 /// `TX_MODE_LARGEST` is one; the counter is what keeps that reset's gate
12466 /// non-vacuous.
12467 pub(crate) static SKIP_VARTX_LUMA_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
12468}
12469
12470/// [`SKIP_VARTX_LUMA_RESET_HITS`], for a gate's own before/after delta.
12471pub fn skip_vartx_luma_reset_hits() -> usize {
12472 SKIP_VARTX_LUMA_RESET_HITS.with(std::cell::Cell::get)
12473}
12474
12475/// [`INTRA128_IN_INTER_HITS`], for a gate's own before/after delta.
12476pub(crate) fn intra128_in_inter_hits() -> [usize; 2] {
12477 INTRA128_IN_INTER_HITS.with(std::cell::Cell::get)
12478}
12479
12480/// [`INTRA_SB128_HORZ_HITS`] / [`INTRA_SB128_VERT_HITS`] /
12481/// [`INTRA_SB128_DEPTH_HITS`], for a gate's own before/after delta.
12482pub(crate) fn intra_sb128_hits() -> (usize, usize, [usize; 3]) {
12483 (
12484 INTRA_SB128_HORZ_HITS.with(std::cell::Cell::get),
12485 INTRA_SB128_VERT_HITS.with(std::cell::Cell::get),
12486 INTRA_SB128_DEPTH_HITS.with(std::cell::Cell::get),
12487 )
12488}
12489
12490/// The 128 root's HORZ/VERT arm on an INTRA frame: ONE 128x64 (HORZ) or
12491/// 64x128 (VERT) intra block (lane-sb128c r8; the inter twin is
12492/// `decode_inter_block`'s own rect path).
12493///
12494/// libaom `decode_block` -> `predict_and_reconstruct_intra_block` per
12495/// transform unit, with the 128-specific geometry:
12496/// * `max_txsize_rect_lookup[BLOCK_128X64]` is TX_64X64, so every luma unit
12497/// is SQUARE and there are at least two of them -- depth 0: 64x64 x2,
12498/// depth 1: 32x32 x8, depth 2: 16x16 x32 (`bsize_to_tx_size_cat` counts
12499/// the `sub_tx_size_map` chain TX_64X64->32->16->8->4, i.e. cat 3, the
12500/// same CDF a 64x64 square block reads).
12501/// * `av1_get_max_uv_txsize` = `av1_get_adjusted_tx_size(
12502/// max_txsize_rect_lookup[BLOCK_64X32])` caps at TX_32X32, so the block's
12503/// 64x32 uv plane block is TWO 32x32 chroma units per plane -- one per
12504/// 64x64 luma "mu" chunk, and `decode_token_recon_block` codes Y, U, V of
12505/// a chunk before moving to the next (the interleave lane-sb128b r3
12506/// measured at the 128x128 NONE root).
12507/// * `get_txb_ctx`: the uv plane block is bigger than the uv transform, so
12508/// chroma `txb_skip_ctx` takes the offset-10 rows (7 + 3).
12509/// No CfL, no filter intra (both cap at 32x32) and no palette
12510/// (`av1_allow_palette` caps at 64x64) exist at this size -- the mode
12511/// reader's own size gates already say so, and the guard below is defensive.
12512#[allow(clippy::too_many_arguments)]
12513fn decode_block_128rect(
12514 dec: &mut SymbolDecoder,
12515 cdfs: &mut Cdfs,
12516 neighbours: &mut Neighbours,
12517 at: (usize, usize),
12518 bw: usize,
12519 bh: usize,
12520 y: &mut PlaneBuf,
12521 u: &mut PlaneBuf,
12522 v: &mut PlaneBuf,
12523 base_q_idx: u8,
12524 enable_filter_intra: bool,
12525 allow_screen_content_tools: bool,
12526 tx_select: bool,
12527 reduced_tx_set: bool,
12528) -> Result<()> {
12529 let (r, c) = at;
12530 let (px, py) = (c * SUB, r * SUB);
12531 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
12532 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
12533 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
12534 let palette_uv_cache = neighbours.palette_uv_cache(at);
12535 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
12536 read_intra_mode_rect(
12537 dec,
12538 cdfs,
12539 nb_above_mode,
12540 nb_left_mode,
12541 // `is_cfl_allowed` caps CFL at 32x32: `uv_mode` comes off the
12542 // 13-symbol no-CFL CDF here, never the 14-symbol one.
12543 false,
12544 true,
12545 bw,
12546 bh,
12547 enable_filter_intra,
12548 neighbours.skip_txfm_ctx(mi_r, mi_c),
12549 allow_screen_content_tools,
12550 Some((palette_ctx, &palette_cache)),
12551 &palette_uv_cache,
12552 mi_r,
12553 mi_c,
12554 )?;
12555 if alpha.is_some() || filter_intra.is_some() || palette_y.is_some() || palette_uv.is_some() {
12556 return Err(unsupported(
12557 "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of \
12558 their size gates caps at 64x64 or below, so none of these symbols exists there)",
12559 ));
12560 }
12561 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
12562 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
12563 if smooth_neighbor {
12564 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
12565 }
12566 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
12567 // spec 5.11.16 `read_tx_size`: read for every intra block, skipped or
12568 // not. `bsize_to_tx_size_cat(BLOCK_128X64)` is 3 (see this fn's doc).
12569 let in_inter = INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some();
12570 let depth = if tx_select {
12571 // lane-inter128intra r1: on an INTER frame `get_tx_size_context` reads
12572 // the real `TXFM_CONTEXT` bands, and compares them against
12573 // `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` -- TX_64X64 for
12574 // every 128-axis block, hence the `min(64)`.
12575 let ctx = if in_inter {
12576 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64))
12577 } else {
12578 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
12579 };
12580 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
12581 } else {
12582 0
12583 };
12584 if depth != 0 {
12585 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
12586 }
12587 INTRA_SB128_DEPTH_HITS.with(|c| {
12588 let mut h = c.get();
12589 h[depth.min(2)] += 1;
12590 c.set(h);
12591 });
12592 let logical_tx = 64 >> depth;
12593 // A 64-point transform codes nothing past its low 32 coefficients.
12594 let coeff_tx_side = logical_tx.min(32);
12595 let luma_set = txbset_for(logical_tx, reduced_tx_set);
12596 let luma_scan = default_scan(coeff_tx_side);
12597 let chroma_tx = 32;
12598 let chroma_scan = default_scan(chroma_tx);
12599 let (cpx, cpy) = (px / 2, py / 2);
12600 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
12601 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
12602 let (nch_x, nch_y) = (bw / 64, bh / 64);
12603 // One 32x32 chroma unit per mu chunk, per plane.
12604 debug_assert_eq!((chroma_w / chroma_tx, chroma_h / chroma_tx), (nch_x, nch_y));
12605 let tpc = 64 / logical_tx;
12606 let zero_tu = vec![0i32; logical_tx * logical_tx];
12607 let zero_cu = vec![0i32; chroma_tx * chroma_tx];
12608 let mut last_grids = [Vec::new(), Vec::new()];
12609 let mut units: Vec<((usize, usize), Vec<i32>, Vec<i32>)> = Vec::new();
12610 for ch_row in 0..nch_y {
12611 for ch_col in 0..nch_x {
12612 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
12613 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
12614 let tu_mi = (
12615 mi_r + tu_row * (logical_tx / MI),
12616 mi_c + tu_col * (logical_tx / MI),
12617 );
12618 let (tu_px, tu_py) = (px + tu_col * logical_tx, py + tu_row * logical_tx);
12619 // libaom clips the transform loop to
12620 // `max_blocks_wide/high`: a unit whose top-left sample is
12621 // outside the frame is never coded.
12622 if tu_px >= y.true_width || tu_py >= y.true_height {
12623 continue;
12624 }
12625 // Edge availability of a unit INSIDE a block, with the
12626 // 128 geometry -- `has_top_right` is false for a block
12627 // whose largest side is > 64, which [`Reach::of_rect`]
12628 // already answered for the block and [`tu_reach`] carries
12629 // down to the units on its own top row.
12630 let tu_r = tu_reach(
12631 bw,
12632 bh,
12633 tu_col * logical_tx,
12634 tu_row * logical_tx,
12635 logical_tx,
12636 reach,
12637 px,
12638 py,
12639 y.width,
12640 y.height,
12641 );
12642 if skip {
12643 y.reconstruct(
12644 tu_px, tu_py, logical_tx, mode, angle_delta_y, tu_r, &zero_tu, None,
12645 None, smooth_neighbor,
12646 );
12647 neighbours.record_mi_luma(tu_mi, logical_tx, &zero_tu);
12648 continue;
12649 }
12650 // The unit is smaller than its block, so `txb_skip_ctx`
12651 // is the neighbour-magnitude table, never the lone-TU 0.
12652 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
12653 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
12654 let tu_grid = read_plane(
12655 dec,
12656 cdfs,
12657 luma_set,
12658 &luma_scan,
12659 0,
12660 tu_around,
12661 mode,
12662 mode,
12663 angle_delta_y,
12664 tu_r,
12665 y,
12666 tu_px,
12667 tu_py,
12668 logical_tx,
12669 coeff_tx_side,
12670 base_q_idx,
12671 None,
12672 None,
12673 Some(tu_skip_ctx),
12674 smooth_neighbor,
12675 )?;
12676 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
12677 }
12678 }
12679 // The chroma context arrays are indexed in LUMA mi, so this
12680 // unit's anchor is its own 64x64 mu chunk.
12681 let luma_span = chroma_tx * 2;
12682 let cu_mi = (
12683 mi_r + ch_row * (luma_span / MI),
12684 mi_c + ch_col * (luma_span / MI),
12685 );
12686 let cu_r = tu_reach(
12687 bw,
12688 bh,
12689 ch_col * luma_span,
12690 ch_row * luma_span,
12691 luma_span,
12692 reach,
12693 px,
12694 py,
12695 y.width,
12696 y.height,
12697 );
12698 let (cu_x, cu_y) = (cpx + ch_col * chroma_tx, cpy + ch_row * chroma_tx);
12699 if skip {
12700 u.reconstruct(
12701 cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r, &zero_cu, None,
12702 None, smooth_neighbor_uv,
12703 );
12704 v.reconstruct(
12705 cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r, &zero_cu, None,
12706 None, smooth_neighbor_uv,
12707 );
12708 continue;
12709 }
12710 let cu_around = neighbours.around_mi(cu_mi, luma_span);
12711 let u_grid = read_plane(
12712 dec, cdfs, TxbSet::Chroma32, &chroma_scan, 1, cu_around[1], mode, uv_predict_mode,
12713 angle_delta_uv, cu_r, u, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, None, None,
12714 Some(3), smooth_neighbor_uv,
12715 )?;
12716 let v_grid = read_plane(
12717 dec, cdfs, TxbSet::Chroma32, &chroma_scan, 2, cu_around[2], mode, uv_predict_mode,
12718 angle_delta_uv, cu_r, v, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, None, None,
12719 Some(3), smooth_neighbor_uv,
12720 )?;
12721 CHROMA_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
12722 // Immediately, so the NEXT unit of this same block reads this
12723 // one's coefficient context; replayed after `record_split_luma_rect`
12724 // below, which would otherwise clobber them whole-block.
12725 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 1, &u_grid);
12726 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 2, &v_grid);
12727 units.push((cu_mi, u_grid.clone(), v_grid.clone()));
12728 last_grids = [u_grid, v_grid];
12729 }
12730 }
12731 if skip {
12732 neighbours.record_rect(
12733 at,
12734 bw,
12735 bh,
12736 mode,
12737 uv_predict_mode,
12738 &[
12739 vec![0i32; bw * bh],
12740 vec![0i32; chroma_w * chroma_h],
12741 vec![0i32; chroma_w * chroma_h],
12742 ],
12743 );
12744 } else {
12745 neighbours.record_split_luma_rect(
12746 at,
12747 bw,
12748 bh,
12749 mode,
12750 uv_predict_mode,
12751 [&last_grids[0], &last_grids[1]],
12752 );
12753 for (cu_mi, u_grid, v_grid) in &units {
12754 neighbours.record_mi_chroma(*cu_mi, 64, 64, 1, u_grid);
12755 neighbours.record_mi_chroma(*cu_mi, 64, 64, 2, v_grid);
12756 }
12757 }
12758 // No palette exists at this size; the unconditional stamp clears any
12759 // stale neighbour palette state, as every other block path does.
12760 neighbours.record_palette_y_rect(at, bw, bh, 0, [0u16; 8]);
12761 neighbours.record_palette_uv_rect(at, bw, bh, 0, [0u16; 8]);
12762 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
12763 neighbours.fill_lf_grid_rect(
12764 (mi_r, mi_c),
12765 bw / MI,
12766 bh / MI,
12767 logical_tx as u8,
12768 logical_tx as u8,
12769 0,
12770 );
12771 if in_inter {
12772 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)`
12773 // (libaom `decodeframe.c` `decode_block`) runs for EVERY block of an
12774 // inter frame, intra ones included: an intra block stamps its
12775 // TRANSFORM size over its own footprint in both TXFM_CONTEXT bands.
12776 // A key frame has no var-tx tree and its readers use the deblock grid,
12777 // so this is the inter path's alone.
12778 txfm_partition_update_rect(
12779 neighbours,
12780 (mi_r, mi_c),
12781 (logical_tx, logical_tx),
12782 (bw, bh),
12783 );
12784 INTRA128_IN_INTER_HITS.with(|c| {
12785 let mut h = c.get();
12786 h[usize::from(bw < bh)] += 1;
12787 c.set(h);
12788 });
12789 } else if bw > bh {
12790 INTRA_SB128_HORZ_HITS.with(|c| c.set(c.get() + 1));
12791 } else {
12792 INTRA_SB128_VERT_HITS.with(|c| c.set(c.get() + 1));
12793 }
12794 Ok(())
12795}
12796
12797
12798/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
12799/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
12800/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
12801/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
12802/// just-decoded mode, not the enclosing slot's stale one, is the true
12803/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
12804/// units, which is what its coefficient context (finer than [`SUB`]) is read
12805/// at. Returns the mode this leaf decoded, for the caller's own
12806/// `prev_leaf`/final mode-writeback bookkeeping.
12807#[allow(clippy::too_many_arguments)]
12808/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
12809/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
12810/// `above_mode[col]`, and its true above neighbour is the mi directly above
12811/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
12812/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
12813/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
12814/// (bottom-right) into both, as this path did, is right only when all four
12815/// leaves happen to share a mode. `done` may be short at the true frame edge
12816/// (the straddle caller filters positions off the frame), so each side falls
12817/// back to the last leaf actually decoded.
12818fn write_back_split_modes(
12819 neighbours: &mut Neighbours,
12820 done: &[((usize, usize), usize)],
12821 parent_mi: (usize, usize),
12822 slot: (usize, usize),
12823) {
12824 let (sr, sc) = slot;
12825 let Some(&(_, last)) = done.last() else {
12826 return;
12827 };
12828 let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m);
12829 neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last);
12830 neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last);
12831}
12832
12833fn decode_leaf8(
12834 dec: &mut SymbolDecoder,
12835 cdfs: &mut Cdfs,
12836 neighbours: &mut Neighbours,
12837 outer_at: (usize, usize),
12838 leaf_mi: (usize, usize),
12839 scans: (&[u16], &[u16]),
12840 prev_leaf: Option<((usize, usize), usize)>,
12841 y: &mut PlaneBuf,
12842 u: &mut PlaneBuf,
12843 v: &mut PlaneBuf,
12844 base_q_idx: u8,
12845 enable_filter_intra: bool,
12846 allow_screen_content_tools: bool,
12847 allow_intrabc: bool,
12848 tx_select: bool,
12849 reduced_tx_set: bool,
12850) -> Result<usize> {
12851 let (r, c) = outer_at;
12852 // lane-modectx r1: the group's own availability-correct fallback pair, not
12853 // the raw coarse bands (which leak across a tile edge -- see
12854 // `modes_above_left`).
12855 let (mut above_mode, mut left_mode) = neighbours.modes_above_left(r, c);
12856 if let Some(((pr, pc), pmode)) = prev_leaf {
12857 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
12858 above_mode = pmode;
12859 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
12860 left_mode = pmode;
12861 }
12862 }
12863 // The mi-exact neighbour wins over both the coarse 16x16 slot and
12864 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
12865 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
12866 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
12867 // lane-rectsplitx r2 swept this arm into
12868 // [`Neighbours::modes_above_left_mi`]: the mi-exact map ALSO has to answer
12869 // "no neighbour" at a tile edge, where the coarse cell holds the block
12870 // above/left of it inside the same 16x16.
12871 let (above_mode, left_mode) =
12872 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
12873 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
12874 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
12875 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
12876 // this leaf's `smooth_neighbor` is built from -- passing `false` here
12877 // filtered a directional chroma block's edge at the wrong strength
12878 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
12879 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
12880 // with the coarse [`SUB`] slot as the fallback when no block recorded
12881 // that exact mi cell.
12882 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
12883 if smooth_neighbor {
12884 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
12885 }
12886 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
12887 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
12888 // `decode_block` caller at 16x16 and up.
12889 // lane-pal8 r1: this leaf's own palette-Y mode ctx and colour cache
12890 // (`av1_get_palette_mode_ctx` / `av1_get_palette_cache`, decodemv.c:567,
12891 // `read_palette_mode_info`), at its REAL mi position -- passing
12892 // `None`/`&[]` read `palette_y_mode` off CDF row 0 and refused by name the
12893 // moment a real 8x8 palette block fired, which is where every 8-bit
12894 // `--tune-content=screen --min-partition-size=8` stream stopped.
12895 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(leaf_mi);
12896 let palette_uv_cache = neighbours.palette_uv_cache_mi(leaf_mi);
12897 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
12898 read_intra_mode(
12899 dec,
12900 cdfs,
12901 above_mode,
12902 left_mode,
12903 true,
12904 8,
12905 enable_filter_intra,
12906 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
12907 allow_screen_content_tools,
12908 allow_intrabc,
12909 Some((palette_ctx, &palette_cache)),
12910 &palette_uv_cache,
12911 leaf_mi.0,
12912 leaf_mi.1,
12913 )?;
12914 // lane-kf900 r7: an 8x8 leaf consumed `use_intrabc` (and its DV) through
12915 // `read_intra_mode` and then decoded the block as if it were ordinary
12916 // intra. libaom's `is_inter_block` counts an intrabc block
12917 // (`blockd.h:373`), so its luma `tx_type` comes off the INTER ext-tx set
12918 // (`av1_get_ext_tx_set_type(TX_8X8, is_inter=1, 0)` = `EXT_TX_SET_ALL16`,
12919 // a 16-symbol CDF) while we read the 7-symbol `TX_SET_INTRA_1` row: the
12920 // same value with a different interval, so the tile desynced at the very
12921 // next symbol (class `wrong-alphabet-same-value`). Everything below
12922 // mirrors `decode_block`'s own intrabc handling at 16x16 and up.
12923 let intrabc_dv = INTRABC_DV.with(|c| c.take());
12924 if intrabc_dv.is_some() {
12925 LEAF8_INTRABC_HITS.with(|c| c.set(c.get() + 1));
12926 }
12927 if intrabc_dv.is_some() && tx_select && !skip {
12928 return Err(unsupported(
12929 "an intrabc block under TxMode::Select (its transform size is coded by the inter var-tx partition tree, which this decoder never reads)",
12930 ));
12931 }
12932 // `av1_visit_palette`'s reconstruction (decodeframe.c:1135): the colour
12933 // index map, mapped through the base colours, IS the block's prediction --
12934 // carried to the next `reconstruct`/`read_plane` through the same
12935 // [`PALETTE_PRED`] slot [`decode_block`] uses at 16x16 and up.
12936 let palette_y_buf: Option<Vec<u16>> = palette_y
12937 .as_ref()
12938 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
12939 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
12940 (
12941 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
12942 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
12943 )
12944 });
12945 let (pal_y_size, pal_y_colors) =
12946 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12947 let (pal_uv_size, pal_uv_colors) =
12948 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12949 if palette_y.is_some() || palette_uv.is_some() {
12950 PALETTE_LEAF8_HITS.with(|c| c.set(c.get() + 1));
12951 }
12952 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
12953 DC_PRED
12954 } else {
12955 uv_mode
12956 };
12957 neighbours.above_uv_mode[c] = uv_predict_mode;
12958 neighbours.left_uv_mode[r] = uv_predict_mode;
12959 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
12960 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
12961 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
12962 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
12963 // transform units, same raster-order per-TU pattern `decode_block`'s
12964 // multi-TU branch runs).
12965 // ... and an intrabc leaf reads no intra `tx_depth` symbol at all: under
12966 // `TX_MODE_SELECT` a skipped inter block takes the largest transform
12967 // (`read_tx_size(.., is_inter=1, ..)`), and the unskipped case is refused
12968 // above.
12969 let resolved = if tx_select && intrabc_dv.is_none() {
12970 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, None)
12971 } else {
12972 8
12973 };
12974 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
12975 let reach = Reach::of(8, px, py, y.width, y.height);
12976 let (cpx, cpy) = (px / 2, py / 2);
12977 // spec 7.11.3.4 with `use_intrabc`, same as `decode_block`: predict from
12978 // the CURRENT frame's own pre-loop-filter reconstruction (every loop
12979 // filter is off whenever `allow_intrabc`, frame.rs:194/210/252/272) at
12980 // the full-pel block vector, with the BILINEAR kernel libaom forces.
12981 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
12982 let mut yb = vec![0u16; 8 * 8];
12983 mc::predict_with_filter(
12984 &y.data, y.width, y.true_width, y.true_height,
12985 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
12986 8, 8, mc::InterpFilterKind::Bilinear, &mut yb,
12987 );
12988 let mut ub = vec![0u16; 4 * 4];
12989 mc::predict_with_filter(
12990 &u.data, u.width, u.true_width, u.true_height,
12991 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
12992 4, 4, mc::InterpFilterKind::Bilinear, &mut ub,
12993 );
12994 let mut vb = vec![0u16; 4 * 4];
12995 mc::predict_with_filter(
12996 &v.data, v.width, v.true_width, v.true_height,
12997 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
12998 4, 4, mc::InterpFilterKind::Bilinear, &mut vb,
12999 );
13000 (yb, ub, vb)
13001 });
13002 // The per-plane prediction override rides the same [`PALETTE_PRED`] slot
13003 // `decode_block` uses: set fresh right before each plane's own
13004 // `reconstruct`/`read_plane` call (the slot is taken, not copied).
13005 if let Some((yb, _, _)) = &intrabc_bufs {
13006 set_palette_pred(yb.clone());
13007 }
13008 let (luma_grid, u_grid, v_grid);
13009 if skip {
13010 // lane-hgkf r2 (same shape as `decode_block`'s own skip branch): an
13011 // 8x8 leaf whose `tx_depth` resolved to TX_4X4 predicts FOUR 4x4
13012 // transform units, each off the units already written left/above of
13013 // it inside this same leaf -- an intra block's transform size is read
13014 // whether or not it is skipped, and spec 7.11.2 predicts per unit.
13015 // A palette block's prediction is the whole-block index map, never
13016 // per-transform-unit edges ([`decode_block`]'s own `split_tx_skip`
13017 // rule) -- so a palette leaf takes the single 8x8 reconstruct below
13018 // even when `tx_depth` resolved to TX_4X4.
13019 if resolved == 4 && palette_y_buf.is_none() {
13020 SKIP_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
13021 for tu_row in 0..2 {
13022 for tu_col in 0..2 {
13023 let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4);
13024 if tu_px >= y.true_width || tu_py >= y.true_height {
13025 continue;
13026 }
13027 let tu_reach = tu_reach(
13028 8,
13029 8,
13030 tu_col * 4,
13031 tu_row * 4,
13032 4,
13033 reach,
13034 px,
13035 py,
13036 y.width,
13037 y.height,
13038 );
13039 y.reconstruct(
13040 tu_px,
13041 tu_py,
13042 4,
13043 mode,
13044 angle_delta_y,
13045 tu_reach,
13046 &vec![0i32; 16],
13047 None,
13048 filter_intra,
13049 smooth_neighbor,
13050 );
13051 }
13052 }
13053 } else {
13054 if let Some(buf) = &palette_y_buf {
13055 set_palette_pred(buf.clone());
13056 }
13057 y.reconstruct(
13058 px,
13059 py,
13060 8,
13061 mode,
13062 angle_delta_y,
13063 reach,
13064 &vec![0i32; 64],
13065 None,
13066 filter_intra,
13067 smooth_neighbor,
13068 );
13069 }
13070 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
13071 if let Some((_, ub, _)) = &intrabc_bufs {
13072 set_palette_pred(ub.clone());
13073 } else if let Some((ub, _)) = &palette_uv_bufs {
13074 set_palette_pred(ub.clone());
13075 }
13076 u.reconstruct(
13077 cpx,
13078 cpy,
13079 4,
13080 uv_predict_mode,
13081 angle_delta_uv,
13082 reach,
13083 &vec![0i32; 16],
13084 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
13085 None,
13086 smooth_neighbor_uv,
13087 );
13088 if let Some((_, _, vb)) = &intrabc_bufs {
13089 set_palette_pred(vb.clone());
13090 } else if let Some((_, vb)) = &palette_uv_bufs {
13091 set_palette_pred(vb.clone());
13092 }
13093 v.reconstruct(
13094 cpx,
13095 cpy,
13096 4,
13097 uv_predict_mode,
13098 angle_delta_uv,
13099 reach,
13100 &vec![0i32; 16],
13101 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
13102 None,
13103 smooth_neighbor_uv,
13104 );
13105 luma_grid = vec![0i32; 64];
13106 u_grid = vec![0i32; 16];
13107 v_grid = vec![0i32; 16];
13108 } else if resolved != 4 {
13109 let around = neighbours.around_mi(leaf_mi, 8);
13110 if let Some(buf) = &palette_y_buf {
13111 set_palette_pred(buf.clone());
13112 }
13113 luma_grid = read_plane(
13114 dec,
13115 cdfs,
13116 if intrabc_dv.is_some() {
13117 txbset_for_inter(8, reduced_tx_set)
13118 } else if reduced_tx_set {
13119 TxbSet::Luma8
13120 } else {
13121 TxbSet::Luma8Set1
13122 },
13123 scans.0,
13124 0,
13125 around[0],
13126 mode,
13127 mode,
13128 angle_delta_y,
13129 reach,
13130 y,
13131 px,
13132 py,
13133 8,
13134 TX8,
13135 base_q_idx,
13136 None,
13137 filter_intra,
13138 None,
13139 smooth_neighbor,
13140 )?;
13141 // `av1_get_tx_type` branches `PLANE_TYPE_UV` on `is_inter_block`, so
13142 // an intrabc block's chroma tx_type is the colocated LUMA transform's
13143 // coded type (lane-kf900 r6's own fix, `decode_block`'s line).
13144 if intrabc_dv.is_some() {
13145 INTRABC_CHROMA_TX.with(|c| c.set(Some(LUMA_TX_TYPE.with(std::cell::Cell::get))));
13146 }
13147 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
13148 if let Some((_, ub, _)) = &intrabc_bufs {
13149 set_palette_pred(ub.clone());
13150 } else if let Some((ub, _)) = &palette_uv_bufs {
13151 set_palette_pred(ub.clone());
13152 }
13153 u_grid = read_plane(
13154 dec,
13155 cdfs,
13156 TxbSet::Chroma4,
13157 scans.1,
13158 1,
13159 around[1],
13160 mode,
13161 uv_predict_mode,
13162 angle_delta_uv,
13163 reach,
13164 u,
13165 cpx,
13166 cpy,
13167 4,
13168 TX4,
13169 base_q_idx,
13170 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
13171 None,
13172 None,
13173 smooth_neighbor_uv,
13174 )?;
13175 if let Some((_, _, vb)) = &intrabc_bufs {
13176 set_palette_pred(vb.clone());
13177 } else if let Some((_, vb)) = &palette_uv_bufs {
13178 set_palette_pred(vb.clone());
13179 }
13180 v_grid = read_plane(
13181 dec,
13182 cdfs,
13183 TxbSet::Chroma4,
13184 scans.1,
13185 2,
13186 around[2],
13187 mode,
13188 uv_predict_mode,
13189 angle_delta_uv,
13190 reach,
13191 v,
13192 cpx,
13193 cpy,
13194 4,
13195 TX4,
13196 base_q_idx,
13197 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
13198 None,
13199 None,
13200 smooth_neighbor_uv,
13201 )?;
13202 // Disarm: `INTRABC_CHROMA_TX` is `Some` across exactly this block's
13203 // two chroma reads (`decode_block`'s own tail does the same) -- left
13204 // set, every later chroma block would inherit this luma tx_type,
13205 // which picks the scan and the inverse transform.
13206 INTRABC_CHROMA_TX.with(|c| c.set(None));
13207 } else {
13208 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
13209 // grid of 4x4 transform units, each predicted from the leaf's own
13210 // 8x8 `mode` and reading its own fresh context off the earlier
13211 // units in this same leaf (the same per-TU pattern `decode_block`'s
13212 // multi-TU branch runs at bigger blocks).
13213 luma_grid = vec![0i32; 64];
13214 for tu_row in 0..2 {
13215 for tu_col in 0..2 {
13216 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
13217 let tu_px = px + tu_col * 4;
13218 let tu_py = py + tu_row * 4;
13219 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
13220 if crate::encode::Reach::in_vert_ab() {
13221 VERT_AB_TX4_HITS.with(|c| c.set(c.get() + 1));
13222 }
13223 let tu_reach = tu_reach(
13224 8,
13225 8,
13226 tu_col * 4,
13227 tu_row * 4,
13228 4,
13229 reach,
13230 px,
13231 py,
13232 y.width,
13233 y.height,
13234 );
13235 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
13236 // Each 4x4 unit predicts from its own window of the block's
13237 // 8x8 colour-index map ([`decode_block`]'s per-TU slice at
13238 // 16x16 and up) -- the whole-block buffer would be taken by
13239 // the FIRST unit and indexed at the wrong stride.
13240 if let Some(buf) = &palette_y_buf {
13241 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
13242 let mut window = vec![0u16; 16];
13243 for row in 0..4 {
13244 let src = (tu_row * 4 + row) * 8 + tu_col * 4;
13245 window[row * 4..][..4].copy_from_slice(&buf[src..][..4]);
13246 }
13247 set_palette_pred(window);
13248 }
13249 let tu_grid = read_plane(
13250 dec,
13251 cdfs,
13252 if reduced_tx_set {
13253 TxbSet::Luma4
13254 } else {
13255 TxbSet::Luma4Set1
13256 },
13257 scans.1,
13258 0,
13259 tu_around,
13260 mode,
13261 mode,
13262 angle_delta_y,
13263 tu_reach,
13264 y,
13265 tu_px,
13266 tu_py,
13267 4,
13268 4,
13269 base_q_idx,
13270 None,
13271 filter_intra,
13272 Some(tu_skip_ctx),
13273 smooth_neighbor,
13274 )?;
13275 if crate::envflags::env_flag!("EC_AV1_TRACE") {
13276 eprintln!(
13277 "TRACE tu_bitpos mi=({},{}) tell={}",
13278 tu_mi.0,
13279 tu_mi.1,
13280 dec.debug_bitpos()
13281 );
13282 }
13283 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
13284 }
13285 }
13286 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
13287 let chroma_around = neighbours.around_mi(leaf_mi, 8);
13288 if let Some((ub, _)) = &palette_uv_bufs {
13289 set_palette_pred(ub.clone());
13290 }
13291 u_grid = read_plane(
13292 dec,
13293 cdfs,
13294 TxbSet::Chroma4,
13295 scans.1,
13296 1,
13297 chroma_around[1],
13298 mode,
13299 uv_predict_mode,
13300 angle_delta_uv,
13301 reach,
13302 u,
13303 cpx,
13304 cpy,
13305 4,
13306 TX4,
13307 base_q_idx,
13308 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
13309 None,
13310 None,
13311 smooth_neighbor_uv,
13312 )?;
13313 if let Some((_, vb)) = &palette_uv_bufs {
13314 set_palette_pred(vb.clone());
13315 }
13316 v_grid = read_plane(
13317 dec,
13318 cdfs,
13319 TxbSet::Chroma4,
13320 scans.1,
13321 2,
13322 chroma_around[2],
13323 mode,
13324 uv_predict_mode,
13325 angle_delta_uv,
13326 reach,
13327 v,
13328 cpx,
13329 cpy,
13330 4,
13331 TX4,
13332 base_q_idx,
13333 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
13334 None,
13335 None,
13336 smooth_neighbor_uv,
13337 )?;
13338 // `record_split_luma` expects a `record`-style `(r, c)` position in
13339 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
13340 // already in mi units, so calling it here double-scaled the
13341 // position. Plane 0 is already correct per-TU from the
13342 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
13343 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
13344 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
13345 // leaf's own 8x8 side over `MI`).
13346 let side_mi = 2;
13347 for cell in 0..side_mi {
13348 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
13349 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
13350 }
13351 let round_up_even = |n: usize| n.div_ceil(2) * 2;
13352 let bound_h = round_up_even(neighbours.mi_rows);
13353 let bound_w = round_up_even(neighbours.mi_cols);
13354 let u_state = neighbour_state(&u_grid);
13355 let v_state = neighbour_state(&v_grid);
13356 for cell in 0..side_mi {
13357 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
13358 neighbours.left[leaf_mi.0 + cell][1] = u_state;
13359 neighbours.left[leaf_mi.0 + cell][2] = v_state;
13360 }
13361 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
13362 neighbours.above[leaf_mi.1 + cell][1] = u_state;
13363 neighbours.above[leaf_mi.1 + cell][2] = v_state;
13364 }
13365 }
13366 // This leaf's own palette state into the mi-granular above/left bands
13367 // (sizes 0 when it used none, which is what clears a previous block's
13368 // palette out of the next block's ctx and colour cache).
13369 {
13370 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
13371 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
13372 }
13373 neighbours.fill_skip_grid(leaf_mi, 2, skip);
13374 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0);
13375 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
13376 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv);
13377 return Ok(mode);
13378 }
13379 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
13380 // This leaf's own palette state into the mi-granular above/left bands
13381 // (sizes 0 when it used none, which is what clears a previous block's
13382 // palette out of the next block's ctx and colour cache).
13383 {
13384 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
13385 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
13386 }
13387 INTER8_SKIP_BAND_HITS.with(|c| c.set(c.get() + 1));
13388 neighbours.fill_skip_grid(leaf_mi, 2, skip);
13389 // lane-kf900 r1: the leaf's own RESOLVED transform size, never the literal
13390 // block side. libaom calls `set_txfm_ctxs(mbmi->tx_size, ..., skip_txfm &&
13391 // is_inter_block(mbmi), xd)` (decodemv.c) -- for an INTRA block that skip
13392 // term is always 0, so a skipped 8x8 leaf whose `tx_depth` resolved to
13393 // TX_4X4 still publishes 4 to the next block's `get_tx_size_context`
13394 // (pred_common.h:342). Writing 8 here made the 8x16 strip below the leaf
13395 // read `tx_size_cat1` row 2 where libaom reads row 1 -- same alphabet,
13396 // wrong CDF row, so the msac range diverged mid-frame with no refusal
13397 // (class `wrong-alphabet-same-value`; the ReelB key frame at
13398 // -ss 900, first bad luma sample row 186 col 1803).
13399 neighbours.fill_lf_grid(leaf_mi, 2, resolved as u8, 0);
13400 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
13401 // The DV predictor of a LATER intrabc block is the ordinary `INTRA_FRAME`
13402 // MV stack over this grid (`av1_find_mv_refs`), so an 8x8 leaf has to
13403 // publish its own cells exactly like `decode_block` does.
13404 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv);
13405 Ok(mode)
13406}
13407
13408/// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf
13409/// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8`
13410/// bottom, where no partition symbol is read at all -- `decode_block` runs
13411/// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec
13412/// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always
13413/// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference`
13414/// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf
13415/// of the 2x2 4x4 group carries chroma syntax at all.
13416#[allow(clippy::too_many_arguments)]
13417fn read_intra_mode_sub8(
13418 dec: &mut SymbolDecoder,
13419 cdfs: &mut Cdfs,
13420 above_mode: usize,
13421 left_mode: usize,
13422 has_chroma: bool,
13423 enable_filter_intra: bool,
13424 // [`filter_intra_size_class_rect`] for the LEAF's own shape: 0 for a
13425 // `BLOCK_4X4` split leaf, 8/9 for a 4x8/8x4 rect leaf. Reading the flag
13426 // from the wrong row is the same VALUE with a different interval, so it
13427 // desyncs a block or two later, not here (class `wrong-alphabet-same-value`).
13428 fi_class: usize,
13429 skip_ctx: usize,
13430 allow_intrabc: bool,
13431 mi_r: usize,
13432 mi_c: usize,
13433) -> Result<(bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option<usize>)> {
13434 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
13435 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
13436 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sub8 rng={}", dec.debug_state().0);
13437 }
13438 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
13439 if trace {
13440 eprintln!("TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}", skip as i32, dec.debug_state().0);
13441 }
13442 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
13443 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip);
13444 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip);
13445 if allow_intrabc {
13446 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
13447 if use_intrabc {
13448 return Err(unsupported(
13449 "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)",
13450 ));
13451 }
13452 }
13453 let above_ctx = INTRA_MODE_CTX[above_mode];
13454 let left_ctx = INTRA_MODE_CTX[left_mode];
13455 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
13456 if trace {
13457 eprintln!("TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
13458 }
13459 // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/
13460 // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`,
13461 // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta
13462 // symbol. Reading one consumed a symbol the encoder never wrote and
13463 // desynced the tile at the very next element.
13464 let angle_delta_y = 0;
13465 let chroma = if has_chroma {
13466 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
13467 if trace {
13468 eprintln!("TRACE sub8 uv_mode value={uv_mode} rng={}", dec.debug_state().0);
13469 }
13470 if (9..=12).contains(&uv_mode) {
13471 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
13472 }
13473 let alpha = if uv_mode == UV_CFL_PRED {
13474 Some(read_cfl_alphas(dec, cdfs))
13475 } else {
13476 None
13477 };
13478 if (V_PRED..=D67_PRED).contains(&uv_mode) {
13479 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
13480 }
13481 // See the luma comment above: no angle delta below 8x8.
13482 let angle_delta_uv = 0;
13483 Some((uv_mode, angle_delta_uv, alpha))
13484 } else {
13485 None
13486 };
13487 let mut filter_intra = None;
13488 if mode == DC_PRED && enable_filter_intra {
13489 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0;
13490 if trace {
13491 eprintln!("TRACE sub8 use_filter_intra value={}", use_filter_intra as i32);
13492 }
13493 if use_filter_intra {
13494 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
13495 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
13496 filter_intra = Some(fi_mode);
13497 }
13498 }
13499 Ok((skip, mode, angle_delta_y, chroma, filter_intra))
13500}
13501
13502/// Decodes a `PARTITION_SPLIT` of one 8x8 block into four `BLOCK_4X4` leaves
13503/// (spec `decode_partition`'s recursion bottom), sharing [`decode_leaf8`]'s
13504/// own signature so its caller's `prev_leaf`/`above_mode`/`left_mode`
13505/// bookkeeping needs no change. Each leaf reads its own luma mode info,
13506/// neighboured off the *previously decoded leaf in this same group* on
13507/// whichever axis is adjacent (mirroring [`decode_leaf8`]'s own `prev_leaf`
13508/// pattern, one level deeper); chroma is read and reconstructed exactly
13509/// once, on the last (bottom-right) leaf, at the whole 8x8 group's own 4x4
13510/// chroma unit -- [`read_intra_mode_sub8`]'s doc has the `is_chroma_reference`
13511/// derivation.
13512#[allow(clippy::too_many_arguments)]
13513fn decode_leaf_split4(
13514 dec: &mut SymbolDecoder,
13515 cdfs: &mut Cdfs,
13516 neighbours: &mut Neighbours,
13517 outer_at: (usize, usize),
13518 leaf_mi: (usize, usize),
13519 scan4: &[u16],
13520 prev_leaf: Option<((usize, usize), usize)>,
13521 y: &mut PlaneBuf,
13522 u: &mut PlaneBuf,
13523 v: &mut PlaneBuf,
13524 base_q_idx: u8,
13525 enable_filter_intra: bool,
13526 allow_intrabc: bool,
13527 reduced_tx_set: bool,
13528 // Returns `(below_mode, right_mode)`: the mode a neighbour BELOW this 8x8
13529 // group sees (its bottom-left 4x4, libaom reads mi(row-1, col)) and the
13530 // one a neighbour to its RIGHT sees (its top-right 4x4, mi(row, col-1)).
13531) -> Result<(usize, usize)> {
13532 SUB8_SPLIT_HITS.with(|c| c.set(c.get() + 1));
13533 let (r, c) = outer_at;
13534 let mut above_mode = neighbours.above_mode[c];
13535 let mut left_mode = neighbours.left_mode[r];
13536 if let Some(((pr, pc), pmode)) = prev_leaf {
13537 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
13538 above_mode = pmode;
13539 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
13540 left_mode = pmode;
13541 }
13542 }
13543 // See `decode_leaf8`'s own `smooth_neighbor_uv`: the chroma edge-filter
13544 // type is the chroma neighbours' `uv_mode`, mi-exact where recorded.
13545 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
13546 let mut leaf_modes = [0usize; 4];
13547 let mut leaf_skips = [false; 4];
13548 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
13549 for i in 0..4usize {
13550 let (dr, dc) = (i / 2, i % 2);
13551 let lmi = (leaf_mi.0 + dr, leaf_mi.1 + dc);
13552 // Neighbour modes at real mi granularity: inside the group the
13553 // sibling leaf, outside it the split-leaf map when the adjacent mi
13554 // was itself a 4x4 leaf, else the coarse 16x16 slot (see
13555 // `sub8_mode_col`'s doc).
13556 let leaf_above = if dr == 0 {
13557 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
13558 } else {
13559 leaf_modes[i - 2]
13560 };
13561 let leaf_left = if dc == 0 {
13562 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
13563 } else {
13564 leaf_modes[i - 1]
13565 };
13566 let has_chroma = i == 3;
13567 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
13568 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
13569 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
13570 filter_intra_size_class(4).expect("BLOCK_4X4 has its own filter_intra row"),
13571 skip_ctx, allow_intrabc, lmi.0, lmi.1,
13572 )?;
13573 leaf_modes[i] = mode;
13574 leaf_skips[i] = skip;
13575 neighbours.record_mode_mi(lmi.0, lmi.1, 1, 1, mode);
13576 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
13577 if smooth_neighbor {
13578 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
13579 }
13580 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
13581 let reach = Reach::of(4, px, py, y.width, y.height);
13582 if skip {
13583 y.reconstruct(px, py, 4, mode, angle_delta_y, reach, &vec![0i32; 16], None, filter_intra, smooth_neighbor);
13584 neighbours.record_mi_luma(lmi, 4, &vec![0i32; 16]);
13585 } else {
13586 let tu_around = neighbours.around_mi(lmi, 4)[0];
13587 // A `BLOCK_4X4` leaf's luma TU *is* the whole block, so libaom's
13588 // `get_txb_ctx` takes its `plane_bsize == txsize_to_bsize[tx_size]`
13589 // branch: `txb_skip_ctx = 0`, never the neighbour-magnitude table
13590 // (`txb_common.h:400`). Reading the table here decoded `all_zero`
13591 // off the wrong CDF on the very first leaf and desynced the tile.
13592 let tu_grid = read_plane(
13593 dec,
13594 cdfs,
13595 if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 },
13596 scan4,
13597 0,
13598 tu_around,
13599 mode,
13600 mode,
13601 angle_delta_y,
13602 reach,
13603 y,
13604 px,
13605 py,
13606 4,
13607 4,
13608 base_q_idx,
13609 None,
13610 filter_intra,
13611 None,
13612 smooth_neighbor,
13613 )?;
13614 neighbours.record_mi_luma(lmi, 4, &tu_grid);
13615 }
13616 neighbours.fill_skip_grid(lmi, 1, skip);
13617 neighbours.fill_lf_grid(lmi, 1, 4, 0);
13618 if has_chroma {
13619 last_uv = chroma;
13620 }
13621 }
13622 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
13623 let (cpx, cpy) = (gpx / 2, gpy / 2);
13624 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height);
13625 let (uv_mode, angle_delta_uv, alpha) =
13626 last_uv.expect("i==3 always sets has_chroma, so chroma is always Some");
13627 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
13628 neighbours.above_uv_mode[c] = uv_predict_mode;
13629 neighbours.left_uv_mode[r] = uv_predict_mode;
13630 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
13631 let (u_grid, v_grid): (Vec<i32>, Vec<i32>) = if leaf_skips[3] {
13632 // A skipped chroma block still gets its CfL contribution: libaom's
13633 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
13634 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
13635 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
13636 // added -- `skip_txfm` only drops the residual, never the alpha.
13637 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
13638 // merge keeps one fix and feeds both lanes' counters so neither of
13639 // their gates goes vacuous.
13640 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
13641 if alpha.is_some() {
13642 CHROMA_SKIP_CFL_HITS.with(|h| h.set(h.get() + 1));
13643 SKIP_CFL_HITS.with(|c| c.set(c.get() + 1));
13644 }
13645 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);
13646 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);
13647 (vec![0i32; 16], vec![0i32; 16])
13648 } else {
13649 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
13650 let chroma_around = neighbours.around_mi(leaf_mi, 8);
13651 let ug = read_plane(
13652 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
13653 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
13654 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv,
13655 )?;
13656 let vg = read_plane(
13657 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
13658 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
13659 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv,
13660 )?;
13661 (ug, vg)
13662 };
13663 // Chroma neighbour bookkeeping for the whole 8x8 group -- mirrors
13664 // [`decode_leaf8`]'s own tx4-chroma section (`record_split_luma`'s
13665 // rescaling is wrong for an already-mi-unit position, so this inlines
13666 // its tail directly at `leaf_mi`, side_mi=2), EXCEPT for the partition
13667 // context value itself. Unlike `decode_leaf8`'s TX4 branch (still one
13668 // `BLOCK_8X8`, `PARTITION_NONE`, transform depth only), this group is
13669 // genuinely four `BLOCK_4X4` blocks (`PARTITION_SPLIT` at the 8x8
13670 // level, libaom `decode_partition`'s `bsize2`/`subsize` recursion
13671 // bottom). libaom's `update_ext_partition_context` writes
13672 // `partition_context_lookup[subsize]` at the 8x8 slot -- `{30,30}` for
13673 // `BLOCK_8X8` (bit0=0, what `decode_leaf8` already reproduces via
13674 // side_mi=8) but `{31,31}` for `BLOCK_4X4` (bit0=1) here, and
13675 // `partition_ctx_mi`'s `left_side_mi[mi_r]*2 <= side` needs
13676 // `left_side_mi <= 4` to read that bit as 1. Leaving this at 8 (this
13677 // round's bug) makes the very next sibling 8x8's `partition_w8` read
13678 // with the wrong context and desync immediately.
13679 let side_mi = 2;
13680 for cell in 0..side_mi {
13681 neighbours.left_side_mi[leaf_mi.0 + cell] = 4;
13682 neighbours.above_side_mi[leaf_mi.1 + cell] = 4;
13683 }
13684 let round_up_even = |n: usize| n.div_ceil(2) * 2;
13685 let bound_h = round_up_even(neighbours.mi_rows);
13686 let bound_w = round_up_even(neighbours.mi_cols);
13687 let u_state = neighbour_state(&u_grid);
13688 let v_state = neighbour_state(&v_grid);
13689 for cell in 0..side_mi {
13690 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
13691 neighbours.left[leaf_mi.0 + cell][1] = u_state;
13692 neighbours.left[leaf_mi.0 + cell][2] = v_state;
13693 }
13694 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
13695 neighbours.above[leaf_mi.1 + cell][1] = u_state;
13696 neighbours.above[leaf_mi.1 + cell][2] = v_state;
13697 }
13698 }
13699 Ok((leaf_modes[2], leaf_modes[1]))
13700}
13701
13702/// Decodes a `PARTITION_VERT`/`PARTITION_HORZ` of one 8x8 block into two
13703/// `BLOCK_4X8`/`BLOCK_8X4` leaves (lane-tx4x8), the last partition shape
13704/// below 8x8 this decoder refused. Mirrors [`decode_leaf_split4`] element for
13705/// element -- same mode reads ([`read_intra_mode_sub8`]: no angle delta, no
13706/// tx-depth symbol below 8x8), same "chroma once, on the last sub-block, at
13707/// the whole 8x8 group's 4x4 unit" rule (`is_chroma_reference` is false for
13708/// every sub-block one mi wide or high but the last) -- differing only where
13709/// the shape does:
13710///
13711/// * the transform is a true `TX_4X8`/`TX_8X4`
13712/// ([`dequant_and_inverse_typed_wh`], whose `abs(rect_type) == 1` scale and
13713/// `av1_inv_txfm_shift_ls` row already cover this size pair);
13714/// * the CDF set is [`TxbSet::LumaRect4x8`] (`get_txsize_entropy_ctx` squares
13715/// up to `TX_8X8`) with a 32-position `eob_pt` and the `TX_4X4` `tx_type`
13716/// row -- see that variant's doc comment;
13717/// * the scan is [`SCAN_4X8`]/[`SCAN_8X4`], or their `mrow`/`mcol` siblings
13718/// ([`class_scan_table_wh`]) when the coded `tx_type` is `V_DCT`/`H_DCT`;
13719/// * `Reach` comes from libaom's own `has_tr_4x8`/`has_bl_8x4` rows
13720/// ([`Reach::of_rect`]);
13721/// * `update_partition_context` writes `partition_context_lookup[BLOCK_4X8]`
13722/// = `{31, 30}` (width 4 above, height 8 left), not the `{31, 31}` a
13723/// `BLOCK_4X4` split writes.
13724///
13725/// Filter intra on one of these leaves is decoded (lane-fi8 r1): the flag is
13726/// read from `BLOCK_4X8`/`BLOCK_8X4`'s own `cdf::FILTER_INTRA` row (classes
13727/// 8/9, NOT `BLOCK_4X4`'s), the predictor is [`crate::intra::predict_filter_intra`]
13728/// over the leaf's true `bw`x`bh` -- per 4x4 transform unit, with that unit's
13729/// own edge, when `tx_depth` splits it -- and the coded `tx_type` row is
13730/// [`fi_tx_row`]'s `fimode_to_intradir`, not the block's raw `DC_PRED`.
13731#[allow(clippy::too_many_arguments)]
13732fn decode_leaf_rect8(
13733 dec: &mut SymbolDecoder,
13734 cdfs: &mut Cdfs,
13735 neighbours: &mut Neighbours,
13736 outer_at: (usize, usize),
13737 leaf_mi: (usize, usize),
13738 vert: bool,
13739 scan4: &[u16],
13740 y: &mut PlaneBuf,
13741 u: &mut PlaneBuf,
13742 v: &mut PlaneBuf,
13743 base_q_idx: u8,
13744 enable_filter_intra: bool,
13745 allow_intrabc: bool,
13746 tx_select: bool,
13747 reduced_tx_set: bool,
13748) -> Result<(usize, usize)> {
13749 let (r, c) = outer_at;
13750 // lane-modectx r1: availability-correct fallback pair (see
13751 // `modes_above_left`), not the raw coarse bands.
13752 let (above_mode, left_mode) = neighbours.modes_above_left(r, c);
13753 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
13754 let (bw, bh) = if vert { (4, 8) } else { (8, 4) };
13755 let (w_mi, h_mi) = (bw / MI, bh / MI);
13756 let scan: &[u16] = if vert { &SCAN_4X8 } else { &SCAN_8X4 };
13757 let mut leaf_modes = [0usize; 2];
13758 let mut leaf_skips = [false; 2];
13759 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
13760 for i in 0..2usize {
13761 let lmi = if vert {
13762 (leaf_mi.0, leaf_mi.1 + i)
13763 } else {
13764 (leaf_mi.0 + i, leaf_mi.1)
13765 };
13766 // Inside the pair the sibling is the neighbour on the split axis;
13767 // outside it the mi-granular map, else the coarse 16x16 slot.
13768 let leaf_above = if !vert && i == 1 {
13769 leaf_modes[0]
13770 } else {
13771 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
13772 };
13773 let leaf_left = if vert && i == 1 {
13774 leaf_modes[0]
13775 } else {
13776 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
13777 };
13778 let has_chroma = i == 1;
13779 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
13780 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
13781 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
13782 filter_intra_size_class_rect(bw, bh)
13783 .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize"),
13784 skip_ctx, allow_intrabc, lmi.0, lmi.1,
13785 )?;
13786 if filter_intra.is_some() {
13787 // lane-fi8 r1: `predict_filter_intra` walks its 4x2 patches over
13788 // a true `bw`x`bh` block, so a 4x8/8x4 leaf predicts through the
13789 // same `reconstruct_rect`/`reconstruct` calls below -- and under
13790 // a split transform, per 4x4 unit with that unit's own edge,
13791 // which is exactly what the depth-1 loop already does.
13792 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
13793 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.set(c.get() + 1));
13794 }
13795 // `TxMode::Select`'s `tx_depth` (spec 5.11.16) exists at a 4x8/8x4
13796 // leaf too, and is read for every intra block, skipped or not. Its
13797 // category is libaom's `bsize_to_tx_size_cat(BLOCK_4X8) == 0` --
13798 // `sub_tx_size_map[TX_4X8] == TX_4X4` is a single step, so it is the
13799 // same 2-symbol `tx_size_cat0` an 8x8 uses, not the 3-symbol
13800 // `tx_size_cat2` the 32x16 strips read -- with the rect context
13801 // (`get_tx_size_context`'s `max_tx_wide`/`max_tx_high` = bw/bh).
13802 // Missing this read consumed one symbol fewer than the encoder wrote
13803 // and desynced the tile at the very first rect leaf (class
13804 // `symbol-consumption-gap`).
13805 let depth = if tx_select {
13806 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band
13807 // read every other rect reader now does -- a no-op on a key frame.
13808 let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {
13809 tx_size_context_txfm_rect(neighbours, lmi, bw, bh)
13810 } else {
13811 tx_size_context_rect(neighbours, lmi, bw, bh)
13812 };
13813 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
13814 } else {
13815 0
13816 };
13817 if depth != 0 {
13818 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
13819 RECT8_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
13820 }
13821 leaf_modes[i] = mode;
13822 leaf_skips[i] = skip;
13823 neighbours.record_mode_mi(lmi.0, lmi.1, w_mi, h_mi, mode);
13824 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
13825 if smooth_neighbor {
13826 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
13827 }
13828 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
13829 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
13830 // `sub_tx_size_map[TX_4X8] == TX_4X4`: depth 1 splits the leaf into
13831 // two 4x4 transform units along its long axis, each predicted from
13832 // the previous unit's reconstruction and reading its own `txb_skip`
13833 // context -- `decode_leaf8`'s own depth-1 loop, two units instead of
13834 // four. The per-TU path writes its own neighbour state, so the
13835 // block-level write below is skipped for it.
13836 let split = depth != 0;
13837 if split {
13838 let mut done = 0usize;
13839 for tu in 0..2usize {
13840 let tu_mi = if vert {
13841 (lmi.0 + tu, lmi.1)
13842 } else {
13843 (lmi.0, lmi.1 + tu)
13844 };
13845 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);
13846 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
13847 // Same per-TU rule as every other split-transform site
13848 // (lane-palette2 r12): a transform unit inside a block is not
13849 // a block at that position, so its reach comes from the
13850 // block's own row, offset by the unit's position.
13851 let tu_reach = tu_reach(
13852 bw,
13853 bh,
13854 tu_px - px,
13855 tu_py - py,
13856 4,
13857 reach,
13858 px,
13859 py,
13860 y.width,
13861 y.height,
13862 );
13863 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
13864 if skip {
13865 // A skipped leaf still predicts per transform unit: the
13866 // second 4x4 takes its above/left edge from the first
13867 // one's reconstruction, which is NOT what a single 4x8
13868 // prediction of the same mode produces.
13869 let zeros = vec![0i32; 16];
13870 y.reconstruct(
13871 tu_px, tu_py, 4, mode, angle_delta_y, tu_reach, &zeros, None,
13872 filter_intra, smooth_neighbor,
13873 );
13874 neighbours.record_mi_luma(tu_mi, 4, &zeros);
13875 continue;
13876 }
13877 let tu_grid = read_plane(
13878 dec,
13879 cdfs,
13880 if reduced_tx_set {
13881 TxbSet::Luma4
13882 } else {
13883 TxbSet::Luma4Set1
13884 },
13885 scan4,
13886 0,
13887 tu_around,
13888 mode,
13889 mode,
13890 angle_delta_y,
13891 tu_reach,
13892 y,
13893 tu_px,
13894 tu_py,
13895 4,
13896 TX4,
13897 base_q_idx,
13898 None,
13899 filter_intra,
13900 Some(tu_skip_ctx),
13901 smooth_neighbor,
13902 )?;
13903 if tu_grid.iter().any(|&l| l != 0) {
13904 done += 1;
13905 }
13906 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
13907 }
13908 if done > 0 {
13909 if vert {
13910 TX4X8_CODED_HITS.with(|h| h.set(h.get() + 1));
13911 } else {
13912 TX8X4_CODED_HITS.with(|h| h.set(h.get() + 1));
13913 }
13914 }
13915 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
13916 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, 4, 4, 0);
13917 if has_chroma {
13918 last_uv = chroma;
13919 }
13920 continue;
13921 }
13922 let grid = if skip {
13923 let zeros = vec![0i32; bw * bh];
13924 y.reconstruct_rect(
13925 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
13926 smooth_neighbor,
13927 );
13928 zeros
13929 } else {
13930 // `plane_bsize == txsize_to_bsize[tx_size]` here too (the leaf's
13931 // luma TU *is* the leaf), so `get_txb_ctx` fixes `txb_skip_ctx`
13932 // at 0 -- see `decode_leaf_split4`'s own note.
13933 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
13934 let set = if reduced_tx_set {
13935 TxbSet::LumaRect4x8
13936 } else {
13937 TxbSet::LumaRect4x8Set1
13938 };
13939 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
13940 let (levels, tx_type) = read_coeffs_rect(
13941 dec,
13942 &mut coding,
13943 scan,
13944 bw,
13945 bh,
13946 0,
13947 dc_sign_ctx(around.2),
13948 TxType::DctDct,
13949 )?;
13950 if levels.iter().any(|&l| l != 0) {
13951 if vert {
13952 TX4X8_CODED_HITS.with(|h| h.set(h.get() + 1));
13953 } else {
13954 TX8X4_CODED_HITS.with(|h| h.set(h.get() + 1));
13955 }
13956 }
13957 let residual = dequant_and_inverse_typed_wh(
13958 &levels,
13959 bw,
13960 bh,
13961 crate::decode::bit_depth(),
13962 CURRENT_Q_IDX.with(|q| q.get()),
13963 plane_q_delta(0).0,
13964 plane_q_delta(0).1,
13965 tx_type,
13966 );
13967 y.reconstruct_rect(
13968 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
13969 smooth_neighbor,
13970 );
13971 levels
13972 };
13973 // Plane 0's per-TU coefficient context over this leaf's own mi span
13974 // (`record_mi_luma`'s rect twin -- the chroma planes are written once
13975 // for the whole 8x8 group below).
13976 let state = neighbour_state(&grid);
13977 for cell in 0..h_mi {
13978 if lmi.0 + cell < neighbours.mi_rows {
13979 neighbours.left[lmi.0 + cell][0] = state;
13980 }
13981 }
13982 for cell in 0..w_mi {
13983 if lmi.1 + cell < neighbours.mi_cols {
13984 neighbours.above[lmi.1 + cell][0] = state;
13985 }
13986 }
13987 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
13988 let (tx_w, tx_h) = if split { (4, 4) } else { (bw as u8, bh as u8) };
13989 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, tx_w, tx_h, 0);
13990 if has_chroma {
13991 last_uv = chroma;
13992 }
13993 }
13994 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
13995 let (cpx, cpy) = (gpx / 2, gpy / 2);
13996 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height);
13997 let (uv_mode, angle_delta_uv, alpha) =
13998 last_uv.expect("i==1 always sets has_chroma, so chroma is always Some");
13999 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
14000 neighbours.above_uv_mode[c] = uv_predict_mode;
14001 neighbours.left_uv_mode[r] = uv_predict_mode;
14002 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
14003 let (u_grid, v_grid): (Vec<i32>, Vec<i32>) = if leaf_skips[1] {
14004 // A skipped chroma block still gets its CfL contribution: libaom's
14005 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
14006 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
14007 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
14008 // added -- `skip_txfm` only drops the residual, never the alpha.
14009 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
14010 // merge keeps one fix and feeds both lanes' counters so neither of
14011 // their gates goes vacuous.
14012 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
14013 if alpha.is_some() {
14014 CHROMA_SKIP_CFL_HITS.with(|h| h.set(h.get() + 1));
14015 SKIP_CFL_HITS.with(|c| c.set(c.get() + 1));
14016 }
14017 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);
14018 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);
14019 (vec![0i32; 16], vec![0i32; 16])
14020 } else {
14021 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
14022 let chroma_around = neighbours.around_mi(leaf_mi, 8);
14023 let ug = read_plane(
14024 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
14025 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
14026 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv,
14027 )?;
14028 let vg = read_plane(
14029 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
14030 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
14031 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv,
14032 )?;
14033 (ug, vg)
14034 };
14035 // `update_partition_context` at the 8x8 level writes
14036 // `partition_context_lookup[subsize]` over the whole 8x8 span: BLOCK_4X8
14037 // is `{31, 30}` (bit0 set on the above half only), BLOCK_8X4 `{30, 31}`
14038 // -- the mirror of `decode_leaf_split4`'s `{31, 31}`, which
14039 // `partition_ctx_mi` reads back off these side values.
14040 for cell in 0..2 {
14041 neighbours.above_side_mi[leaf_mi.1 + cell] = bw;
14042 neighbours.left_side_mi[leaf_mi.0 + cell] = bh;
14043 }
14044 let round_up_even = |n: usize| n.div_ceil(2) * 2;
14045 let bound_h = round_up_even(neighbours.mi_rows);
14046 let bound_w = round_up_even(neighbours.mi_cols);
14047 let u_state = neighbour_state(&u_grid);
14048 let v_state = neighbour_state(&v_grid);
14049 for cell in 0..2usize {
14050 if cell < 2usize.min(bound_h.saturating_sub(leaf_mi.0)) {
14051 neighbours.left[leaf_mi.0 + cell][1] = u_state;
14052 neighbours.left[leaf_mi.0 + cell][2] = v_state;
14053 }
14054 if cell < 2usize.min(bound_w.saturating_sub(leaf_mi.1)) {
14055 neighbours.above[leaf_mi.1 + cell][1] = u_state;
14056 neighbours.above[leaf_mi.1 + cell][2] = v_state;
14057 }
14058 }
14059 // `(below_mode, right_mode)`: the sub-block a neighbour below sees is the
14060 // bottom one (the second under HORZ, the left one under VERT), the one a
14061 // neighbour to the right sees is the top-right (the second under VERT).
14062 Ok(if vert {
14063 (leaf_modes[0], leaf_modes[1])
14064 } else {
14065 (leaf_modes[1], leaf_modes[0])
14066 })
14067}
14068
14069/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
14070/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
14071/// (mod 8) reuse the same table.
14072const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
14073 [(-1, 1), (-2, 2)],
14074 [(0, 1), (-1, 2)],
14075 [(0, 1), (0, 2)],
14076 [(0, 1), (1, 2)],
14077 [(1, 1), (2, 2)],
14078 [(1, 0), (2, 1)],
14079 [(1, 0), (2, 0)],
14080 [(1, 0), (2, -1)],
14081];
14082/// A neighbour tap outside the frame's true extent -- `constrain` reads this
14083/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
14084const CDEF_VERY_LARGE: i32 = 0x4000;
14085const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
14086const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
14087
14088fn cdef_msb(x: i32) -> i32 {
14089 31 - x.leading_zeros() as i32
14090}
14091
14092/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
14093/// centre sample a filter tap is allowed to contribute.
14094fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
14095 if threshold == 0 {
14096 return 0;
14097 }
14098 cdef_constrain_shifted(diff, threshold, cdef_constrain_shift(threshold, damping))
14099}
14100
14101/// `constrain`'s damping shift: a function of the block's threshold and
14102/// damping alone, so the filter loop computes it once per block instead of
14103/// the `leading_zeros` + branch it used to do twice per tap read.
14104fn cdef_constrain_shift(threshold: i32, damping: i32) -> i32 {
14105 (damping - cdef_msb(threshold)).max(0)
14106}
14107
14108/// [`cdef_constrain`]'s body with the shift already resolved; `threshold` is
14109/// non-zero on every call (the caller only filters when its strength is).
14110fn cdef_constrain_shifted(diff: i32, threshold: i32, shift: i32) -> i32 {
14111 let a = diff.abs();
14112 diff.signum() * (threshold - (a >> shift)).clamp(0, a)
14113}
14114
14115/// The widest `CDEF_DIRECTIONS` offset in either axis: every tap a block reads
14116/// lies inside its own samples grown by this much.
14117const CDEF_BORDER: usize = 2;
14118
14119/// Copies one block's whole CDEF footprint -- its `bh` x `bw` samples plus the
14120/// [`CDEF_BORDER`] tap ring -- out of the *unfiltered* plane into `buf` (row
14121/// stride `bw + 2 * CDEF_BORDER`), so the direction search and the tap loops
14122/// index a small contiguous window instead of re-deriving the frame-bounds
14123/// test on every one of a pixel's ~17 tap reads. Out-of-frame positions get
14124/// `CDEF_VERY_LARGE`, exactly as the per-sample closure did.
14125fn cdef_gather(
14126 src: &[u16],
14127 stride: usize,
14128 true_w: usize,
14129 true_h: usize,
14130 ox: usize,
14131 oy: usize,
14132 bw: usize,
14133 bh: usize,
14134 buf: &mut [i32],
14135) {
14136 let bstride = bw + 2 * CDEF_BORDER;
14137 let rows = bh + 2 * CDEF_BORDER;
14138 if oy >= CDEF_BORDER
14139 && ox >= CDEF_BORDER
14140 && oy + bh + CDEF_BORDER <= true_h
14141 && ox + bw + CDEF_BORDER <= true_w
14142 {
14143 // Interior block: every tap is inside the frame, so the whole window
14144 // is `rows` contiguous runs.
14145 for r in 0..rows {
14146 let s0 = (oy - CDEF_BORDER + r) * stride + (ox - CDEF_BORDER);
14147 let src_row = &src[s0..s0 + bstride];
14148 let dst_row = &mut buf[r * bstride..r * bstride + bstride];
14149 for (d, &v) in dst_row.iter_mut().zip(src_row) {
14150 *d = i32::from(v);
14151 }
14152 }
14153 return;
14154 }
14155 for r in 0..rows {
14156 let ny = oy as isize + r as isize - CDEF_BORDER as isize;
14157 for c in 0..bstride {
14158 let nx = ox as isize + c as isize - CDEF_BORDER as isize;
14159 buf[r * bstride + c] =
14160 if ny < 0 || nx < 0 || ny as usize >= true_h || nx as usize >= true_w {
14161 CDEF_VERY_LARGE
14162 } else {
14163 i32::from(src[ny as usize * stride + nx as usize])
14164 };
14165 }
14166 }
14167}
14168
14169/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
14170/// direction of an 8x8 luma window and the variance gap between it and its
14171/// orthogonal, `sample(row, col)` reading that window's own pixels.
14172fn cdef_find_dir(coeff_shift: i32, sample: impl Fn(usize, usize) -> i32) -> (usize, i32) {
14173 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
14174 let mut partial = [[0i64; 15]; 8];
14175 for i in 0..8i64 {
14176 for j in 0..8i64 {
14177 // libaom `cdef_find_dir_c`: normalise to an 8-bit sample before
14178 // accumulating, same as `constrain`'s threshold shift below.
14179 let x = i64::from(sample(i as usize, j as usize) >> coeff_shift) - 128;
14180 partial[0][(i + j) as usize] += x;
14181 partial[1][(i + j / 2) as usize] += x;
14182 partial[2][i as usize] += x;
14183 partial[3][(3 + i - j / 2) as usize] += x;
14184 partial[4][(7 + i - j) as usize] += x;
14185 partial[5][(3 - i / 2 + j) as usize] += x;
14186 partial[6][j as usize] += x;
14187 partial[7][(i / 2 + j) as usize] += x;
14188 }
14189 }
14190 let mut cost = [0i64; 8];
14191 for i in 0..8usize {
14192 cost[2] += partial[2][i] * partial[2][i];
14193 cost[6] += partial[6][i] * partial[6][i];
14194 }
14195 cost[2] *= DIV_TABLE[8];
14196 cost[6] *= DIV_TABLE[8];
14197 for i in 0..7usize {
14198 cost[0] += (partial[0][i] * partial[0][i] + partial[0][14 - i] * partial[0][14 - i])
14199 * DIV_TABLE[i + 1];
14200 cost[4] += (partial[4][i] * partial[4][i] + partial[4][14 - i] * partial[4][14 - i])
14201 * DIV_TABLE[i + 1];
14202 }
14203 cost[0] += partial[0][7] * partial[0][7] * DIV_TABLE[8];
14204 cost[4] += partial[4][7] * partial[4][7] * DIV_TABLE[8];
14205 for i in (1..8).step_by(2) {
14206 for j in 0..5usize {
14207 cost[i] += partial[i][3 + j] * partial[i][3 + j];
14208 }
14209 cost[i] *= DIV_TABLE[8];
14210 for j in 0..3usize {
14211 cost[i] += (partial[i][j] * partial[i][j] + partial[i][10 - j] * partial[i][10 - j])
14212 * DIV_TABLE[2 * j + 2];
14213 }
14214 }
14215 let mut best_cost = 0i64;
14216 let mut best_dir = 0usize;
14217 for (i, &c) in cost.iter().enumerate() {
14218 if c > best_cost {
14219 best_cost = c;
14220 best_dir = i;
14221 }
14222 }
14223 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
14224 (best_dir, var as i32)
14225}
14226
14227/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
14228/// (high variance gap) gets more deringing than a flat or non-directional
14229/// one, only ever applied to the luma primary strength.
14230fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
14231 if var == 0 {
14232 return 0;
14233 }
14234 let i = if var >> 6 != 0 {
14235 cdef_msb(var >> 6).min(12)
14236 } else {
14237 0
14238 };
14239 (strength * (4 + i) + 8) >> 4
14240}
14241
14242/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
14243/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
14244/// previously-filtered neighbour must never feed this block's own sum).
14245#[allow(clippy::too_many_arguments)]
14246#[allow(unsafe_code)]
14247fn cdef_filter_block(
14248 src: &[i32],
14249 dst: &mut PlaneBuf,
14250 ox: usize,
14251 oy: usize,
14252 bw: usize,
14253 bh: usize,
14254 pri_strength: i32,
14255 sec_strength: i32,
14256 dir: usize,
14257 pri_damping: i32,
14258 sec_damping: i32,
14259 enable_primary: bool,
14260 enable_secondary: bool,
14261 coeff_shift: i32,
14262) {
14263 let (stride, smax) = (dst.width, sample_max());
14264 #[cfg(target_arch = "x86_64")]
14265 if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 && (bw == 4 || bw == 8) && bh % 2 == 0
14266 {
14267 // SAFETY: reached only when the CPU reports avx2; the kernel reads
14268 // `src`'s whole (bw + 4) x (bh + 4) window and writes exactly the
14269 // `bh` runs of `bw` samples the scalar form writes.
14270 unsafe {
14271 cdef_simd::filter_block_avx2(
14272 src,
14273 &mut dst.data,
14274 stride,
14275 ox,
14276 oy,
14277 bw,
14278 bh,
14279 pri_strength,
14280 sec_strength,
14281 dir,
14282 pri_damping,
14283 sec_damping,
14284 enable_primary,
14285 enable_secondary,
14286 coeff_shift,
14287 smax,
14288 )
14289 };
14290 return;
14291 }
14292 cdef_filter_block_scalar(
14293 src,
14294 &mut dst.data,
14295 stride,
14296 ox,
14297 oy,
14298 bw,
14299 bh,
14300 pri_strength,
14301 sec_strength,
14302 dir,
14303 pri_damping,
14304 sec_damping,
14305 enable_primary,
14306 enable_secondary,
14307 coeff_shift,
14308 smax,
14309 );
14310}
14311
14312/// [`cdef_filter_block`]'s scalar reference: spec 7.15.3 sample by sample,
14313/// the form every non-AVX2 build decodes through and the one
14314/// `cdef_simd_kernel_matches_the_scalar_filter` checks the kernel against.
14315#[allow(clippy::too_many_arguments)]
14316fn cdef_filter_block_scalar(
14317 src: &[i32],
14318 dst: &mut [u16],
14319 stride: usize,
14320 ox: usize,
14321 oy: usize,
14322 bw: usize,
14323 bh: usize,
14324 pri_strength: i32,
14325 sec_strength: i32,
14326 dir: usize,
14327 pri_damping: i32,
14328 sec_damping: i32,
14329 enable_primary: bool,
14330 enable_secondary: bool,
14331 coeff_shift: i32,
14332 smax: i32,
14333) {
14334 let clipping_required = enable_primary && enable_secondary;
14335 // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >>
14336 // coeff_shift) & 1]` -- `pri_strength` (and its `adjust_strength`
14337 // derivative) carries the bit-depth shift, so the tap-set parity bit
14338 // must be read back above that shift, not off the raw low bit.
14339 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
14340 // Both damping shifts depend only on this block's strengths (spec 7.15.3's
14341 // `constrain`), so they are resolved here rather than per tap read.
14342 let pri_shift = cdef_constrain_shift(pri_strength.max(1), pri_damping);
14343 let sec_shift = cdef_constrain_shift(sec_strength.max(1), sec_damping);
14344 let bstride = bw + 2 * CDEF_BORDER;
14345 // `src` is [`cdef_gather`]'s window: (i, j) in block coordinates, taps
14346 // reaching +-CDEF_BORDER, so every index below is in range by construction.
14347 let at = |i: i32, j: i32| -> i32 {
14348 src[(i + CDEF_BORDER as i32) as usize * bstride + (j + CDEF_BORDER as i32) as usize]
14349 };
14350 let (pri_dir, sec_dir0, sec_dir1) =
14351 (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]);
14352 for i in 0..bh {
14353 for j in 0..bw {
14354 let (i32i, i32j) = (i as i32, j as i32);
14355 let x = at(i32i, i32j);
14356 let mut sum = 0i32;
14357 let mut max = x;
14358 let mut min = x;
14359 for k in 0..2usize {
14360 if enable_primary {
14361 let (tr, tc) = pri_dir[k];
14362 let p0 = at(i32i + tr, i32j + tc);
14363 let p1 = at(i32i - tr, i32j - tc);
14364 sum += pri_taps[k] * cdef_constrain_shifted(p0 - x, pri_strength, pri_shift);
14365 sum += pri_taps[k] * cdef_constrain_shifted(p1 - x, pri_strength, pri_shift);
14366 if clipping_required {
14367 if p0 != CDEF_VERY_LARGE {
14368 max = max.max(p0);
14369 }
14370 if p1 != CDEF_VERY_LARGE {
14371 max = max.max(p1);
14372 }
14373 min = min.min(p0).min(p1);
14374 }
14375 }
14376 if enable_secondary {
14377 let (tr0, tc0) = sec_dir0[k];
14378 let (tr1, tc1) = sec_dir1[k];
14379 let s0 = at(i32i + tr0, i32j + tc0);
14380 let s1 = at(i32i - tr0, i32j - tc0);
14381 let s2 = at(i32i + tr1, i32j + tc1);
14382 let s3 = at(i32i - tr1, i32j - tc1);
14383 if clipping_required {
14384 for s in [s0, s1, s2, s3] {
14385 if s != CDEF_VERY_LARGE {
14386 max = max.max(s);
14387 }
14388 }
14389 min = min.min(s0).min(s1).min(s2).min(s3);
14390 }
14391 sum += CDEF_SEC_TAPS[k]
14392 * (cdef_constrain_shifted(s0 - x, sec_strength, sec_shift)
14393 + cdef_constrain_shifted(s1 - x, sec_strength, sec_shift)
14394 + cdef_constrain_shifted(s2 - x, sec_strength, sec_shift)
14395 + cdef_constrain_shifted(s3 - x, sec_strength, sec_shift));
14396 }
14397 }
14398 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
14399 if clipping_required {
14400 y = y.clamp(min, max);
14401 }
14402 dst[(oy + i) * stride + (ox + j)] = y.clamp(0, smax) as u16;
14403 }
14404 }
14405}
14406
14407/// lane-perf7 step 1: [`cdef_filter_block`]'s AVX2 kernel -- the scalar
14408/// filter was 13.1% of a 4K decode's self time. Nothing here is spec logic:
14409/// the same taps, the same `constrain`, the same `min`/`max` clamp with the
14410/// `CDEF_VERY_LARGE` sentinel excluded from the max, the same
14411/// `y + ((8 + sum - (sum < 0)) >> 4)` rounding, done 16 samples (two rows) at
14412/// a time in 16-bit lanes.
14413///
14414/// 16-bit lanes are exact for every value this filter sees: window samples
14415/// are in `[0, CDEF_VERY_LARGE]` (0x4000), so a tap difference fits in
14416/// `i16`, a `constrain` result is bounded by the threshold (at most
14417/// `15 << 4`), and the tap-weighted sum by `24 *` that.
14418#[cfg(target_arch = "x86_64")]
14419#[allow(unsafe_code)]
14420#[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract
14421mod cdef_simd {
14422 use super::{
14423 cdef_constrain_shift, CDEF_BORDER, CDEF_DIRECTIONS, CDEF_PRI_TAPS, CDEF_SEC_TAPS,
14424 CDEF_VERY_LARGE,
14425 };
14426 use std::arch::x86_64::*;
14427
14428 /// The window's rows `i` and `i + 1` at one tap offset, as one 256-bit
14429 /// register (low half = row `i`).
14430 ///
14431 /// # Safety
14432 /// Requires AVX2; `off + bstride + 8` must be inside `w`.
14433 #[target_feature(enable = "avx2")]
14434 #[inline]
14435 unsafe fn ld2(w: *const i16, off: isize, bstride: isize) -> __m256i {
14436 let lo = _mm_loadu_si128(w.offset(off).cast());
14437 let hi = _mm_loadu_si128(w.offset(off + bstride).cast());
14438 _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1)
14439 }
14440
14441 /// Spec 7.15.3's `constrain`, lane-parallel:
14442 /// `sign(diff) * clamp(threshold - (|diff| >> shift), 0, |diff|)`.
14443 /// `_mm256_sign_epi16` reproduces `signum` exactly, zero included (the
14444 /// clamped magnitude is already 0 where `diff` is).
14445 ///
14446 /// # Safety
14447 /// Requires AVX2.
14448 #[target_feature(enable = "avx2")]
14449 #[inline]
14450 unsafe fn constrain(p: __m256i, x: __m256i, thr: __m256i, shift: __m128i) -> __m256i {
14451 let diff = _mm256_sub_epi16(p, x);
14452 let a = _mm256_abs_epi16(diff);
14453 let t = _mm256_sub_epi16(thr, _mm256_sra_epi16(a, shift));
14454 let t = _mm256_min_epi16(_mm256_max_epi16(t, _mm256_setzero_si256()), a);
14455 _mm256_sign_epi16(t, diff)
14456 }
14457
14458 /// [`super::cdef_filter_block_scalar`]'s arithmetic, two rows per
14459 /// iteration. `bw` is 8 (luma) or 4 (4:2:0 chroma) and `bh` matches; for
14460 /// `bw == 4` the upper four lanes of each half are window samples read
14461 /// past the row (never past the buffer -- `w` is padded to 256 entries),
14462 /// computed and then dropped by the 64-bit store.
14463 ///
14464 /// # Safety
14465 /// Requires AVX2. `src` must hold the `(bw + 4) x (bh + 4)` window and
14466 /// `dst` the `bh` rows of `bw` samples at `(ox, oy)`.
14467 #[target_feature(enable = "avx2")]
14468 #[allow(clippy::too_many_arguments)]
14469 pub unsafe fn filter_block_avx2(
14470 src: &[i32],
14471 dst: &mut [u16],
14472 stride: usize,
14473 ox: usize,
14474 oy: usize,
14475 bw: usize,
14476 bh: usize,
14477 pri_strength: i32,
14478 sec_strength: i32,
14479 dir: usize,
14480 pri_damping: i32,
14481 sec_damping: i32,
14482 enable_primary: bool,
14483 enable_secondary: bool,
14484 coeff_shift: i32,
14485 smax: i32,
14486 ) {
14487 let bstride = bw + 2 * CDEF_BORDER;
14488 // The window as `i16`, padded so every two-row tap load stays inside
14489 // it (largest read: (bh + 3) * bstride + 8 <= 152 for the 8x8 luma
14490 // block, 72 for the 4x4 chroma one).
14491 let mut w = [0i16; 256];
14492 let rows = bh + 2 * CDEF_BORDER;
14493 for (d, &v) in w[..rows * bstride].iter_mut().zip(&src[..rows * bstride]) {
14494 *d = v as i16;
14495 }
14496 let clipping_required = enable_primary && enable_secondary;
14497 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
14498 let pri_shift = _mm_cvtsi32_si128(cdef_constrain_shift(pri_strength.max(1), pri_damping));
14499 let sec_shift = _mm_cvtsi32_si128(cdef_constrain_shift(sec_strength.max(1), sec_damping));
14500 let pri_thr = _mm256_set1_epi16(pri_strength as i16);
14501 let sec_thr = _mm256_set1_epi16(sec_strength as i16);
14502 let very_large = _mm256_set1_epi16(CDEF_VERY_LARGE as i16);
14503 let zero = _mm256_setzero_si256();
14504 let eight = _mm256_set1_epi16(8);
14505 let smaxv = _mm256_set1_epi16(smax as i16);
14506 let (pri_dir, sec_dir0, sec_dir1) =
14507 (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]);
14508 let wp = w.as_ptr();
14509 let bs = bstride as isize;
14510 let dp = dst.as_mut_ptr();
14511 let mut i = 0usize;
14512 while i < bh {
14513 let base = (i + CDEF_BORDER) as isize * bs + CDEF_BORDER as isize;
14514 let x = ld2(wp, base, bs);
14515 let mut sum = zero;
14516 let mut max = x;
14517 let mut min = x;
14518 for k in 0..2usize {
14519 if enable_primary {
14520 let (tr, tc) = pri_dir[k];
14521 let off = tr as isize * bs + tc as isize;
14522 let p0 = ld2(wp, base + off, bs);
14523 let p1 = ld2(wp, base - off, bs);
14524 let tap = _mm256_set1_epi16(pri_taps[k] as i16);
14525 sum = _mm256_add_epi16(
14526 sum,
14527 _mm256_mullo_epi16(tap, constrain(p0, x, pri_thr, pri_shift)),
14528 );
14529 sum = _mm256_add_epi16(
14530 sum,
14531 _mm256_mullo_epi16(tap, constrain(p1, x, pri_thr, pri_shift)),
14532 );
14533 if clipping_required {
14534 // The sentinel is excluded from the max exactly as the
14535 // scalar `if p != CDEF_VERY_LARGE` does: masking it to
14536 // 0 cannot win a max whose seed `x` is non-negative.
14537 max = _mm256_max_epi16(
14538 max,
14539 _mm256_andnot_si256(_mm256_cmpeq_epi16(p0, very_large), p0),
14540 );
14541 max = _mm256_max_epi16(
14542 max,
14543 _mm256_andnot_si256(_mm256_cmpeq_epi16(p1, very_large), p1),
14544 );
14545 min = _mm256_min_epi16(min, _mm256_min_epi16(p0, p1));
14546 }
14547 }
14548 if enable_secondary {
14549 let (tr0, tc0) = sec_dir0[k];
14550 let (tr1, tc1) = sec_dir1[k];
14551 let off0 = tr0 as isize * bs + tc0 as isize;
14552 let off1 = tr1 as isize * bs + tc1 as isize;
14553 let s0 = ld2(wp, base + off0, bs);
14554 let s1 = ld2(wp, base - off0, bs);
14555 let s2 = ld2(wp, base + off1, bs);
14556 let s3 = ld2(wp, base - off1, bs);
14557 if clipping_required {
14558 for s in [s0, s1, s2, s3] {
14559 max = _mm256_max_epi16(
14560 max,
14561 _mm256_andnot_si256(_mm256_cmpeq_epi16(s, very_large), s),
14562 );
14563 }
14564 min = _mm256_min_epi16(
14565 min,
14566 _mm256_min_epi16(
14567 _mm256_min_epi16(s0, s1),
14568 _mm256_min_epi16(s2, s3),
14569 ),
14570 );
14571 }
14572 let c = _mm256_add_epi16(
14573 _mm256_add_epi16(
14574 constrain(s0, x, sec_thr, sec_shift),
14575 constrain(s1, x, sec_thr, sec_shift),
14576 ),
14577 _mm256_add_epi16(
14578 constrain(s2, x, sec_thr, sec_shift),
14579 constrain(s3, x, sec_thr, sec_shift),
14580 ),
14581 );
14582 sum = _mm256_add_epi16(
14583 sum,
14584 _mm256_mullo_epi16(_mm256_set1_epi16(CDEF_SEC_TAPS[k] as i16), c),
14585 );
14586 }
14587 }
14588 // `-1` where `sum < 0`, i.e. the scalar `- i32::from(sum < 0)`.
14589 let neg = _mm256_cmpgt_epi16(zero, sum);
14590 let mut y = _mm256_add_epi16(
14591 x,
14592 _mm256_srai_epi16(_mm256_add_epi16(_mm256_add_epi16(eight, sum), neg), 4),
14593 );
14594 if clipping_required {
14595 y = _mm256_min_epi16(_mm256_max_epi16(y, min), max);
14596 }
14597 y = _mm256_min_epi16(_mm256_max_epi16(y, zero), smaxv);
14598 let (lo, hi) = (_mm256_castsi256_si128(y), _mm256_extracti128_si256(y, 1));
14599 let o0 = ((oy + i) * stride + ox) as isize;
14600 let o1 = o0 + stride as isize;
14601 if bw == 8 {
14602 _mm_storeu_si128(dp.offset(o0).cast(), lo);
14603 _mm_storeu_si128(dp.offset(o1).cast(), hi);
14604 } else {
14605 _mm_storel_epi64(dp.offset(o0).cast(), lo);
14606 _mm_storel_epi64(dp.offset(o1).cast(), hi);
14607 }
14608 i += 2;
14609 }
14610 }
14611}
14612
14613/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
14614/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
14615/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
14616/// every block's level comes from [`LoopFilterParams::level`] plus the
14617/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
14618/// `get_filter_level`, precomputed per-block here rather than cached in a
14619/// table the way libaom's `av1_loop_filter_frame_init` does).
14620///
14621/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
14622/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
14623fn apply_deblock(
14624 y: &mut PlaneBuf,
14625 u: &mut PlaneBuf,
14626 v: &mut PlaneBuf,
14627 lf: &LoopFilterParams,
14628 n: &Neighbours,
14629 frame_width: usize,
14630 frame_height: usize,
14631) {
14632 // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel
14633 // mismatch between the raw reconstruction and post-filter output.
14634 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_DEBLOCK") {
14635 return;
14636 }
14637 if lf.level[0] != 0 || lf.level[1] != 0 {
14638 deblock_plane(y, 0, lf, n, frame_width, frame_height);
14639 }
14640 if lf.level[2] != 0 {
14641 deblock_plane(u, 1, lf, n, frame_width, frame_height);
14642 }
14643 if lf.level[3] != 0 {
14644 deblock_plane(v, 2, lf, n, frame_width, frame_height);
14645 }
14646}
14647
14648/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
14649/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
14650/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
14651/// mi unit under this decoder's assumed 4:2:0 subsampling).
14652///
14653/// lane-t900 r30b: the chroma arm ORs in the subsampling, exactly as
14654/// `set_lpf_parameters` does (`av1_loopfilter.c:245`, `mi_col = scale_horz |
14655/// ((x << scale_horz) >> MI_SIZE_LOG2)`) -- "for sub8x8 block, chroma
14656/// prediction mode is obtained from the bottom/right mi structure of the
14657/// co-located 8x8 luma block, so for chroma plane both mi_row and mi_col
14658/// should be odd". Dropping that `| 1` read the group's TOP-LEFT mi, which
14659/// is the same cell for every block 8x8 and larger and a DIFFERENT coded
14660/// block (different tx size, ref frame, skip flag and delta_lf) as soon as
14661/// the group is split into 4x4 luma blocks (class
14662/// `context-read-from-one-cell`).
14663fn plane_to_mi(chroma: bool, coord: usize) -> usize {
14664 if chroma { (coord / 2) | 1 } else { coord / 4 }
14665}
14666
14667/// This plane's own transform width in pixels at the covering block, spec
14668/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
14669/// width directly; chroma halves it (this decoder's UV transform is always
14670/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
14671/// under 4:2:0 and a block that never splits its own transform).
14672fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
14673 let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid };
14674 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
14675}
14676
14677/// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
14678/// edges step and gate by transform height, which differs from width only
14679/// on rect partition strips.
14680fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
14681 let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid };
14682 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
14683}
14684
14685/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
14686/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
14687/// present only when its neighbour exists inside the true frame -- whether
14688/// the block immediately above (at this block's own leftmost mi column) or
14689/// to the left (at its own topmost mi row) coded a transform at least as wide
14690/// as `own_side`.
14691fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
14692 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side;
14693 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side;
14694 usize::from(above) + usize::from(left)
14695}
14696
14697/// `get_tx_size_context` as libaom actually writes it (`pred_common.h:342`),
14698/// for a block inside an INTER frame: the two `TXFM_CONTEXT` arrays
14699/// ([`Neighbours::above_txfm`]/[`Neighbours::left_txfm`], which only the
14700/// inter path maintains), except that an *inter* neighbour contributes its
14701/// own BLOCK size rather than its transform size -- the two differ the moment
14702/// a neighbour's var-tx tree splits. [`tx_size_context`]'s deblock-grid
14703/// approximation coincides with this only while every neighbour codes one
14704/// whole-block transform, which is exactly what `TxMode::Select` ends.
14705/// [`tx_size_context_txfm`] with the block's own width and height (lane-intrasplit
14706/// r1): `get_tx_size_context` compares the neighbour ABOVE against
14707/// `tx_size_wide[max_txsize_rect_lookup[bsize]]` and the neighbour to the LEFT
14708/// against `tx_size_high[...]` (libaom `pred_common.h:342`), which for a 2:1
14709/// strip are two different numbers. The intra strip inside an inter frame read
14710/// this through [`tx_size_context_rect`] -- the key frame's deblock-grid
14711/// approximation -- so once `TxMode::Select` made the depth symbol exist, it was
14712/// read off the wrong CDF row whenever a neighbour's var-tx tree had split.
14713fn tx_size_context_txfm_rect(
14714 n: &Neighbours,
14715 (mi_r, mi_c): (usize, usize),
14716 own_w: usize,
14717 own_h: usize,
14718) -> usize {
14719 INTRA_IN_INTER_TXCTX_HITS.with(|c| c.set(c.get() + 1));
14720 let has_above = mi_r > n.tile_row0_mi;
14721 let has_left = mi_c > n.tile_col0_mi;
14722 let mut above = usize::from(n.above_txfm[mi_c]) >= own_w;
14723 let mut left = usize::from(n.left_txfm[mi_r]) >= own_h;
14724 if has_above && n.above_inter[mi_c] {
14725 above = n.above_side_mi[mi_c] >= own_w;
14726 }
14727 if has_left && n.left_inter[mi_r] {
14728 left = n.left_side_mi[mi_r] >= own_h;
14729 }
14730 if crate::envflags::env_flag!("EC_TXCTX") {
14731 eprintln!(
14732 "EC_TXCTX mi={mi_r},{mi_c} own={own_w}x{own_h} ha={has_above} hl={has_left} \
14733 above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \
14734 above={above} left={left}",
14735 n.above_txfm[mi_c],
14736 n.left_txfm[mi_r],
14737 n.above_inter[mi_c],
14738 n.left_inter[mi_r],
14739 n.above_side_mi[mi_c],
14740 n.left_side_mi[mi_r],
14741 );
14742 }
14743 let ctx = match (has_above, has_left) {
14744 (true, true) => usize::from(above) + usize::from(left),
14745 (true, false) => usize::from(above),
14746 (false, true) => usize::from(left),
14747 (false, false) => 0,
14748 };
14749 // lane-midcut r3: count only the blocks the KEY FRAME deblock-grid
14750 // approximation ([`tx_size_context_rect`]) would have read off a DIFFERENT
14751 // CDF row, i.e. exactly the blocks this band read fixes -- a plain "rect
14752 // intra in an inter frame" tally is green on the buggy code too (class
14753 // gate-blind-to-feature).
14754 if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {
14755 let (cw, ch) = (own_w.min(64), own_h.min(64));
14756 let stale = usize::from(has_above && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= cw)
14757 + usize::from(has_left && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= ch);
14758 if ctx != stale {
14759 INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS.with(|c| c.set(c.get() + 1));
14760 }
14761 }
14762 ctx
14763}
14764
14765/// lane-intrasplit r3: `above_inter`/`left_inter` are mi-granular bands (they
14766/// are written and read everywhere else with a raw mi index); the SUB-cell
14767/// division this pair used read a cell four blocks away, so the inter-neighbour
14768/// override above fired on the wrong neighbour -- the first divergence of the
14769/// 10-bit gate's stream was exactly this (`tx_depth` ctx 0 where libaom has 1,
14770/// at the intra block right of an inter one).
14771fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
14772 let has_above = mi_r > n.tile_row0_mi;
14773 let has_left = mi_c > n.tile_col0_mi;
14774 let mut above = usize::from(n.above_txfm[mi_c]) >= side;
14775 let mut left = usize::from(n.left_txfm[mi_r]) >= side;
14776 // lane-angledelta r1 (class [[context-read-from-one-cell]]): both
14777 // `above_inter`/`left_inter` bands are written per MI unit
14778 // (`record_inter_rect_mi`), so they are read per MI too -- the `/ (SUB /
14779 // MI)` here read the 16-px cell's FIRST mi instead, i.e. a different
14780 // block whenever the neighbour column/row is not the cell's first. A
14781 // 16x16 intra block whose left neighbour is an inter block at mi row 4
14782 // then missed libaom's "an inter neighbour contributes its BLOCK size"
14783 // override and read `tx_size_cat1` row 1 where aomdec reads row 2.
14784 if has_above && n.above_inter[mi_c] {
14785 above = n.above_side_mi[mi_c] >= side;
14786 }
14787 if has_left && n.left_inter[mi_r] {
14788 left = n.left_side_mi[mi_r] >= side;
14789 }
14790 if crate::envflags::env_flag!("EC_TXCTX") {
14791 eprintln!(
14792 "EC_TXCTX mi={mi_r},{mi_c} own={side} ha={has_above} hl={has_left} \
14793 above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \
14794 above={above} left={left}",
14795 n.above_txfm[mi_c],
14796 n.left_txfm[mi_r],
14797 n.above_inter[mi_c],
14798 n.left_inter[mi_r],
14799 n.above_side_mi[mi_c],
14800 n.left_side_mi[mi_r],
14801 );
14802 }
14803 match (has_above, has_left) {
14804 (true, true) => usize::from(above) + usize::from(left),
14805 (true, false) => usize::from(above),
14806 (false, true) => usize::from(left),
14807 (false, false) => 0,
14808 }
14809}
14810
14811/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
14812/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
14813/// the transform's own side in pixels (`side >> depth`) -- this decoder's
14814/// four square categories (8/16/32/64) each halve at most twice, matching
14815/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
14816fn read_tx_size(
14817 dec: &mut SymbolDecoder,
14818 cdfs: &mut Cdfs,
14819 n: &Neighbours,
14820 at_mi: (usize, usize),
14821 side: usize,
14822 // lane-txselect: `get_tx_size_context`'s real context, for the callers
14823 // that have one -- see [`tx_size_context_txfm`]. `None` keeps the
14824 // key-frame path's own deblock-grid approximation.
14825 ctx_override: Option<usize>,
14826) -> usize {
14827 // `max_txsize_rect_lookup[bsize]` (libaom `read_selected_tx_size` /
14828 // `get_tx_size_context`): a block wider than 64 still tops out at
14829 // TX_64X64, so BLOCK_128X128 reads BLOCK_64X64's own category (its depth
14830 // chain 64->32->16->8->4 is the same four steps) and resolves against 64,
14831 // never against its own 128 side (lane-sb128b r1).
14832 let max_tx = side.min(64);
14833 let ctx = ctx_override.unwrap_or_else(|| tx_size_context(n, at_mi, max_tx));
14834 let depth = match max_tx {
14835 8 => {
14836 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
14837 }
14838 16 => {
14839 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
14840 }
14841 32 => {
14842 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
14843 }
14844 64 => {
14845 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
14846 }
14847 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64/128"),
14848 };
14849 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
14850 let (rng, _) = dec.debug_state();
14851 let (mi_r, mi_c) = at_mi;
14852 eprintln!(
14853 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={depth} ctx={ctx} rng={rng}"
14854 );
14855 }
14856 if depth != 0 {
14857 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
14858 }
14859 max_tx >> depth
14860}
14861
14862/// `txfm_partition_context` (libaom `av1_common_int.h`): an inter block's
14863/// `txfm_split` context -- a category from the block's own largest square
14864/// transform and whether this unit already sits below it, times three, plus
14865/// the two neighbour terms (whether the transform last written above/left of
14866/// this unit is narrower/shorter than the unit itself).
14867fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize {
14868 txfm_partition_ctx_rect(above_px, left_px, blk_max_px, tx_px, tx_px)
14869}
14870
14871/// [`txfm_partition_ctx`] for a *rectangular* transform (lane-inter4 r2):
14872/// libaom's `txfm_partition_context` compares the above context against
14873/// `tx_size_wide` and the left one against `tx_size_high`, and takes its
14874/// category from `txsize_sqr_up_map[tx_size]` -- all three collapse to one
14875/// side for a square transform, which is why the square form above is a
14876/// special case of this one.
14877fn txfm_partition_ctx_rect(
14878 above_px: u8,
14879 left_px: u8,
14880 blk_max_px: usize,
14881 tx_w: usize,
14882 tx_h: usize,
14883) -> usize {
14884 let above = usize::from(usize::from(above_px) < tx_w);
14885 let left = usize::from(usize::from(left_px) < tx_h);
14886 let tx_px = tx_w.max(tx_h);
14887 // `get_sqr_tx_size(max(block_size_wide, block_size_high))`, capped at the
14888 // largest transform (`TX_64X64`); `TX_4X4`..`TX_64X64` index as
14889 // `log2(px) - 2`.
14890 let max_tx = blk_max_px.min(64);
14891 let max_idx = max_tx.trailing_zeros() as usize - 2;
14892 let category = usize::from(tx_px != max_tx && max_tx > 8) + (4 - max_idx) * 2;
14893 category * 3 + above + left
14894}
14895
14896/// `txfm_partition_update` (libaom `av1_common_int.h`): once a var-tx unit
14897/// resolves, every mi cell its *parent* unit (`txb_px`) spans records the
14898/// resolved transform's own size.
14899fn txfm_partition_update(
14900 n: &mut Neighbours,
14901 at_mi: (usize, usize),
14902 tx_px: usize,
14903 txb_px: usize,
14904) {
14905 txfm_partition_update_rect(n, at_mi, (tx_px, tx_px), (txb_px, txb_px));
14906}
14907
14908/// [`txfm_partition_update`] for a rectangular transform (lane-inter4 r2):
14909/// the left column records `tx_size_high` over the parent's own height and
14910/// the above row records `tx_size_wide` over its width.
14911/// libaom `set_txfm_ctxs` + `txfm_partition_update` (`decodeframe.c`, end of
14912/// `decode_token_recon_block`): EVERY block of an inter frame publishes its
14913/// TRANSFORM size into both `TXFM_CONTEXT` bands, intra blocks included. The
14914/// key frame writes neither (its readers use the deblock grid), so the
14915/// key-frame bodies reused by [`decode_intra_rect_in_inter`] have to do it
14916/// themselves when they run inside an inter frame. The 2:1 and 16x4 arms do it
14917/// at the call site (the transform size comes back to them); the 1:4 arms
14918/// ([`decode_block_rect4`] / [`decode_block_rect64`]) keep their size inside,
14919/// so they call this where their own depth resolves. A no-op on a key frame
14920/// ([`INTRA_IN_INTER_MODE`] unset), where those bands are not read at all.
14921///
14922/// lane-t900 r1 root cause: the HORZ_4 32x8 intra strip at mi(0,312) of an
14923/// inter frame left `left_txfm[0]` at a stale 32 where libaom's own
14924/// `set_txfm_ctxs` writes 8, so the intra 8x16 block at mi(0,320) read
14925/// `tx_size_cat1` row 1 instead of row 0 -- same depth VALUE, different CDF,
14926/// range 39156 where the reference has 54736 (class tx-grid-published-block-side
14927/// / early-return-skips-tail).
14928fn publish_txfm_bands_if_in_inter(
14929 n: &mut Neighbours,
14930 at_mi: (usize, usize),
14931 (tx_w, tx_h): (usize, usize),
14932 (bw, bh): (usize, usize),
14933) {
14934 if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_none() {
14935 return;
14936 }
14937 let (mi_r, mi_c) = at_mi;
14938 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
14939 for i in 0..bw / MI {
14940 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
14941 *cell = tx_w as u8;
14942 }
14943 }
14944 for i in 0..bh / MI {
14945 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
14946 *cell = tx_h as u8;
14947 }
14948 }
14949}
14950
14951fn txfm_partition_update_rect(
14952 n: &mut Neighbours,
14953 (mi_r, mi_c): (usize, usize),
14954 (tx_w, tx_h): (usize, usize),
14955 (txb_w, txb_h): (usize, usize),
14956) {
14957 if crate::envflags::env_flag!("EC_TXUPD") {
14958 eprintln!("EC_TXUPD rect mi=({},{}) tx=({tx_w},{tx_h}) txb=({txb_w},{txb_h})", mi_r, mi_c);
14959 }
14960 for i in 0..txb_h / MI {
14961 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
14962 *cell = tx_h as u8;
14963 }
14964 }
14965 for i in 0..txb_w / MI {
14966 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
14967 *cell = tx_w as u8;
14968 }
14969 }
14970}
14971
14972/// `set_txfm_ctxs` (libaom `av1_common_int.h`): the non-var-tx write of the
14973/// same contexts -- a skipped *inter* block records its own block size rather
14974/// than its transform size.
14975fn set_txfm_ctxs(
14976 n: &mut Neighbours,
14977 (mi_r, mi_c): (usize, usize),
14978 tx_px: usize,
14979 w_mi: usize,
14980 h_mi: usize,
14981 skip_inter: bool,
14982) {
14983 if crate::envflags::env_flag!("EC_TXUPD") {
14984 eprintln!("EC_TXUPD ctxs mi=({mi_r},{mi_c}) tx={tx_px} wh=({w_mi},{h_mi}) skip_inter={skip_inter}");
14985 }
14986 let bw = if skip_inter { w_mi * MI } else { tx_px };
14987 let bh = if skip_inter { h_mi * MI } else { tx_px };
14988 for i in 0..w_mi {
14989 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
14990 *cell = bw as u8;
14991 }
14992 }
14993 for i in 0..h_mi {
14994 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
14995 *cell = bh as u8;
14996 }
14997 }
14998}
14999
15000/// The value libaom initialises both transform contexts to -- NOT zero:
15001/// `av1_zero_above_context` memsets the txfm row to
15002/// `tx_size_wide[TX_SIZES_LARGEST]` and `av1_zero_left_context` does the same
15003/// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64
15004/// pixels, so an unwritten neighbour reads as the *widest* possible
15005/// transform, not the narrowest.
15006const TXFM_CTX_INIT: u8 = 64;
15007
15008/// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most
15009/// twice below its own largest transform.
15010const MAX_VARTX_DEPTH: usize = 2;
15011
15012/// libaom `sub_tx_size_map[TX_SIZES_ALL]` (`common_data.c`): the transform
15013/// one `txfm_split` step below `tx_size`. RECTANGULAR for the 1:4 shapes
15014/// (`[TX_64X16] == TX_32X16`, `[TX_16X64] == TX_16X32`) and for the 4:1
15015/// small ones, square everywhere else.
15016fn sub_tx_size_map(tx_w: usize, tx_h: usize) -> (usize, usize) {
15017 match (tx_w, tx_h) {
15018 (4, 4) => (4, 4),
15019 (8, 8) => (4, 4),
15020 (16, 16) => (8, 8),
15021 (32, 32) => (16, 16),
15022 (64, 64) => (32, 32),
15023 (4, 8) | (8, 4) => (4, 4),
15024 (8, 16) | (16, 8) => (8, 8),
15025 (16, 32) | (32, 16) => (16, 16),
15026 (32, 64) | (64, 32) => (32, 32),
15027 (4, 16) => (4, 8),
15028 (16, 4) => (8, 4),
15029 (8, 32) => (8, 16),
15030 (32, 8) => (16, 8),
15031 (16, 64) => (16, 32),
15032 (64, 16) => (32, 16),
15033 _ => unreachable!("not a TX_SIZES_ALL shape: {tx_w}x{tx_h}"),
15034 }
15035}
15036
15037#[test]
15038fn sub_tx_size_map_matches_libaom() {
15039 // libaom `common_data.c` `sub_tx_size_map`, in TX_SIZES_ALL order.
15040 const TABLE: [((usize, usize), (usize, usize)); 19] = [
15041 ((4, 4), (4, 4)), ((8, 8), (4, 4)), ((16, 16), (8, 8)), ((32, 32), (16, 16)),
15042 ((64, 64), (32, 32)), ((4, 8), (4, 4)), ((8, 4), (4, 4)), ((8, 16), (8, 8)),
15043 ((16, 8), (8, 8)), ((16, 32), (16, 16)), ((32, 16), (16, 16)), ((32, 64), (32, 32)),
15044 ((64, 32), (32, 32)), ((4, 16), (4, 8)), ((16, 4), (8, 4)), ((8, 32), (8, 16)),
15045 ((32, 8), (16, 8)), ((16, 64), (16, 32)), ((64, 16), (32, 16)),
15046 ];
15047 for (tx, want) in TABLE {
15048 assert_eq!(sub_tx_size_map(tx.0, tx.1), want, "sub_tx_size_map({tx:?})");
15049 }
15050}
15051
15052/// The domain of var-tx leaf sizes, enumerated against the two refusals that
15053/// name a leaf "larger than 32x32" / "larger than 64x64".
15054///
15055/// [`read_var_tx_size`] emits a leaf in exactly three places, and each one is
15056/// either the unit it was entered with or a `sub_tx_size_map` step below it:
15057/// the depth cap, the `!split` return, and libaom's `sub_txs == TX_4X4` early
15058/// return. So the leaf set reachable from an entry unit is that unit plus the
15059/// chain of `sub_tx_size_map` steps under it, capped at `MAX_VARTX_DEPTH` --
15060/// which this test enumerates, and over which no leaf is ever larger than the
15061/// entry.
15062///
15063/// That closes both refusals:
15064///
15065/// * [`read_block_tx_size_rect`]'s `bw.max(bh) > 64` branch enters every unit
15066/// at TX_64X64 (`max_txsize_rect_lookup[BLOCK_128X64]`), so "larger than
15067/// 64x64" names a leaf the tree cannot produce;
15068/// * [`read_block_tx_size`] enters at `side.min(64)` with a ceiling of 32
15069/// below the 128 root. The only entry that exceeds that ceiling is 64x64,
15070/// reached only when `side == 64`, and then the block is ONE unit whose only
15071/// above-ceiling leaf is the whole 64x64 unit itself -- which is the `single`
15072/// case the refusal is guarded by.
15073#[test]
15074fn a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered() {
15075 // Every leaf `read_var_tx_size` can reach from `entry`, as (depth, w, h).
15076 fn reachable(entry: (usize, usize), depth: usize, out: &mut Vec<(usize, usize, usize)>) {
15077 out.push((depth, entry.0, entry.1));
15078 if depth == MAX_VARTX_DEPTH {
15079 return;
15080 }
15081 let sub = sub_tx_size_map(entry.0, entry.1);
15082 if sub == (4, 4) {
15083 out.push((depth + 1, 4, 4));
15084 return;
15085 }
15086 reachable(sub, depth + 1, out);
15087 }
15088
15089 for entry in [(4, 4), (8, 8), (16, 16), (32, 32), (64, 64)] {
15090 let mut leaves = Vec::new();
15091 reachable(entry, 0, &mut leaves);
15092 for (depth, w, h) in &leaves {
15093 assert!(
15094 w.max(h) <= &entry.0.max(entry.1),
15095 "a {}x{} unit reaches a {w}x{h} leaf at depth {depth}",
15096 entry.0,
15097 entry.1
15098 );
15099 }
15100 // Above-ceiling leaves of a 64x64 entry: the entry itself, at depth 0.
15101 if entry == (64, 64) {
15102 let above: Vec<&(usize, usize, usize)> =
15103 leaves.iter().filter(|(_, w, h)| w.max(h) > &32).collect();
15104 assert_eq!(above, [&(0usize, 64usize, 64usize)], "64x64 entry, leaves above 32");
15105 }
15106 }
15107
15108 // The entry size and ceiling each caller uses, over the block sides that
15109 // reach them (`read_block_tx_size`'s square path; the 128-root rect path
15110 // enters at a fixed 64).
15111 for side in [8usize, 16, 32, 64, 128] {
15112 let max_tx = side.min(64);
15113 let ceiling = if side > 64 { 64 } else { 32 };
15114 let units = (side / max_tx) * (side / max_tx);
15115 if max_tx <= ceiling {
15116 continue;
15117 }
15118 assert_eq!(
15119 (side, units),
15120 (64, 1),
15121 "a {side}px block enters var-tx at {max_tx} over a ceiling of {ceiling} in \
15122 {units} units -- an above-ceiling leaf there would NOT be the `single` case"
15123 );
15124 }
15125}
15126
15127/// `read_var_tx_size` (spec 5.11.17, libaom `decodeframe.c`
15128/// `read_tx_size_vartx`): the recursive `txfm_split` tree of one
15129/// max-transform-sized unit of an inter block, collecting the resolved leaf
15130/// transform units into `out` as `(row offset, col offset, side)` in mi units
15131/// -- exactly the order `decode_reconstruct_tx` later reads their
15132/// coefficients in. `blk_row`/`blk_col` are mi offsets inside the block;
15133/// `max_w_mi`/`max_h_mi` clip it to the true frame edge (`max_block_wide`/
15134/// `max_block_high`).
15135#[allow(clippy::too_many_arguments)]
15136fn read_var_tx_size(
15137 dec: &mut SymbolDecoder,
15138 cdfs: &mut Cdfs,
15139 n: &mut Neighbours,
15140 at_mi: (usize, usize),
15141 blk_max_px: usize,
15142 (max_w_mi, max_h_mi): (usize, usize),
15143 (tx_w, tx_h): (usize, usize),
15144 depth: usize,
15145 blk_row: usize,
15146 blk_col: usize,
15147 out: &mut Vec<(usize, usize, usize, usize)>,
15148) {
15149 if blk_row >= max_h_mi || blk_col >= max_w_mi {
15150 return;
15151 }
15152 let unit = (at_mi.0 + blk_row, at_mi.1 + blk_col);
15153 if depth == MAX_VARTX_DEPTH {
15154 out.push((blk_row, blk_col, tx_w, tx_h));
15155 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
15156 return;
15157 }
15158 let ctx = txfm_partition_ctx_rect(
15159 n.above_txfm[unit.1],
15160 n.left_txfm[unit.0],
15161 blk_max_px,
15162 tx_w,
15163 tx_h,
15164 );
15165 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
15166 TXFM_SPLIT_READS.with(|c| c.set(c.get() + 1));
15167 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
15168 let (rng, _) = dec.debug_state();
15169 eprintln!(
15170 "EC_ISTEP mi_row={} mi_col={} name=txfm_split val={} ctx={ctx} rng={rng}",
15171 unit.0,
15172 unit.1,
15173 u8::from(split)
15174 );
15175 }
15176 if !split {
15177 out.push((blk_row, blk_col, tx_w, tx_h));
15178 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
15179 return;
15180 }
15181 TXFM_SPLIT_HITS.with(|c| c.set(c.get() + 1));
15182 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
15183 if (sub_w, sub_h) == (4, 4) {
15184 // libaom's `sub_txs == TX_4X4` early return: every mi cell of the
15185 // unit is marked 4x4 (raster order) without recursing.
15186 for row in 0..tx_h / MI {
15187 for col in 0..tx_w / MI {
15188 if blk_row + row < max_h_mi && blk_col + col < max_w_mi {
15189 out.push((blk_row + row, blk_col + col, 4, 4));
15190 }
15191 }
15192 }
15193 txfm_partition_update_rect(n, unit, (4, 4), (tx_w, tx_h));
15194 return;
15195 }
15196 for row in (0..tx_h / MI).step_by(sub_h / MI) {
15197 for col in (0..tx_w / MI).step_by(sub_w / MI) {
15198 read_var_tx_size(
15199 dec,
15200 cdfs,
15201 n,
15202 at_mi,
15203 blk_max_px,
15204 (max_w_mi, max_h_mi),
15205 (sub_w, sub_h),
15206 depth + 1,
15207 blk_row + row,
15208 blk_col + col,
15209 out,
15210 );
15211 }
15212 }
15213}
15214
15215/// `read_block_tx_size` (libaom `decodeframe.c` `parse_decode_block`'s tx
15216/// branch): every block of a `TxMode::Select` inter frame codes its transform
15217/// size right after its own mode info -- an inter non-skip block through the
15218/// recursive var-tx tree ([`read_var_tx_size`], whose leaf list this returns),
15219/// every other block through the intra `tx_depth` symbol (a skipped inter
15220/// block codes no symbol at all) plus a `set_txfm_ctxs` write. Returns the
15221/// block's own resolved transform side and the leaf list, the latter only
15222/// when the tree resolved to more than one transform unit.
15223#[allow(clippy::too_many_arguments)]
15224fn read_block_tx_size(
15225 dec: &mut SymbolDecoder,
15226 cdfs: &mut Cdfs,
15227 n: &mut Neighbours,
15228 at_mi: (usize, usize),
15229 side: usize,
15230 (mi_cols, mi_rows): (usize, usize),
15231 is_inter: bool,
15232 skip: bool,
15233) -> Result<(usize, Option<Vec<(usize, usize, usize, usize)>>)> {
15234 if !TX_SELECT_INTER.with(std::cell::Cell::get) {
15235 // lane-sb128c r1: `max_txsize_rect_lookup[BLOCK_128X128]` is TX_64X64,
15236 // so a 128x128 inter block is FOUR luma units even with `tx_mode ==
15237 // TX_MODE_LARGEST` -- the same leaf shape the var-tx tree hands back.
15238 // lane-sb128c r3: intra too -- an INTRA 128x128 block under
15239 // `TX_MODE_LARGEST` also resolves to TX_64X64, i.e. four luma units.
15240 if side > 64 {
15241 let step = 64 / MI;
15242 let mut leaves = Vec::new();
15243 for row in (0..side / MI).step_by(step) {
15244 for col in (0..side / MI).step_by(step) {
15245 leaves.push((row, col, 64, 64));
15246 }
15247 }
15248 return Ok((64, Some(leaves)));
15249 }
15250 return Ok((side, None));
15251 }
15252 let side_mi = side / MI;
15253 if is_inter && !skip {
15254 let max_tx = side.min(64);
15255 let max_w_mi = side_mi.min(mi_cols.saturating_sub(at_mi.1));
15256 let max_h_mi = side_mi.min(mi_rows.saturating_sub(at_mi.0));
15257 let mut leaves = Vec::new();
15258 let step = max_tx / MI;
15259 for row in (0..side_mi).step_by(step) {
15260 for col in (0..side_mi).step_by(step) {
15261 read_var_tx_size(
15262 dec,
15263 cdfs,
15264 n,
15265 at_mi,
15266 side,
15267 (max_w_mi, max_h_mi),
15268 (max_tx, max_tx),
15269 0,
15270 row,
15271 col,
15272 &mut leaves,
15273 );
15274 }
15275 }
15276 let single = leaves.len() == 1 && leaves[0].2 == side && leaves[0].3 == side;
15277 // lane-sb128c r6: below the 128 root the ceiling is main's TX_32X32
15278 // ([`inter_txbset_for`] has no 64-point *inter* table set); a 128x128
15279 // block's own var-tx tree legitimately bottoms out at TX_64X64 leaves,
15280 // which the mu-chunk reader above codes as their 32x32 coded corner.
15281 let leaf_ceiling = if side > 64 { 64 } else { 32 };
15282 if !single && leaves.iter().any(|leaf| leaf.2.max(leaf.3) > leaf_ceiling) {
15283 // Only a block wider than a superblock's own 64x64 max transform
15284 // reaches here; this crate has no 64-point *inter* coefficient
15285 // table set ([`inter_txbset_for`] stops at 32).
15286 return Err(unsupported(
15287 "an inter var-tx tree with a leaf transform larger than 32x32",
15288 ));
15289 }
15290 let resolved = leaves.last().map_or(side, |l| l.2);
15291 return Ok((resolved, (!single).then_some(leaves)));
15292 }
15293 let tx = if is_inter {
15294 side.min(64)
15295 } else {
15296 read_tx_size(
15297 dec,
15298 cdfs,
15299 n,
15300 at_mi,
15301 side,
15302 // lane-sb128c r3: `get_tx_size_context` compares the neighbour txfm
15303 // contexts against `tx_size_wide[max_txsize_rect_lookup[bsize]]`,
15304 // which is 64 for BLOCK_128X128 -- never the block's own 128 side.
15305 Some(tx_size_context_txfm(n, at_mi, side.min(64))),
15306 )
15307 };
15308 set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter);
15309 if !is_inter && tx != side {
15310 // lane-intrainter r1: an intra block inside an inter frame whose
15311 // `tx_depth` split its luma transform codes exactly the key-frame
15312 // split path's transform units (`decode_block`'s multi-TU loop),
15313 // raster order over the block. Handed back in the same leaf shape the
15314 // inter var-tx tree uses, so the caller's per-TU luma loop, the
15315 // `record_split_luma` neighbour write-back and the per-TU deblock
15316 // edges are the ones it already runs for a var-tx inter block. A
15317 // caller that has no per-TU intra loop (the 8x8 leaf) refuses on
15318 // seeing `Some` here.
15319 let step = tx / MI;
15320 let mut leaves = Vec::new();
15321 for row in (0..side_mi).step_by(step) {
15322 for col in (0..side_mi).step_by(step) {
15323 leaves.push((row, col, tx, tx));
15324 }
15325 }
15326 INTRA_IN_INTER_SPLIT_TX_HITS.with(|c| {
15327 let mut h = c.get();
15328 h[(side.trailing_zeros() as usize).saturating_sub(3).min(3)] += 1;
15329 c.set(h);
15330 });
15331 return Ok((tx, Some(leaves)));
15332 }
15333 Ok((tx, None))
15334}
15335
15336/// lane-inter4 r2: the shapes whose *rectangular inter* residual this
15337/// decoder codes -- a 2:1 strip whose own max rect transform
15338/// (`max_txsize_rect_lookup[BLOCK_32X16] == TX_32X16`) has both a
15339/// coefficient table set ([`TxbSet::LumaRect32x16Inter`], 512-coefficient
15340/// `eob_pt`) and a `tx_type` alphabet here. 64x32/64x16 strips would need a
15341/// 64-point rect transform, and 16x8/8x16 needs
15342/// `default_inter_ext_tx_cdf[2][TX_8X8]` (the 12-symbol
15343/// `DTT9_IDTX_1DDCT` row at `tx_size_sqr == TX_8X8`, only reachable through a
15344/// rect transform), neither of which exists yet -- both stay refused by name.
15345pub(crate) fn rect_inter_residual_supported(w: usize, h: usize) -> bool {
15346 matches!(
15347 (w, h),
15348 // 2:1 strips whose transform is coded in full (lane-inter4).
15349 (32, 16) | (16, 32) | (16, 8) | (8, 16)
15350 // lane-inter16ab r2: the 16x16-level 1:4 strips. TX_16X4/TX_4X16
15351 // codes all 64 of its positions, and its chroma pair is an 8x4 /
15352 // 4x8 unit (`ss_size_lookup[BLOCK_16X4]` = BLOCK_8X4).
15353 | (16, 4) | (4, 16)
15354 // lane-r14 r2: strips with a 64-px axis. `av1_get_max_eob` codes
15355 // only the low 32 coefficients of a 64-length axis, so these read
15356 // exactly the truncated corner the INTRA superblock-strip path
15357 // already reads (`read_intra_mode_rect`), through
15358 // `av1_get_adjusted_tx_size`'s CDF set. Their `tx_size_sqr_up` is
15359 // `TX_64X64`, so `av1_get_ext_tx_set_type` is `DCT_ONLY` and no
15360 // `tx_type` symbol is coded at all.
15361 | (64, 32) | (32, 64) | (64, 16) | (16, 64)
15362 // lane-inter16ab r4: `sub_tx_size_map[TX_16X4] == TX_8X4`, so a
15363 // split-transform 16x4/4x16 strip has RECTANGULAR 8x4/4x8 leaves.
15364 // Only reachable as a var-tx LEAF -- an 8x4/4x8 inter BLOCK is
15365 // refused earlier ("an inter partition below 8x8").
15366 | (8, 4) | (4, 8)
15367 // lane-sb128c r7: the 128 root's HORZ/VERT halves. These are NOT
15368 // one rectangular transform -- `max_txsize_rect_lookup
15369 // [BLOCK_128X64]` is TX_64X64, so the block tiles into two square
15370 // TX_64X64 units read through the mu-chunk loop, same as the
15371 // 128x128 NONE block's four.
15372 | (128, 64) | (64, 128)
15373 // lane-rectres r1: the 32x32-level 1:4 strips -- THE shape both
15374 // 10-bit film cuts and every measured 1080p offset stop on
15375 // (measured: 6/6 probes refuse at 32x8 or 8x32, nothing else).
15376 // `max_txsize_rect_lookup[BLOCK_32X8] == TX_32X8` codes all 256
15377 // positions, and its chroma pair is a 16x4 / 4x16 unit
15378 // (`ss_size_lookup[BLOCK_32X8]` = BLOCK_16X4).
15379 | (32, 8) | (8, 32)
15380 )
15381}
15382
15383// lane-t900 r20: the `(side, write_w, write_h)` triples the inter block path
15384// actually PRESENTS, as a thread-local bitmask -- the measured domain behind
15385// the "rectangular ... has no ... here" refusals. `side` is the square context
15386// a block reads its CDFs at and `write_w`/`write_h` its true footprint;
15387// `inter_piece!` derives `reject_residual` from exactly that inequality, so
15388// these triples are what decides whether those refusals can fire at all. Bit
15389// 31 is "a triple this table does not list", which is what makes the gate a
15390// census rather than a restatement of its own table.
15391pub(crate) const INTER_BLOCK_SHAPES: [(usize, usize, usize); 18] = [
15392 (16, 16, 16),
15393 (32, 32, 32),
15394 (32, 16, 32),
15395 (32, 32, 16),
15396 (16, 8, 16),
15397 (16, 16, 8),
15398 (32, 8, 32),
15399 (64, 64, 64),
15400 (32, 32, 8),
15401 (64, 16, 64),
15402 (128, 128, 128),
15403 (64, 32, 64),
15404 (64, 64, 32),
15405 (16, 4, 16),
15406 (64, 64, 16),
15407 (16, 16, 4),
15408 (128, 128, 64),
15409 (128, 64, 128),
15410];
15411
15412/// Bit 31 of [`inter_block_shape_mask`]: a `(side, write_w, write_h)` triple
15413/// outside [`INTER_BLOCK_SHAPES`].
15414pub const INTER_BLOCK_SHAPE_UNLISTED: u32 = 1 << 31;
15415
15416thread_local! {
15417 static INTER_BLOCK_SHAPE_MASK: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
15418}
15419
15420/// Which of [`INTER_BLOCK_SHAPES`] this THREAD has decoded (thread-local, so a
15421/// gate reading it sees only the streams it decoded itself).
15422pub fn inter_block_shape_mask() -> u32 {
15423 INTER_BLOCK_SHAPE_MASK.with(std::cell::Cell::get)
15424}
15425
15426/// Records one block's shape. The table is ordered by measured frequency over
15427/// the three witnesses the census gate decodes, so the common square shapes
15428/// leave the scan on their first comparison.
15429fn census_inter_block_shape(side: usize, w: usize, h: usize) {
15430 let bit = match INTER_BLOCK_SHAPES.iter().position(|&s| s == (side, w, h)) {
15431 Some(i) => 1u32 << i,
15432 None => INTER_BLOCK_SHAPE_UNLISTED,
15433 };
15434 let seen = inter_block_shape_mask();
15435 if seen & bit == 0 {
15436 INTER_BLOCK_SHAPE_MASK.with(|c| c.set(seen | bit));
15437 }
15438}
15439
15440/// The luma coefficient/`tx_type` table set of a whole-block rectangular
15441/// INTER transform unit (lane-inter4 r3). `av1_get_ext_tx_set_type` splits
15442/// the two shapes: a 32x16/16x32 unit has `tx_size_sqr_up == TX_32X32`, so
15443/// it reads the 2-symbol `EXT_TX_SET_DCT_IDTX` set regardless of
15444/// `reduced_tx_set`; a 16x8/8x16 unit has `tx_size_sqr_up == TX_16X16` and
15445/// `tx_size_sqr == TX_8X8`, so it reads `EXT_TX_SET_DCT_IDTX` when reduced
15446/// and the 16-symbol `EXT_TX_SET_ALL16` otherwise -- both at the *8x8* CDF
15447/// row (`txsize_sqr_map`), never the 16x16 one.
15448fn rect_inter_luma_set(w: usize, h: usize) -> Result<TxbSet> {
15449 Ok(match (w, h) {
15450 (32, 16) | (16, 32) => TxbSet::LumaRect32x16Inter,
15451 // lane-inter16ab r4: the 8x4/4x8 split leaf of a 16x4/4x16 strip.
15452 // `av1_get_ext_tx_set_type` (blockd.h:1097) at `tx_size_sqr_up ==
15453 // TX_8X8`, `tx_size_sqr == TX_4X4`, inter: DCT_IDTX when reduced,
15454 // ALL16 otherwise -- both at the TX_4X4 row.
15455 (8, 4) | (4, 8) => {
15456 if REDUCED_TX_SET_INTER.with(std::cell::Cell::get) {
15457 TxbSet::LumaRect8x4Inter
15458 } else {
15459 TxbSet::LumaRect8x4InterSet1
15460 }
15461 }
15462 (16, 4) | (4, 16) => {
15463 if REDUCED_TX_SET_INTER.with(std::cell::Cell::get) {
15464 TxbSet::LumaRect16x4Inter
15465 } else {
15466 TxbSet::LumaRect16x4Inter1
15467 }
15468 }
15469 (16, 8) | (8, 16) => {
15470 if REDUCED_TX_SET_INTER.with(std::cell::Cell::get) {
15471 TxbSet::LumaRect16x8Inter
15472 } else {
15473 TxbSet::LumaRect16x8InterSet1
15474 }
15475 }
15476 // lane-r14 r2: `av1_get_adjusted_tx_size` maps TX_64X32/TX_32X64 to
15477 // TX_32X32 and TX_64X16/TX_16X64 to TX_32X16/TX_16X32, and
15478 // `get_txsize_entropy_ctx`/`txsize_log2_minus4` agree with the
15479 // adjusted size, so the existing sets are bit-exact. Neither carries a
15480 // `tx_type` table (DCT_ONLY above), so the intra/inter split is moot.
15481 // lane-rectres r1: `tx_size_sqr_up[TX_32X8] == TX_32X32`, so
15482 // `av1_get_ext_tx_set_type` is `EXT_TX_SET_DCT_IDTX` for inter with or
15483 // without `reduced_tx_set` -- one set, no `REDUCED_TX_SET_INTER`
15484 // branch, read at the `txsize_sqr_map[TX_32X8] == TX_8X8` row.
15485 (32, 8) | (8, 32) => TxbSet::LumaRect32x8Inter,
15486 (64, 32) | (32, 64) => TxbSet::Luma64,
15487 (64, 16) | (16, 64) => TxbSet::LumaRect32x16,
15488 _ => {
15489 return Err(unsupported(
15490 "a rectangular inter luma transform unit whose shape has no coefficient table set here",
15491 ));
15492 }
15493 })
15494}
15495
15496/// The chroma table set of the same block's single rectangular chroma unit
15497/// (`av1_get_max_uv_txsize`): 16x8/8x16 under a 32x16/16x32 strip, 8x4/4x8
15498/// under a 16x8/8x16 one. Neither codes a `tx_type` symbol -- both inherit
15499/// the luma unit's.
15500fn rect_inter_chroma_set(w: usize, h: usize) -> Result<TxbSet> {
15501 Ok(match (w, h) {
15502 (16, 8) | (8, 16) => TxbSet::ChromaRect16x8,
15503 (8, 4) | (4, 8) => TxbSet::ChromaRect8x4,
15504 // lane-r14 r2: chroma of a 64-axis strip -- 32x16/16x32 under a
15505 // 64x32/32x64 one, 32x8/8x32 under a 64x16/16x64 one. Neither chroma
15506 // unit has a 64-px axis, so both are coded in full; `Chroma16` is the
15507 // exact set for TX_32X8/TX_8X32 (`get_txsize_entropy_ctx` = TX_16X16,
15508 // `txsize_log2_minus4` = 4), same as the intra strip path uses.
15509 (32, 16) | (16, 32) => TxbSet::ChromaRect32x16,
15510 (32, 8) | (8, 32) => TxbSet::Chroma16,
15511 // lane-rectres r1: chroma of a 32x8/8x32 strip. `Chroma8` is the exact
15512 // set for TX_16X4/TX_4X16 (`get_txsize_entropy_ctx` = TX_8X8,
15513 // `txsize_log2_minus4` = 2, 64-coefficient `eob_pt`).
15514 (16, 4) | (4, 16) => TxbSet::Chroma8,
15515 _ => {
15516 return Err(unsupported(
15517 "a rectangular inter chroma transform unit whose shape has no coefficient table set here",
15518 ));
15519 }
15520 })
15521}
15522
15523/// libaom `size_group_lookup[bsize]` for the block shapes this decoder's
15524/// inter path reaches, from the block's TRUE footprint rather than the
15525/// square `side` corner-cut: 8x8/8x16/16x8 -> 1, 16x16/16x32/32x16 -> 2,
15526/// everything 32 and above -> 3.
15527fn size_group_wh(w: usize, h: usize) -> usize {
15528 // lane-inter4 r4: `size_group_lookup[BLOCK_SIZES_ALL]` (libaom
15529 // `common_data.h:60`) is 0 for every block with a 4-px side
15530 // (4x4/4x8/8x4/4x16/16x4), 1 for min side 8, 2 for 16, 3 above -- the old
15531 // `0..=8 => 1` row gave a sub-8 leaf group 1 where libaom says 0.
15532 match w.min(h) {
15533 0..=4 => 0,
15534 8 => 1,
15535 16 => 2,
15536 _ => 3,
15537 }
15538}
15539
15540#[test]
15541fn size_group_wh_matches_libaom_size_group_lookup() {
15542 // `BLOCK_SIZES_ALL` in libaom's own order, with `size_group_lookup`'s
15543 // transcribed values (common_data.h:60-62).
15544 const TABLE: [((usize, usize), usize); 22] = [
15545 ((4, 4), 0), ((4, 8), 0), ((8, 4), 0), ((8, 8), 1), ((8, 16), 1), ((16, 8), 1),
15546 ((16, 16), 2), ((16, 32), 2), ((32, 16), 2), ((32, 32), 3), ((32, 64), 3),
15547 ((64, 32), 3), ((64, 64), 3), ((64, 128), 3), ((128, 64), 3), ((128, 128), 3),
15548 ((4, 16), 0), ((16, 4), 0), ((8, 32), 1), ((32, 8), 1), ((16, 64), 2), ((64, 16), 2),
15549 ];
15550 for ((w, h), want) in TABLE {
15551 assert_eq!(size_group_wh(w, h), want, "size_group_wh({w}, {h})");
15552 }
15553}
15554
15555/// The default (2D) coefficient scan of a rectangular transform.
15556fn rect_scan(w: usize, h: usize) -> Result<&'static [u16]> {
15557 Ok(match (w, h) {
15558 (32, 16) => &SCAN_32X16,
15559 (16, 32) => &SCAN_16X32,
15560 (16, 8) => &SCAN_16X8,
15561 (8, 16) => &SCAN_8X16,
15562 (16, 4) => &SCAN_16X4,
15563 (4, 16) => &SCAN_4X16,
15564 (8, 4) => &SCAN_8X4,
15565 (4, 8) => &SCAN_4X8,
15566 (32, 8) => &SCAN_32X8,
15567 (8, 32) => &SCAN_8X32,
15568 _ => {
15569 return Err(unsupported(
15570 "a rectangular transform unit whose shape has no coefficient scan table here",
15571 ));
15572 }
15573 })
15574}
15575
15576/// lane-t900 r20, refusal D -- the three "a rectangular inter luma/chroma
15577/// transform unit whose shape has no coefficient table set here" / "a
15578/// rectangular transform unit whose shape has no coefficient scan table here"
15579/// arms, enumerated against the MEASURED domain of the inter block path
15580/// ([`INTER_BLOCK_SHAPES`], filled from three real streams by the gate
15581/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`).
15582///
15583/// What each helper is actually handed:
15584///
15585/// * [`rect_inter_luma_set`] -- the block's own footprint (call sites at the
15586/// whole-block residual), and a var-tx LEAF shape. `sub_tx_size_map` is
15587/// square for every rect transform except TX_16X4/TX_4X16, whose leaves are
15588/// TX_8X4/TX_4X8, so the leaf domain adds exactly 8x4 and 4x8.
15589/// * [`rect_inter_chroma_set`] -- `(write_w / 2, write_h / 2)` for a 4:2:0
15590/// block, except a 16x4/4x16 strip, whose chroma is the PAIR's 8x4 / 4x8.
15591/// * [`rect_scan`] -- the `min(w, 32) x min(h, 32)` coded corner of a rect
15592/// unit, and only when that corner is not 32x32 (a square corner goes
15593/// through the square reader with `rect_shape = Some((w, h))`).
15594///
15595/// The 128-px halves take neither: `max_txsize_rect_lookup[BLOCK_128X64]` is
15596/// TX_64X64, so they tile into SQUARE 64x64 luma units through the mu-chunk
15597/// loop, which is why they are skipped below.
15598#[test]
15599fn every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan() {
15600 let corner_scan = |w: usize, h: usize| {
15601 let (cw, ch) = (w.min(32), h.min(32));
15602 if (cw, ch) == (32, 32) {
15603 return; // the square coefficient reader, not `rect_scan`
15604 }
15605 assert!(
15606 rect_scan(cw, ch).is_ok(),
15607 "a {w}x{h} rect transform codes its {cw}x{ch} corner, which has no scan table"
15608 );
15609 };
15610 let mut checked = 0;
15611 for &(side, w, h) in &INTER_BLOCK_SHAPES {
15612 if (w, h) == (side, side) || w.max(h) > 64 {
15613 continue;
15614 }
15615 assert!(
15616 rect_inter_luma_set(w, h).is_ok(),
15617 "the inter path decodes {w}x{h} blocks but has no luma coefficient table set for one"
15618 );
15619 corner_scan(w, h);
15620 // 4:2:0 chroma: the pair's 8x4 / 4x8 for a 1:4 strip, the halved
15621 // footprint for every other shape.
15622 let (cw, ch) = match (w, h) {
15623 (16, 4) => (8, 4),
15624 (4, 16) => (4, 8),
15625 _ => (w / 2, h / 2),
15626 };
15627 assert!(
15628 rect_inter_chroma_set(cw, ch).is_ok(),
15629 "a {w}x{h} block's {cw}x{ch} chroma unit has no coefficient table set"
15630 );
15631 corner_scan(cw, ch);
15632 checked += 1;
15633 }
15634 assert_eq!(
15635 checked, 12,
15636 "the block-shape census changed: {checked} rect shapes reach the rect transform \
15637 tables, not the 12 this claim was measured over"
15638 );
15639 // `sub_tx_size_map[TX_16X4] == TX_8X4` -- the only RECTANGULAR var-tx leaf
15640 // shapes, which reach `rect_inter_luma_set` as `(tw, th)`.
15641 for (w, h) in [(8usize, 4usize), (4, 8)] {
15642 assert!(
15643 rect_inter_luma_set(w, h).is_ok(),
15644 "the {w}x{h} split leaf of a 16x4/4x16 strip has no luma coefficient table set"
15645 );
15646 corner_scan(w, h);
15647 }
15648}
15649
15650/// [`read_block_tx_size`] for a rectangular inter block (lane-inter4 r2):
15651/// spec 5.11.17 / libaom `read_tx_size_vartx` starting from the block's own
15652/// `max_txsize_rect_lookup` entry, which for a 2:1 strip IS rectangular. The
15653/// depth-0 `txfm_partition` symbol reads its context off the rect transform's
15654/// own width/height; a `0` leaves one whole-block rect transform unit
15655/// (`None`), and a `1` splits it into `sub_tx_size_map`'s two SQUARE
15656/// sub-transforms (`sub_tx_size_map[TX_32X16] == TX_16X16`), from which the
15657/// ordinary square [`read_var_tx_size`] recursion continues at depth 1 -- so
15658/// every leaf of a split rect block is square and the existing square leaf
15659/// loop reconstructs it unchanged.
15660#[allow(clippy::too_many_arguments)]
15661fn read_block_tx_size_rect(
15662 dec: &mut SymbolDecoder,
15663 cdfs: &mut Cdfs,
15664 n: &mut Neighbours,
15665 at_mi: (usize, usize),
15666 (bw, bh): (usize, usize),
15667 (mi_cols, mi_rows): (usize, usize),
15668 skip: bool,
15669) -> Result<Option<Vec<(usize, usize, usize, usize)>>> {
15670 if skip {
15671 // `set_txfm_ctxs(.., skip && is_inter)`: a skipped inter block records
15672 // its own BLOCK size -- width above, height left -- not a transform.
15673 txfm_partition_update_rect(n, at_mi, (bw, bh), (bw, bh));
15674 return Ok(None);
15675 }
15676 // `max_txsize_rect_lookup` is the block's own size, capped at 64 -- and
15677 // `rect_inter_residual_supported` has already excluded everything above 32.
15678 // lane-sb128c r7: except at the 128 root. `max_txsize_rect_lookup
15679 // [BLOCK_128X64] == TX_64X64` (libaom `common_data.h`), so a 128x64 block
15680 // is TWO square top-level transform units side by side and a 64x128 one is
15681 // two stacked -- exactly what libaom `read_block_tx_size`
15682 // (decodeframe.c:1140) codes with its `idy/idx` loop over
15683 // `tx_size_high_unit/tx_size_wide_unit[max_tx_size]`. Each unit reads its
15684 // own `txfm_partition` symbol at depth 0.
15685 if bw.max(bh) > 64 {
15686 let tx = 64usize;
15687 let (max_w_mi, max_h_mi) = (
15688 (bw / MI).min(mi_cols.saturating_sub(at_mi.1)),
15689 (bh / MI).min(mi_rows.saturating_sub(at_mi.0)),
15690 );
15691 let mut leaves = Vec::new();
15692 if !TX_SELECT_INTER.with(std::cell::Cell::get) {
15693 for row in (0..bh / MI).step_by(tx / MI) {
15694 for col in (0..bw / MI).step_by(tx / MI) {
15695 leaves.push((row, col, tx, tx));
15696 }
15697 }
15698 for &(row, col, tw, th) in &leaves {
15699 txfm_partition_update_rect(n, (at_mi.0 + row, at_mi.1 + col), (tw, th), (tw, th));
15700 }
15701 return Ok(Some(leaves));
15702 }
15703 for row in (0..bh / MI).step_by(tx / MI) {
15704 for col in (0..bw / MI).step_by(tx / MI) {
15705 read_var_tx_size(
15706 dec,
15707 cdfs,
15708 n,
15709 at_mi,
15710 bw.max(bh),
15711 (max_w_mi, max_h_mi),
15712 (tx, tx),
15713 0,
15714 row,
15715 col,
15716 &mut leaves,
15717 );
15718 }
15719 }
15720 if leaves.iter().any(|l| l.2.max(l.3) > 64) {
15721 return Err(unsupported(
15722 "an inter var-tx tree with a leaf transform larger than 64x64",
15723 ));
15724 }
15725 return Ok(Some(leaves));
15726 }
15727 let (tx_w, tx_h) = (bw, bh);
15728 if !TX_SELECT_INTER.with(std::cell::Cell::get) {
15729 // `TX_MODE_LARGEST`: no symbol at all, the whole block is one
15730 // transform, and `set_txfm_ctxs` records exactly what
15731 // `txfm_partition_update` would for that same unit.
15732 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
15733 RECT_INTER_TU_HITS.with(|c| c.set(c.get() + 1));
15734 return Ok(None);
15735 }
15736 let ctx = txfm_partition_ctx_rect(
15737 n.above_txfm[at_mi.1],
15738 n.left_txfm[at_mi.0],
15739 bw.max(bh),
15740 tx_w,
15741 tx_h,
15742 );
15743 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
15744 TXFM_SPLIT_READS.with(|c| c.set(c.get() + 1));
15745 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
15746 let (rng, _) = dec.debug_state();
15747 eprintln!(
15748 "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}",
15749 at_mi.0,
15750 at_mi.1,
15751 u8::from(split)
15752 );
15753 }
15754 if !split {
15755 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
15756 RECT_INTER_TU_HITS.with(|c| c.set(c.get() + 1));
15757 return Ok(None);
15758 }
15759 TXFM_SPLIT_HITS.with(|c| c.set(c.get() + 1));
15760 RECT_INTER_TXSPLIT_HITS.with(|c| c.set(c.get() + 1));
15761 // lane-r14 r3: `sub_tx_size_map` (libaom `common_data.c`) stays
15762 // RECTANGULAR under a 1:4 strip -- `[TX_64X16] == TX_32X16`,
15763 // `[TX_16X64] == TX_16X32` -- so the recursion below is the general
15764 // rect one and its leaves carry their own width and height.
15765 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
15766 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(at_mi.1));
15767 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(at_mi.0));
15768 let mut leaves = Vec::new();
15769 for row in (0..bh / MI).step_by(sub_h / MI) {
15770 for col in (0..bw / MI).step_by(sub_w / MI) {
15771 read_var_tx_size(
15772 dec,
15773 cdfs,
15774 n,
15775 at_mi,
15776 bw.max(bh),
15777 (max_w_mi, max_h_mi),
15778 (sub_w, sub_h),
15779 1,
15780 row,
15781 col,
15782 &mut leaves,
15783 );
15784 }
15785 }
15786 Ok(Some(leaves))
15787}
15788
15789/// [`read_inter_plane`] for a rectangular transform unit (lane-inter4 r2):
15790/// the coefficients are read with the rect coefficient machinery
15791/// ([`read_coeffs_rect`], whose `TxClass` handling covers the 1D `V_*`/`H_*`
15792/// types), inverted with the rect inverse transform
15793/// ([`dequant_and_inverse_typed_wh`], which carries the 2:1 `sqrt2` scale),
15794/// and added onto the top-left `w x h` of the block's own square-strided
15795/// motion-compensated prediction buffer. Returns the *rect* coefficient grid
15796/// and the coded `tx_type`.
15797///
15798/// `txb_skip_ctx` is 0 for luma: this unit covers the whole block, i.e.
15799/// `get_txb_ctx`'s `plane_bsize == txsize_to_bsize[tx_size]` branch.
15800#[allow(clippy::too_many_arguments)]
15801fn read_inter_plane_rect(
15802 dec: &mut SymbolDecoder,
15803 cdfs: &mut Cdfs,
15804 set: TxbSet,
15805 (w, h): (usize, usize),
15806 stride: usize,
15807 plane_idx: usize,
15808 around: (bool, bool, i32),
15809 tx_mode: usize,
15810 plane: &mut PlaneBuf,
15811 x: usize,
15812 y: usize,
15813 prediction: &[u16],
15814 inherited_luma_tx_type: Option<TxType>,
15815 luma_skip_ctx: Option<usize>,
15816) -> Result<(Vec<i32>, TxType)> {
15817 let skip_ctx = if plane_idx == 0 {
15818 // `get_txb_ctx_general`: 0 only when this unit IS the whole plane
15819 // block; a var-tx leaf passes its own neighbour-table context.
15820 luma_skip_ctx.unwrap_or(0)
15821 } else {
15822 usize::from(around.0) + usize::from(around.1)
15823 };
15824 let mut coding = cdfs.txb(set, tx_mode);
15825 // `av1_get_ext_tx_set_type`'s DCT-only clamp is on `tx_size_sqr_up`, i.e.
15826 // the *longer* side of this rect transform.
15827 let default_tx_type = match inherited_luma_tx_type {
15828 Some(t) => reduce_inherited_chroma_tx_type(t, w, h),
15829 None => TxType::DctDct,
15830 };
15831 // lane-r14 r2: a 64-length axis codes only its low 32 coefficients
15832 // (`av1_get_max_eob`), so the coded unit is the `min(w,32) x min(h,32)`
15833 // corner, zero-extended into the true `w x h` grid before the inverse
15834 // transform -- exactly what the intra superblock-strip path does. A
15835 // corner that comes out square (32x32, under a 64x32/32x64 strip) reads
15836 // through the SQUARE coefficient reader with `rect_shape = Some((w, h))`,
15837 // because `av1_nz_map_ctx_offset` is indexed by the real, un-adjusted
15838 // rectangular shape (lane-sbpart r8).
15839 let (cw, ch) = (w.min(32), h.min(32));
15840 if plane_idx == 0 && w.max(h) == 64 {
15841 RECT64_INTER_TU_HITS.with(|c| c.set(c.get() + 1));
15842 }
15843 if plane_idx == 0 && (w, h) == (32, 8) || plane_idx == 0 && (w, h) == (8, 32) {
15844 RECT32X8_INTER_TU_HITS.with(|c| {
15845 let mut v = c.get();
15846 v[usize::from(w == 8)] += 1;
15847 c.set(v);
15848 });
15849 }
15850 let (corner, tx_type) = if (cw, ch) == (32, 32) {
15851 let scan32 = default_scan(TX32);
15852 read_coeffs(
15853 dec,
15854 &mut coding,
15855 &scan32,
15856 skip_ctx,
15857 dc_sign_ctx(around.2),
15858 default_tx_type,
15859 Some((w, h)),
15860 )?
15861 } else {
15862 read_coeffs_rect(
15863 dec,
15864 &mut coding,
15865 rect_scan(cw, ch)?,
15866 cw,
15867 ch,
15868 skip_ctx,
15869 dc_sign_ctx(around.2),
15870 default_tx_type,
15871 )?
15872 };
15873 let grid = if (cw, ch) == (w, h) {
15874 corner
15875 } else {
15876 let mut full = vec![0i32; w * h];
15877 for row in 0..ch {
15878 full[row * w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
15879 }
15880 full
15881 };
15882 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
15883 let residual = dequant_and_inverse_typed_wh(
15884 &grid,
15885 w,
15886 h,
15887 bit_depth(),
15888 block_q_idx(),
15889 dc_delta,
15890 ac_delta,
15891 tx_type,
15892 );
15893 if crate::envflags::env_flag!("EC_TRACE_TXTYPE") {
15894 eprintln!("OUR_TXTYPE plane={plane_idx} x={x} y={y} w={w} h={h} tx_type={tx_type:?} inh={inherited_luma_tx_type:?}");
15895 }
15896 // `reconstruct_mc_rect` reads both buffers at the square prediction
15897 // stride, so the dense `w x h` residual is re-laid at that stride first.
15898 let mut strided = vec![0i32; stride * stride];
15899 for row in 0..h {
15900 strided[row * stride..][..w].copy_from_slice(&residual[row * w..][..w]);
15901 }
15902 plane.reconstruct_mc_rect(x, y, stride, w, h, prediction, &strided);
15903 Ok((grid, tx_type))
15904}
15905
15906/// A rect coefficient grid re-laid into the square `stride x stride` grid the
15907/// neighbour/deblock stamps downstream of the residual expect.
15908fn embed_rect_grid(grid: &[i32], w: usize, h: usize, stride: usize) -> Vec<i32> {
15909 let mut full = vec![0i32; stride * stride];
15910 for row in 0..h {
15911 full[row * stride..][..w].copy_from_slice(&grid[row * w..][..w]);
15912 }
15913 full
15914}
15915
15916/// One 8x8 inter leaf's luma residual (lane-txselect): either the whole-8x8
15917/// transform, or -- when [`read_block_tx_size`]'s var-tx tree took the single
15918/// split a `BLOCK_8X8` can take (`split`) -- the four 4x4 transform units in
15919/// raster order, each reading its own coefficient context off the units
15920/// already decoded before it. Returns the block's luma grid (all-zero in the
15921/// split case, whose reconstruction has already happened unit by unit) and
15922/// the `tx_type` chroma inherits: `av1_get_tx_type`'s colocated luma lookup,
15923/// which for a split block lands on the top-left unit.
15924#[allow(clippy::too_many_arguments)]
15925fn read_inter_luma8(
15926 dec: &mut SymbolDecoder,
15927 cdfs: &mut Cdfs,
15928 neighbours: &mut Neighbours,
15929 leaf_mi: (usize, usize),
15930 y: &mut PlaneBuf,
15931 px: usize,
15932 py: usize,
15933 pred_y: &[u16],
15934 mode_for_tx: usize,
15935 base_q_idx: u8,
15936 scan8: &[u16],
15937 scan4: &[u16],
15938 reduced_tx_set: bool,
15939 split: bool,
15940) -> Result<(Vec<i32>, TxType)> {
15941 if !split {
15942 return read_inter_plane(
15943 dec,
15944 cdfs,
15945 if reduced_tx_set {
15946 TxbSet::Luma8Inter
15947 } else {
15948 TxbSet::Luma8InterSet1
15949 },
15950 scan8,
15951 0,
15952 neighbours.around_mi(leaf_mi, 8)[0],
15953 mode_for_tx,
15954 y,
15955 px,
15956 py,
15957 8,
15958 base_q_idx,
15959 pred_y,
15960 None,
15961 None,
15962 );
15963 }
15964 let mut first = TxType::DctDct;
15965 for tu_row in 0..2 {
15966 for tu_col in 0..2 {
15967 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
15968 let mut tu_pred = Vec::with_capacity(16);
15969 for rr in 0..4 {
15970 let start = (tu_row * 4 + rr) * 8 + tu_col * 4;
15971 tu_pred.extend_from_slice(&pred_y[start..start + 4]);
15972 }
15973 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
15974 let (tu_grid, tu_tx_type) = read_inter_plane(
15975 dec,
15976 cdfs,
15977 if reduced_tx_set {
15978 TxbSet::Luma4Inter
15979 } else {
15980 TxbSet::Luma4InterSet1
15981 },
15982 scan4,
15983 0,
15984 neighbours.around_mi(tu_mi, 4)[0],
15985 mode_for_tx,
15986 y,
15987 px + tu_col * 4,
15988 py + tu_row * 4,
15989 4,
15990 base_q_idx,
15991 &tu_pred,
15992 None,
15993 Some(tu_skip_ctx),
15994 )?;
15995 if tu_row == 0 && tu_col == 0 {
15996 first = tu_tx_type;
15997 }
15998 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
15999 }
16000 }
16001 Ok((vec![0i32; 64], first))
16002}
16003
16004/// The [`TxbSet`] one leaf of an inter block's var-tx tree reads its
16005/// coefficient tables from -- the inter counterpart of [`txbset_for`].
16006/// `av1_get_tx_type`'s chroma tail (libaom `av1/common/blockd.h:1291-1305`):
16007/// an inter block's chroma transform inherits the *colocated luma* unit's
16008/// coded `tx_type`, then drops back to `DCT_DCT` unless that type is a member
16009/// of the extended set the CHROMA transform size selects
16010/// (`av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)][tx_type]`,
16011/// `blockd.h:1036`/`1097`). lane-golomb r7: we used to force `DCT_DCT` at
16012/// every chroma side >= 32, but `av1_get_ext_tx_set_type`'s DCT-only rung is
16013/// `tx_size_sqr_up > TX_32X32`; at exactly TX_32X32 an inter block reads
16014/// `EXT_TX_SET_DCT_IDTX`, so a 64x64 inter block whose first luma leaf coded
16015/// `IDTX` inherits IDTX on its 32x32 chroma units. `IDTX` and `DCT_DCT` are
16016/// both `TX_CLASS_2D`, so that mistake left the entropy stream perfectly in
16017/// sync and only corrupted the inverse transform (one 64x64 superblock of
16018/// high-frequency chroma noise, luma bit-exact).
16019fn reduce_inherited_chroma_tx_type(t: TxType, w: usize, h: usize) -> TxType {
16020 use TxType::*;
16021 let sqr_up = w.max(h);
16022 let sqr = w.min(h);
16023 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
16024 // `av1_get_ext_tx_set_type(tx_size, is_inter = 1, reduced)`.
16025 let allowed: &[TxType] = if sqr_up > 32 {
16026 // EXT_TX_SET_DCTONLY
16027 &[DctDct]
16028 } else if sqr_up == 32 || reduced {
16029 // EXT_TX_SET_DCT_IDTX
16030 &[DctDct, Idtx]
16031 } else if sqr == 16 {
16032 // EXT_TX_SET_DTT9_IDTX_1DDCT -- TX_TYPES 0..=11, i.e. everything but
16033 // the four 1D ADST/FLIPADST types.
16034 &[
16035 DctDct, AdstDct, DctAdst, AdstAdst, FlipAdstDct, DctFlipAdst, FlipAdstFlipAdst,
16036 AdstFlipAdst, FlipAdstAdst, Idtx, VDct, HDct,
16037 ]
16038 } else {
16039 // EXT_TX_SET_ALL16
16040 return t;
16041 };
16042 if allowed.contains(&t) { t } else { DctDct }
16043}
16044
16045fn inter_txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
16046 match tx_px {
16047 // lane-sb128c r1: a 128x128 inter block's own luma unit
16048 // (`max_txsize_rect_lookup[BLOCK_128X128] == TX_64X64`).
16049 // `av1_get_ext_tx_set_type` is `DCT_ONLY` at `tx_size_sqr_up ==
16050 // TX_64X64`, so no `tx_type` symbol is coded and the intra/inter sets
16051 // coincide -- exactly the set the whole-64x64 inter block already uses.
16052 64 => TxbSet::Luma64,
16053 32 => TxbSet::Luma32Inter,
16054 16 if reduced_tx_set => TxbSet::Luma16Inter,
16055 16 => TxbSet::Luma16InterSet1,
16056 8 if reduced_tx_set => TxbSet::Luma8Inter,
16057 8 => TxbSet::Luma8InterSet1,
16058 4 if reduced_tx_set => TxbSet::Luma4Inter,
16059 4 => TxbSet::Luma4InterSet1,
16060 _ => unreachable!("a var-tx leaf is never wider than a 64x64 block's 32x32 sub-transform"),
16061 }
16062}
16063
16064/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
16065/// the only four sizes a `TxMode::Select` block's coded coefficient grid
16066/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
16067fn scan_for<'a>(
16068 tx_px: usize,
16069 scan32: &'a [u16],
16070 scan16: &'a [u16],
16071 scan8: &'a [u16],
16072 scan4: &'a [u16],
16073) -> &'a [u16] {
16074 match tx_px {
16075 32 => scan32,
16076 16 => scan16,
16077 8 => scan8,
16078 4 => scan4,
16079 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
16080 }
16081}
16082
16083/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
16084/// from -- 64 is only ever the 64x64-block, depth-0, corner-scanned case
16085/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
16086/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
16087/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
16088/// regardless of the flag (`av1_get_ext_tx_set_type`'s
16089/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
16090/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
16091/// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]).
16092/// [`txbset_for`], for a block libaom's `is_inter_block` calls inter -- which
16093/// an intrabc block is (`blockd.h:373`), so its `tx_type` comes off the
16094/// inter `ext_tx` sets, never the mode-indexed intra ones.
16095fn txbset_for_inter(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
16096 match tx_px {
16097 64 => TxbSet::Luma64,
16098 32 => TxbSet::Luma32Inter,
16099 16 if reduced_tx_set => TxbSet::Luma16Inter,
16100 16 => TxbSet::Luma16InterSet1,
16101 8 if reduced_tx_set => TxbSet::Luma8Inter,
16102 8 => TxbSet::Luma8InterSet1,
16103 _ => TxbSet::Luma64,
16104 }
16105}
16106
16107fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
16108 match tx_px {
16109 64 => TxbSet::Luma64,
16110 32 => TxbSet::Luma32,
16111 16 => TxbSet::Luma16,
16112 8 if reduced_tx_set => TxbSet::Luma8,
16113 8 => TxbSet::Luma8Set1,
16114 4 if reduced_tx_set => TxbSet::Luma4,
16115 4 => TxbSet::Luma4Set1,
16116 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
16117 }
16118}
16119
16120/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
16121/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
16122fn unit_log2(px: u32) -> i32 {
16123 if px == 0 {
16124 0
16125 } else {
16126 px.trailing_zeros() as i32 - 2
16127 }
16128}
16129
16130/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
16131/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
16132/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
16133/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
16134/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
16135/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
16136/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
16137/// block anywhere aborted the whole stream's decode before comparison).
16138fn lf_level(
16139 lf: &LoopFilterParams,
16140 plane_idx: usize,
16141 dir: usize,
16142 ref_frame: i8,
16143 delta_lf: i32,
16144 segment_id: u8,
16145) -> i32 {
16146 let base = i32::from(if plane_idx == 0 {
16147 lf.level[dir]
16148 } else if plane_idx == 1 {
16149 lf.level[2]
16150 } else {
16151 lf.level[3]
16152 });
16153 // spec 7.14.4: the per-superblock `DeltaLF` term applies before the
16154 // ref/mode delta scaling below, and regardless of `delta_enabled`
16155 // (that flag only gates `ref_deltas`/`mode_deltas`).
16156 let base = (base + delta_lf).clamp(0, 63);
16157 // lane-seg, spec 7.14.4 / libaom `av1_loop_filter_frame_init`: this
16158 // block's segment's own `SEG_LVL_ALT_LF_*` delta applies after the
16159 // per-superblock `DeltaLF` term and before the ref/mode deltas below.
16160 // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4)
16161 // for chroma.
16162 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
16163 // lane-perf9: `segment_id` is `0` and this lookup is skipped entirely
16164 // when the frame codes no segmentation (`seg_lf_active`), which is what
16165 // spares the deblock loop two thread-local reads per 4x4 edge.
16166 let base = match seg_feature(usize::from(segment_id), feature) {
16167 Some(data) => (base + data).clamp(0, 63),
16168 None => base,
16169 };
16170 if !lf.delta_enabled {
16171 return base;
16172 }
16173 let scale = 1i32 << (base >> 5);
16174 let is_inter = ref_frame != 0;
16175 let is_globalmv = ref_frame < 0;
16176 let ref_idx = ref_frame.unsigned_abs() as usize;
16177 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
16178 if is_inter {
16179 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
16180 }
16181 lvl.clamp(0, 63)
16182}
16183
16184/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
16185/// no-segmentation, no-delta-LF path and to this decoder's own invariant
16186/// that a coded block's transform is always its own full size -- so a TU
16187/// edge is always also a PU edge, and the "both sides skipped, not a PU
16188/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
16189/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
16190/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
16191fn edge_params(
16192 lf: &LoopFilterParams,
16193 n: &Neighbours,
16194 plane_idx: usize,
16195 dir: usize,
16196 chroma: bool,
16197 x0: usize,
16198 y0: usize,
16199 // lane-perf9: `segmentation_enabled`, read once per plane pass instead of
16200 // four thread-local reads (`SEG_MI_DIMS`, `SEG_IDS`, twice each) plus two
16201 // `SEG` borrows per 4x4 edge. With it clear, every segment id is 0 and no
16202 // `SEG_LVL_ALT_LF_*` feature can be active, so the levels are unchanged.
16203 seg_lf_active: bool,
16204) -> Option<(u8, i32)> {
16205 let (mi_r, mi_c) = (plane_to_mi(chroma, y0), plane_to_mi(chroma, x0));
16206 let cur_tx = if dir == 0 {
16207 tx_px_at(n, chroma, mi_r, mi_c)
16208 } else {
16209 tx_h_px_at(n, chroma, mi_r, mi_c)
16210 };
16211 if cur_tx == 0 || (if dir == 0 { x0 } else { y0 }) % cur_tx as usize != 0 {
16212 return None;
16213 }
16214 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
16215 // `mode_step` (`set_lpf_parameters`): one mi for luma, `1 << ss` for
16216 // chroma -- the previous cell must keep the odd parity `plane_to_mi`
16217 // just established, i.e. the bottom/right mi of the PREVIOUS 8x8 luma
16218 // group, not the other half of this one.
16219 let step = if chroma { 2 } else { 1 };
16220 let (pv_mi_r, pv_mi_c) = if dir == 0 {
16221 (mi_r, mi_c - step)
16222 } else {
16223 (mi_r - step, mi_c)
16224 };
16225 let pv_tx = if dir == 0 {
16226 tx_px_at(n, chroma, pv_mi_r, pv_mi_c)
16227 } else {
16228 tx_h_px_at(n, chroma, pv_mi_r, pv_mi_c)
16229 };
16230 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
16231 let delta_idx = if plane_idx == 0 { dir } else { plane_idx + 1 };
16232 let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][delta_idx]);
16233 let pv_delta_lf = i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][delta_idx]);
16234
16235 // spec 7.14.2 / libaom `set_lpf_parameters`: a transform edge between two
16236 // SKIPPED INTER blocks is filtered only when it is also a prediction
16237 // (coded-block) edge -- `!pv_skip || !curr_skipped || pu_edge`. The
16238 // omission of this term (on the stale invariant "a coded block's transform
16239 // is always its own full size", which var-tx broke) had us filtering an
16240 // interior 8-px lattice the reference never touches: on the pinned 192x68
16241 // inter stream frame 1 went from 7244 wrong post-deblock luma px to 0.
16242 // libaom prices `pu_edge` in the PLANE's own pixels against the plane's
16243 // block size (`!(coord & (block_size_wide[get_plane_block_size(bsize)] -
16244 // 1))`), which for chroma bottoms out at 4 px: every 4-aligned chroma
16245 // edge of a sub-8x8 group is a prediction edge, even though the group's
16246 // bottom/right mi does not start there. Comparing mi origins instead is
16247 // the same test only while the block's own origin is aligned to its
16248 // size, which a 4x4 luma block read at the `| 1` mi is not.
16249 let cur_org = n.blk_org_grid[mi_r * n.skip_grid_cols_mi + mi_c];
16250 let cur_dim = n.blk_dim_grid[mi_r * n.skip_grid_cols_mi + mi_c];
16251 let (org_px, dim_mi) = if dir == 0 {
16252 (usize::from(cur_org[1]), usize::from(cur_dim[0]))
16253 } else {
16254 (usize::from(cur_org[0]), usize::from(cur_dim[1]))
16255 };
16256 let pu_edge = if chroma {
16257 let plane_dim = (dim_mi * MI / 2).max(4);
16258 (if dir == 0 { x0 } else { y0 }) % plane_dim == 0
16259 } else {
16260 plane_to_mi(false, if dir == 0 { x0 } else { y0 }) == org_px
16261 };
16262 if !pu_edge
16263 && cur_ref != 0
16264 && pv_ref != 0
16265 && n.skip_at(mi_r, mi_c)
16266 && n.skip_at(pv_mi_r, pv_mi_c)
16267 {
16268 return None;
16269 }
16270 let (cur_seg, pv_seg) = if seg_lf_active {
16271 (segment_id_at(mi_r, mi_c), segment_id_at(pv_mi_r, pv_mi_c))
16272 } else {
16273 (0, 0)
16274 };
16275 let cur_level = lf_level(lf, plane_idx, dir, cur_ref, cur_delta_lf, cur_seg);
16276 let pv_level = lf_level(lf, plane_idx, dir, pv_ref, pv_delta_lf, pv_seg);
16277 if cur_level == 0 && pv_level == 0 {
16278 return None;
16279 }
16280 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
16281 let len: u8 = if chroma {
16282 if dim == 0 { 4 } else { 6 }
16283 } else {
16284 [4, 8, 14, 14, 14][dim]
16285 };
16286 let level = if cur_level != 0 { cur_level } else { pv_level };
16287 DEBLOCK_HITS.with(|c| c.set(c.get() + 1));
16288 Some((len, level))
16289}
16290
16291/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
16292fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
16293 let sharpness = i32::from(sharpness);
16294 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
16295 let mut lim = level >> shift;
16296 if sharpness > 0 {
16297 lim = lim.min(9 - sharpness);
16298 }
16299 lim = lim.max(1);
16300 (2 * (level + 2) + lim, lim, level >> 4)
16301}
16302
16303fn sclamp(v: i32) -> i32 {
16304 // libaom's `signed_char_clamp_high`: the clamp range scales with
16305 // `128 << (bit_depth - 8)` alongside the centering constant below.
16306 let scale = 1i32 << (bit_depth() - 8);
16307 v.clamp(-128 * scale, 128 * scale - 1)
16308}
16309
16310fn round_pow2(v: i32, n: u32) -> i32 {
16311 (v + (1 << (n - 1))) >> n
16312}
16313
16314/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
16315/// fallback.
16316fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32) -> [i32; 4] {
16317 if !mask {
16318 return [p1, p0, q0, q1];
16319 }
16320 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
16321 // lane-perf6: `sclamp` re-read the thread-local bit depth on every one of
16322 // this kernel's eight clamps, and this kernel runs per deblocked sample.
16323 // Same bound, resolved once.
16324 let scale = 1i32 << (bit_depth() - 8);
16325 let sclamp = |v: i32| v.clamp(-128 * scale, 128 * scale - 1);
16326 let centre = 128i32 * scale;
16327 let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre);
16328 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
16329 let filter = sclamp(outer + 3 * (qs0 - ps0));
16330 let filter1 = sclamp(filter + 4) >> 3;
16331 let filter2 = sclamp(filter + 3) >> 3;
16332 let oq0 = sclamp(qs0 - filter1) + centre;
16333 let op0 = sclamp(ps0 + filter2) + centre;
16334 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
16335 let oq1 = sclamp(qs1 - tap) + centre;
16336 let op1 = sclamp(ps1 + tap) + centre;
16337 [op1, op0, oq0, oq1]
16338}
16339
16340/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
16341/// `filter4`'s narrow taps.
16342#[allow(clippy::too_many_arguments)]
16343fn filter6(
16344 mask: bool,
16345 thresh: i32,
16346 flat: bool,
16347 p2: i32,
16348 p1: i32,
16349 p0: i32,
16350 q0: i32,
16351 q1: i32,
16352 q2: i32,
16353) -> [i32; 4] {
16354 if flat && mask {
16355 [
16356 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
16357 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
16358 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
16359 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
16360 ]
16361 } else {
16362 filter4(mask, thresh, p1, p0, q0, q1)
16363 }
16364}
16365
16366/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
16367#[allow(clippy::too_many_arguments)]
16368fn filter8(
16369 mask: bool,
16370 thresh: i32,
16371 flat: bool,
16372 p3: i32,
16373 p2: i32,
16374 p1: i32,
16375 p0: i32,
16376 q0: i32,
16377 q1: i32,
16378 q2: i32,
16379 q3: i32,
16380) -> [i32; 6] {
16381 if flat && mask {
16382 [
16383 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
16384 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
16385 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
16386 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
16387 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
16388 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
16389 ]
16390 } else {
16391 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1);
16392 [p2, op1, op0, oq0, oq1, q2]
16393 }
16394}
16395
16396/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
16397/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
16398/// way -- they are only ever taps here, never written).
16399#[allow(clippy::too_many_arguments)]
16400fn filter14(
16401 mask: bool,
16402 thresh: i32,
16403 flat: bool,
16404 flat2: bool,
16405 p6: i32,
16406 p5: i32,
16407 p4: i32,
16408 p3: i32,
16409 p2: i32,
16410 p1: i32,
16411 p0: i32,
16412 q0: i32,
16413 q1: i32,
16414 q2: i32,
16415 q3: i32,
16416 q4: i32,
16417 q5: i32,
16418 q6: i32,
16419) -> [i32; 12] {
16420 if flat2 && flat && mask {
16421 [
16422 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
16423 round_pow2(
16424 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
16425 4,
16426 ),
16427 round_pow2(
16428 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
16429 4,
16430 ),
16431 round_pow2(
16432 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
16433 4,
16434 ),
16435 round_pow2(
16436 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
16437 4,
16438 ),
16439 round_pow2(
16440 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
16441 4,
16442 ),
16443 round_pow2(
16444 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
16445 4,
16446 ),
16447 round_pow2(
16448 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
16449 4,
16450 ),
16451 round_pow2(
16452 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
16453 4,
16454 ),
16455 round_pow2(
16456 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
16457 4,
16458 ),
16459 round_pow2(
16460 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
16461 4,
16462 ),
16463 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
16464 ]
16465 } else {
16466 let [op2, op1, op0, oq0, oq1, oq2] =
16467 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3);
16468 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
16469 }
16470}
16471
16472/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
16473/// the first (`q0`) sample past the edge, `outer_stride` advances to the
16474/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
16475/// the next along the edge's own filtering direction.
16476#[allow(clippy::too_many_arguments)]
16477fn filter_edge(
16478 data: &mut [u16],
16479 base: usize,
16480 outer_stride: isize,
16481 tap_stride: isize,
16482 len: u8,
16483 level: i32,
16484 sharpness: u8,
16485) {
16486 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
16487 // libaom `highbd_filter_mask*`/`highbd_flat_mask4`/`highbd_hev_mask`:
16488 // every 8-bit threshold (including the flat masks' fixed `1`) is
16489 // compared against a raw pixel difference on the stream's own bit-depth
16490 // scale, so each is shifted left by `bit_depth - 8` before use.
16491 let shift = bit_depth() - 8;
16492 let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift);
16493 let flat_thresh = 1i32 << shift;
16494 let smax = sample_max();
16495 for i in 0..4isize {
16496 let center = (base as isize + i * outer_stride) as usize;
16497 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
16498 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
16499 match len {
16500 4 => {
16501 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
16502 let mask = (p1 - p0).abs() <= limit
16503 && (q1 - q0).abs() <= limit
16504 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
16505 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1);
16506 data[idx(-2)] = op1.clamp(0, smax) as u16;
16507 data[idx(-1)] = op0.clamp(0, smax) as u16;
16508 data[idx(0)] = oq0.clamp(0, smax) as u16;
16509 data[idx(1)] = oq1.clamp(0, smax) as u16;
16510 }
16511 6 => {
16512 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
16513 let mask = (p2 - p1).abs() <= limit
16514 && (p1 - p0).abs() <= limit
16515 && (q1 - q0).abs() <= limit
16516 && (q2 - q1).abs() <= limit
16517 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
16518 let flat = (p1 - p0).abs() <= flat_thresh
16519 && (q1 - q0).abs() <= flat_thresh
16520 && (p2 - p0).abs() <= flat_thresh
16521 && (q2 - q0).abs() <= flat_thresh;
16522 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2);
16523 data[idx(-2)] = op1.clamp(0, smax) as u16;
16524 data[idx(-1)] = op0.clamp(0, smax) as u16;
16525 data[idx(0)] = oq0.clamp(0, smax) as u16;
16526 data[idx(1)] = oq1.clamp(0, smax) as u16;
16527 }
16528 8 => {
16529 let (p3, p2, p1, p0, q0, q1, q2, q3) =
16530 (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3));
16531 let mask = (p3 - p2).abs() <= limit
16532 && (p2 - p1).abs() <= limit
16533 && (p1 - p0).abs() <= limit
16534 && (q1 - q0).abs() <= limit
16535 && (q2 - q1).abs() <= limit
16536 && (q3 - q2).abs() <= limit
16537 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
16538 let flat = (p1 - p0).abs() <= flat_thresh
16539 && (q1 - q0).abs() <= flat_thresh
16540 && (p2 - p0).abs() <= flat_thresh
16541 && (q2 - q0).abs() <= flat_thresh
16542 && (p3 - p0).abs() <= flat_thresh
16543 && (q3 - q0).abs() <= flat_thresh;
16544 let [op2, op1, op0, oq0, oq1, oq2] =
16545 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3);
16546 data[idx(-3)] = op2.clamp(0, smax) as u16;
16547 data[idx(-2)] = op1.clamp(0, smax) as u16;
16548 data[idx(-1)] = op0.clamp(0, smax) as u16;
16549 data[idx(0)] = oq0.clamp(0, smax) as u16;
16550 data[idx(1)] = oq1.clamp(0, smax) as u16;
16551 data[idx(2)] = oq2.clamp(0, smax) as u16;
16552 }
16553 _ => {
16554 let (p6, p5, p4, p3, p2, p1, p0) =
16555 (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1));
16556 let (q0, q1, q2, q3, q4, q5, q6) =
16557 (px(0), px(1), px(2), px(3), px(4), px(5), px(6));
16558 let mask = (p3 - p2).abs() <= limit
16559 && (p2 - p1).abs() <= limit
16560 && (p1 - p0).abs() <= limit
16561 && (q1 - q0).abs() <= limit
16562 && (q2 - q1).abs() <= limit
16563 && (q3 - q2).abs() <= limit
16564 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
16565 let flat = (p1 - p0).abs() <= flat_thresh
16566 && (q1 - q0).abs() <= flat_thresh
16567 && (p2 - p0).abs() <= flat_thresh
16568 && (q2 - q0).abs() <= flat_thresh
16569 && (p3 - p0).abs() <= flat_thresh
16570 && (q3 - q0).abs() <= flat_thresh;
16571 let flat2 = (p4 - p0).abs() <= flat_thresh
16572 && (q4 - q0).abs() <= flat_thresh
16573 && (p5 - p0).abs() <= flat_thresh
16574 && (q5 - q0).abs() <= flat_thresh
16575 && (p6 - p0).abs() <= flat_thresh
16576 && (q6 - q0).abs() <= flat_thresh;
16577 let out = filter14(
16578 mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5,
16579 q6,
16580 );
16581 for (k, v) in (-6..=5isize).zip(out) {
16582 data[idx(k)] = v.clamp(0, smax) as u16;
16583 }
16584 }
16585 }
16586 }
16587}
16588
16589/// lane-perf8: [`filter_edge`]'s AVX2 kernel -- the scalar loop was 8.0% of a
16590/// 4K decode's self time, spent almost entirely on the per-tap strided
16591/// addressing (`perf annotate`'s hot lines are `leaq`/`movzwl` pairs, not the
16592/// arithmetic). Nothing here is spec logic: the same masks, the same
16593/// `filter4`/`filter6`/`filter8`/`filter14` weighted sums and the same
16594/// rounding, done for 16 edge lines at once.
16595///
16596/// 16-bit lanes are exact for every value these filters see. Samples are in
16597/// `[0, 4095]`, so a difference and the `blimit` term (`2 * |p0 - q0| +
16598/// |p1 - q1| / 2 <= 10237`) fit `i16`; `filter4` works in the centred domain
16599/// where every intermediate is clamped to `+-128 << (bit_depth - 8)`; and the
16600/// wide kernels' weights each total 8 or 16, so their sums (at most
16601/// `16 * 4095 + 8 = 65528`) fit `u16` -- hence `_mm256_srli_epi16` for their
16602/// rounding shift, which is the unsigned shift the scalar's non-negative sum
16603/// takes.
16604#[cfg(target_arch = "x86_64")]
16605#[allow(unsafe_code)]
16606#[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract
16607mod deblock_simd {
16608 use std::arch::x86_64::*;
16609
16610 /// `a <= b` lane-wise, as a full-width mask.
16611 ///
16612 /// # Safety
16613 /// Requires AVX2.
16614 #[target_feature(enable = "avx2")]
16615 #[inline]
16616 unsafe fn le(a: __m256i, b: __m256i) -> __m256i {
16617 _mm256_cmpeq_epi16(_mm256_max_epi16(a, b), b)
16618 }
16619
16620 /// `|a - b|` lane-wise.
16621 ///
16622 /// # Safety
16623 /// Requires AVX2.
16624 #[target_feature(enable = "avx2")]
16625 #[inline]
16626 unsafe fn ad(a: __m256i, b: __m256i) -> __m256i {
16627 _mm256_abs_epi16(_mm256_sub_epi16(a, b))
16628 }
16629
16630 /// `signed_char_clamp_high`, lane-wise.
16631 ///
16632 /// # Safety
16633 /// Requires AVX2.
16634 #[target_feature(enable = "avx2")]
16635 #[inline]
16636 unsafe fn sclamp(v: __m256i, lo: __m256i, hi: __m256i) -> __m256i {
16637 _mm256_min_epi16(_mm256_max_epi16(v, lo), hi)
16638 }
16639
16640 /// 16 rows of 16 `i16` transposed in place (unpack ladder, then the
16641 /// 128-bit lane swap AVX2's in-lane unpacks leave behind).
16642 ///
16643 /// # Safety
16644 /// Requires AVX2.
16645 #[target_feature(enable = "avx2")]
16646 unsafe fn transpose16(t: &mut [__m256i; 16]) {
16647 let mut a = [_mm256_setzero_si256(); 16];
16648 for k in 0..8 {
16649 a[2 * k] = _mm256_unpacklo_epi16(t[2 * k], t[2 * k + 1]);
16650 a[2 * k + 1] = _mm256_unpackhi_epi16(t[2 * k], t[2 * k + 1]);
16651 }
16652 let mut b = [_mm256_setzero_si256(); 16];
16653 for g in 0..4 {
16654 let s = 4 * g;
16655 b[s] = _mm256_unpacklo_epi32(a[s], a[s + 2]);
16656 b[s + 1] = _mm256_unpackhi_epi32(a[s], a[s + 2]);
16657 b[s + 2] = _mm256_unpacklo_epi32(a[s + 1], a[s + 3]);
16658 b[s + 3] = _mm256_unpackhi_epi32(a[s + 1], a[s + 3]);
16659 }
16660 let mut c = [_mm256_setzero_si256(); 16];
16661 for g in 0..2 {
16662 let s = 8 * g;
16663 for j in 0..4 {
16664 c[s + 2 * j] = _mm256_unpacklo_epi64(b[s + j], b[s + j + 4]);
16665 c[s + 2 * j + 1] = _mm256_unpackhi_epi64(b[s + j], b[s + j + 4]);
16666 }
16667 }
16668 for i in 0..8 {
16669 t[i] = _mm256_permute2x128_si256(c[i], c[i + 8], 0x20);
16670 t[i + 8] = _mm256_permute2x128_si256(c[i], c[i + 8], 0x31);
16671 }
16672 }
16673
16674 /// The wide kernels' tap weights, in tap order and with the spec's
16675 /// rounding divisor as the row sum: `filter6` over `p2..q2`, `filter8`
16676 /// over `p3..q3`, `filter14` over `p6..q6`.
16677 const W6: [[i16; 6]; 4] = [
16678 [3, 2, 2, 1, 0, 0],
16679 [1, 2, 2, 2, 1, 0],
16680 [0, 1, 2, 2, 2, 1],
16681 [0, 0, 1, 2, 2, 3],
16682 ];
16683 const W8: [[i16; 8]; 6] = [
16684 [3, 2, 1, 1, 1, 0, 0, 0],
16685 [2, 1, 2, 1, 1, 1, 0, 0],
16686 [1, 1, 1, 2, 1, 1, 1, 0],
16687 [0, 1, 1, 1, 2, 1, 1, 1],
16688 [0, 0, 1, 1, 1, 2, 1, 2],
16689 [0, 0, 0, 1, 1, 1, 2, 3],
16690 ];
16691 const W14: [[i16; 14]; 12] = [
16692 [7, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
16693 [5, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
16694 [4, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0],
16695 [3, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0],
16696 [2, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0],
16697 [1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0],
16698 [0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1],
16699 [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2],
16700 [0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 3],
16701 [0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 4],
16702 [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 5],
16703 [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 7],
16704 ];
16705
16706 /// One weighted tap sum, rounded by `shift` (3 for the divide-by-8 rows,
16707 /// 4 for `filter14`'s divide-by-16 ones). The sum is non-negative and
16708 /// below `1 << 16`, so the logical shift is the arithmetic one.
16709 ///
16710 /// # Safety
16711 /// Requires AVX2.
16712 #[target_feature(enable = "avx2")]
16713 #[inline]
16714 unsafe fn wsum(taps: &[__m256i], w: &[i16], shift: i32) -> __m256i {
16715 let mut s = _mm256_setzero_si256();
16716 for (t, &k) in taps.iter().zip(w) {
16717 match k {
16718 0 => {}
16719 1 => s = _mm256_add_epi16(s, *t),
16720 2 => s = _mm256_add_epi16(s, _mm256_add_epi16(*t, *t)),
16721 _ => s = _mm256_add_epi16(s, _mm256_mullo_epi16(*t, _mm256_set1_epi16(k))),
16722 }
16723 }
16724 let s = _mm256_add_epi16(s, _mm256_set1_epi16(1 << (shift - 1)));
16725 if shift == 3 {
16726 _mm256_srli_epi16(s, 3)
16727 } else {
16728 _mm256_srli_epi16(s, 4)
16729 }
16730 }
16731
16732 /// [`super::filter_edge`]'s body for 16 lines held as `t[0..16]`, `q0` in
16733 /// `t[8]`; the filtered taps are written back in place.
16734 ///
16735 /// # Safety
16736 /// Requires AVX2.
16737 #[target_feature(enable = "avx2")]
16738 #[allow(clippy::too_many_arguments)]
16739 unsafe fn filter16(
16740 t: &mut [__m256i; 16],
16741 len: u8,
16742 blimit: i32,
16743 limit: i32,
16744 hev_thr: i32,
16745 flat_thresh: i32,
16746 scale: i32,
16747 smax: i32,
16748 ) {
16749 let lim = _mm256_set1_epi16(limit as i16);
16750 let blim = _mm256_set1_epi16(blimit as i16);
16751 let hthr = _mm256_set1_epi16(hev_thr as i16);
16752 let fthr = _mm256_set1_epi16(flat_thresh as i16);
16753 let zero = _mm256_setzero_si256();
16754 let smaxv = _mm256_set1_epi16(smax as i16);
16755 let (p6, p5, p4, p3, p2, p1, p0) = (t[1], t[2], t[3], t[4], t[5], t[6], t[7]);
16756 let (q0, q1, q2, q3, q4, q5, q6) = (t[8], t[9], t[10], t[11], t[12], t[13], t[14]);
16757
16758 // `highbd_filter_mask`: the neighbour steps this kernel's length
16759 // reaches, plus the shared `blimit` term.
16760 let d1 = _mm256_max_epi16(ad(p1, p0), ad(q1, q0));
16761 let mut md = d1;
16762 if len >= 6 {
16763 md = _mm256_max_epi16(md, _mm256_max_epi16(ad(p2, p1), ad(q2, q1)));
16764 }
16765 if len >= 8 {
16766 md = _mm256_max_epi16(md, _mm256_max_epi16(ad(p3, p2), ad(q3, q2)));
16767 }
16768 let bl = _mm256_add_epi16(
16769 _mm256_slli_epi16(ad(p0, q0), 1),
16770 _mm256_srli_epi16(ad(p1, q1), 1),
16771 );
16772 let mask = _mm256_and_si256(le(md, lim), le(bl, blim));
16773 let hev = _mm256_cmpgt_epi16(d1, hthr);
16774
16775 // `filter4`, in the centred domain.
16776 let centre = _mm256_set1_epi16((128 * scale) as i16);
16777 let lo = _mm256_set1_epi16((-128 * scale) as i16);
16778 let hi = _mm256_set1_epi16((128 * scale - 1) as i16);
16779 let ps1 = _mm256_sub_epi16(p1, centre);
16780 let ps0 = _mm256_sub_epi16(p0, centre);
16781 let qs0 = _mm256_sub_epi16(q0, centre);
16782 let qs1 = _mm256_sub_epi16(q1, centre);
16783 let outer = _mm256_and_si256(hev, sclamp(_mm256_sub_epi16(ps1, qs1), lo, hi));
16784 let f = sclamp(
16785 _mm256_add_epi16(
16786 outer,
16787 _mm256_mullo_epi16(_mm256_set1_epi16(3), _mm256_sub_epi16(qs0, ps0)),
16788 ),
16789 lo,
16790 hi,
16791 );
16792 let f1 = _mm256_srai_epi16(sclamp(_mm256_add_epi16(f, _mm256_set1_epi16(4)), lo, hi), 3);
16793 let f2 = _mm256_srai_epi16(sclamp(_mm256_add_epi16(f, _mm256_set1_epi16(3)), lo, hi), 3);
16794 let tap = _mm256_andnot_si256(
16795 hev,
16796 _mm256_srai_epi16(_mm256_add_epi16(f1, _mm256_set1_epi16(1)), 1),
16797 );
16798 let n_p1 = _mm256_add_epi16(sclamp(_mm256_add_epi16(ps1, tap), lo, hi), centre);
16799 let n_p0 = _mm256_add_epi16(sclamp(_mm256_add_epi16(ps0, f2), lo, hi), centre);
16800 let n_q0 = _mm256_add_epi16(sclamp(_mm256_sub_epi16(qs0, f1), lo, hi), centre);
16801 let n_q1 = _mm256_add_epi16(sclamp(_mm256_sub_epi16(qs1, tap), lo, hi), centre);
16802 let mut r = [
16803 p5,
16804 p4,
16805 p3,
16806 p2,
16807 _mm256_blendv_epi8(p1, n_p1, mask),
16808 _mm256_blendv_epi8(p0, n_p0, mask),
16809 _mm256_blendv_epi8(q0, n_q0, mask),
16810 _mm256_blendv_epi8(q1, n_q1, mask),
16811 q2,
16812 q3,
16813 q4,
16814 q5,
16815 ];
16816
16817 if len >= 6 {
16818 // `highbd_flat_mask4`, over the same reach as this length's mask.
16819 let mut fl = _mm256_max_epi16(
16820 _mm256_max_epi16(ad(p1, p0), ad(q1, q0)),
16821 _mm256_max_epi16(ad(p2, p0), ad(q2, q0)),
16822 );
16823 if len >= 8 {
16824 fl = _mm256_max_epi16(fl, _mm256_max_epi16(ad(p3, p0), ad(q3, q0)));
16825 }
16826 let flat = _mm256_and_si256(le(fl, fthr), mask);
16827 if len == 6 {
16828 let taps = [p2, p1, p0, q0, q1, q2];
16829 for (j, w) in W6.iter().enumerate() {
16830 r[4 + j] = _mm256_blendv_epi8(r[4 + j], wsum(&taps, w, 3), flat);
16831 }
16832 } else {
16833 let taps = [p3, p2, p1, p0, q0, q1, q2, q3];
16834 for (j, w) in W8.iter().enumerate() {
16835 r[3 + j] = _mm256_blendv_epi8(r[3 + j], wsum(&taps, w, 3), flat);
16836 }
16837 if len > 8 {
16838 let fl2 = _mm256_max_epi16(
16839 _mm256_max_epi16(
16840 _mm256_max_epi16(ad(p4, p0), ad(q4, q0)),
16841 _mm256_max_epi16(ad(p5, p0), ad(q5, q0)),
16842 ),
16843 _mm256_max_epi16(ad(p6, p0), ad(q6, q0)),
16844 );
16845 let flat2 = _mm256_and_si256(le(fl2, fthr), flat);
16846 let taps = [p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5, q6];
16847 for (j, w) in W14.iter().enumerate() {
16848 r[j] = _mm256_blendv_epi8(r[j], wsum(&taps, w, 4), flat2);
16849 }
16850 }
16851 }
16852 }
16853
16854 // `r[j]` holds the sample at tap `j - 6`, i.e. `t[j + 2]`.
16855 let (a, b) = match len {
16856 4 | 6 => (4, 8),
16857 8 => (3, 9),
16858 _ => (0, 12),
16859 };
16860 for j in a..b {
16861 t[j + 2] = _mm256_min_epi16(_mm256_max_epi16(r[j], zero), smaxv);
16862 }
16863 }
16864
16865 /// 16 edge lines at `base`. `vertical` names the edge: a vertical edge's
16866 /// 16 lines are 16 consecutive rows and its taps are consecutive samples
16867 /// (loaded as a 16x16 tile and transposed), a horizontal edge's are 16
16868 /// consecutive columns with each tap a whole row segment.
16869 ///
16870 /// # Safety
16871 /// Requires AVX2. For a vertical edge `base % stride >= 8`, `base %
16872 /// stride + 8 <= stride` and 16 rows from `base` must be inside `data`;
16873 /// for a horizontal edge `base >= 8 * stride` and `base + 8 * stride`
16874 /// must be inside it.
16875 #[target_feature(enable = "avx2")]
16876 #[allow(clippy::too_many_arguments)]
16877 pub unsafe fn edge16(
16878 data: &mut [u16],
16879 base: usize,
16880 stride: usize,
16881 vertical: bool,
16882 len: u8,
16883 blimit: i32,
16884 limit: i32,
16885 hev_thr: i32,
16886 flat_thresh: i32,
16887 scale: i32,
16888 smax: i32,
16889 ) {
16890 let p = data.as_mut_ptr();
16891 let mut t = [_mm256_setzero_si256(); 16];
16892 // The taps this length reads, as `t` indices.
16893 let (lo, hi) = match len {
16894 4 => (6, 10),
16895 6 => (5, 11),
16896 8 => (4, 12),
16897 _ => (1, 15),
16898 };
16899 if vertical {
16900 for j in 0..16 {
16901 t[j] = _mm256_loadu_si256(p.add(base + j * stride - 8).cast());
16902 }
16903 transpose16(&mut t);
16904 } else {
16905 let top = base - 8 * stride;
16906 for i in lo..hi {
16907 t[i] = _mm256_loadu_si256(p.add(top + i * stride).cast());
16908 }
16909 }
16910 filter16(&mut t, len, blimit, limit, hev_thr, flat_thresh, scale, smax);
16911 if vertical {
16912 transpose16(&mut t);
16913 for j in 0..16 {
16914 _mm256_storeu_si256(p.add(base + j * stride - 8).cast(), t[j]);
16915 }
16916 } else {
16917 let top = base - 8 * stride;
16918 let (a, b) = match len {
16919 4 | 6 => (6, 10),
16920 8 => (5, 11),
16921 _ => (2, 14),
16922 };
16923 for i in a..b {
16924 _mm256_storeu_si256(p.add(top + i * stride).cast(), t[i]);
16925 }
16926 }
16927 }
16928}
16929
16930/// [`filter_edge`] for 16 adjacent edge lines that share `edge_params`'
16931/// output. Returns `false` when this build or CPU has no kernel, leaving the
16932/// caller on the scalar path.
16933#[allow(unused_variables)]
16934fn filter_edge16(
16935 data: &mut [u16],
16936 base: usize,
16937 stride: usize,
16938 vertical: bool,
16939 len: u8,
16940 level: i32,
16941 sharpness: u8,
16942) -> bool {
16943 #[cfg(target_arch = "x86_64")]
16944 {
16945 if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 {
16946 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
16947 let shift = bit_depth() - 8;
16948 // SAFETY: the avx2 arm is reached only when the CPU reports it,
16949 // and `deblock_plane` checks the kernel's edge bounds.
16950 #[allow(unsafe_code)]
16951 unsafe {
16952 deblock_simd::edge16(
16953 data,
16954 base,
16955 stride,
16956 vertical,
16957 len,
16958 blimit << shift,
16959 limit << shift,
16960 hev_thr << shift,
16961 1 << shift,
16962 1 << shift,
16963 sample_max(),
16964 )
16965 };
16966 return true;
16967 }
16968 }
16969 false
16970}
16971
16972/// One plane's worth of spec 7.14: every vertical edge across the plane,
16973/// then every horizontal edge (the order the spec and libaom both use).
16974fn deblock_plane(
16975 plane: &mut PlaneBuf,
16976 plane_idx: usize,
16977 lf: &LoopFilterParams,
16978 n: &Neighbours,
16979 frame_width: usize,
16980 frame_height: usize,
16981) {
16982 let chroma = plane_idx != 0;
16983 // r7: libaom clips the deblock loop to the CODED frame's own
16984 // width/height, not the mi-aligned `true_width`/`true_height` margin
16985 // (the padding up to the next 8-pixel/superblock boundary that
16986 // reconstruction still fills in but the loop filter never visits).
16987 // Confirmed against the superres gate: with the margin included, the
16988 // last coded mi column's horizontal edges were filtered when libaom's
16989 // real output leaves them untouched (r6's post-deblock diff, 37 px, all
16990 // in columns 44-47); clipping here closes it (3/3 frames pixel-exact).
16991 // lane-golomb r9: the bound is the MI-ROUNDED frame, not the coded
16992 // frame. libaom's `av1_filter_block_plane_vert/horz` walk the superblock
16993 // and stop at `cm->mi_params.mi_cols`/`mi_rows`, which
16994 // `av1_set_mb_mi` derives from `ALIGN_POWER_OF_TWO(width, 3)` -- the
16995 // 8-pixel-aligned frame, i.e. a 68-wide frame is filtered out to column
16996 // 72 and the vertical edge AT x=68 is a real edge that rewrites the
16997 // in-crop columns 64..67. Clipping at `frame_width` skipped it, which is
16998 // the +-1 straddling-band defect (68x192 cq35, frame 1, 141 luma pixels
16999 // all in columns 64..67; frame 0 survived because that edge carried no
17000 // filter level there). r7's superres measurement is preserved: its frame
17001 // was already 8-aligned, so this bound equals `frame_width` there and
17002 // still excludes the superblock padding up to `true_width`.
17003 let (cw, ch) = if chroma {
17004 (frame_width.div_ceil(2), frame_height.div_ceil(2))
17005 } else {
17006 (frame_width, frame_height)
17007 };
17008 let (tw, th, stride) = (
17009 plane.true_width.min(cw),
17010 plane.true_height.min(ch),
17011 plane.width,
17012 );
17013 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") {
17014 eprintln!("DEBLOCK plane={plane_idx} tw={tw} th={th} stride={stride} true={}x{} crop={cw}x{ch}", plane.true_width, plane.true_height);
17015 }
17016 // lane-perf8: both passes iterate the edge's OWN direction innermost, so
17017 // 4 consecutive 4-sample groups (16 lines) can go through one AVX2
17018 // kernel. The swap is order-preserving: a filtered group overlaps only
17019 // groups along the edge it sits on -- the vertical pass's writes at
17020 // `x0` reach columns `x0 - 7 ..= x0 + 5` of its own 4 rows, so the
17021 // dependence is on ascending `x0` within a row, which stays the outer
17022 // loop's order, and rows remain independent (horizontal pass mirrored).
17023 let rows = plane.data.len() / stride.max(1);
17024 let seg_lf_active = SEG.with(|s| s.borrow().enabled);
17025 let mut x0 = 4usize;
17026 while x0 < tw {
17027 let mut y0 = 0usize;
17028 while y0 < th {
17029 if y0 + 16 <= th && x0 >= 8 && x0 + 8 <= stride {
17030 let ps: [Option<(u8, i32)>; 4] =
17031 std::array::from_fn(|k| edge_params(lf, n, plane_idx, 0, chroma, x0, y0 + 4 * k, seg_lf_active));
17032 if let Some((len, level)) = ps[0] {
17033 if ps.iter().all(|p| *p == ps[0])
17034 && filter_edge16(
17035 &mut plane.data,
17036 y0 * stride + x0,
17037 stride,
17038 true,
17039 len,
17040 level,
17041 lf.sharpness,
17042 )
17043 {
17044 y0 += 16;
17045 continue;
17046 }
17047 }
17048 for (k, p) in ps.iter().enumerate() {
17049 if let Some((len, level)) = *p {
17050 filter_edge(
17051 &mut plane.data,
17052 (y0 + 4 * k) * stride + x0,
17053 stride as isize,
17054 1,
17055 len,
17056 level,
17057 lf.sharpness,
17058 );
17059 }
17060 }
17061 y0 += 16;
17062 continue;
17063 }
17064 if let Some((len, level)) = edge_params(lf, n, plane_idx, 0, chroma, x0, y0, seg_lf_active) {
17065 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") && plane_idx == 0 {
17066 eprintln!("VEDGE x0={x0} y0={y0} len={len} level={level}");
17067 }
17068 filter_edge(
17069 &mut plane.data,
17070 y0 * stride + x0,
17071 stride as isize,
17072 1,
17073 len,
17074 level,
17075 lf.sharpness,
17076 );
17077 }
17078 y0 += 4;
17079 }
17080 x0 += 4;
17081 }
17082 let mut y0 = 4usize;
17083 while y0 < th {
17084 let mut x0 = 0usize;
17085 while x0 < tw {
17086 if x0 + 16 <= tw && y0 >= 8 && y0 + 7 <= rows {
17087 let ps: [Option<(u8, i32)>; 4] =
17088 std::array::from_fn(|k| edge_params(lf, n, plane_idx, 1, chroma, x0 + 4 * k, y0, seg_lf_active));
17089 if let Some((len, level)) = ps[0] {
17090 if ps.iter().all(|p| *p == ps[0])
17091 && filter_edge16(
17092 &mut plane.data,
17093 y0 * stride + x0,
17094 stride,
17095 false,
17096 len,
17097 level,
17098 lf.sharpness,
17099 )
17100 {
17101 x0 += 16;
17102 continue;
17103 }
17104 }
17105 for (k, p) in ps.iter().enumerate() {
17106 if let Some((len, level)) = *p {
17107 filter_edge(
17108 &mut plane.data,
17109 y0 * stride + x0 + 4 * k,
17110 1,
17111 stride as isize,
17112 len,
17113 level,
17114 lf.sharpness,
17115 );
17116 }
17117 }
17118 x0 += 16;
17119 continue;
17120 }
17121 if let Some((len, level)) = edge_params(lf, n, plane_idx, 1, chroma, x0, y0, seg_lf_active) {
17122 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE")
17123 && plane_idx == 0
17124 && x0 == 44
17125 {
17126 eprintln!(
17127 "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}",
17128 lf.sharpness
17129 );
17130 }
17131 filter_edge(
17132 &mut plane.data,
17133 y0 * stride + x0,
17134 1,
17135 stride as isize,
17136 len,
17137 level,
17138 lf.sharpness,
17139 );
17140 }
17141 x0 += 4;
17142 }
17143 y0 += 4;
17144 }
17145}
17146
17147thread_local! {
17148 /// lane-perf6: reused whole-plane `u16` buffers. Every frame takes a
17149 /// pre-CDEF snapshot of all three planes, a post-deblock snapshot when
17150 /// loop restoration is active, and a fresh LR destination per plane --
17151 /// freshly allocated that is ~25 MB of `mmap`/`munmap` per frame at 4K,
17152 /// so every sample written also takes a first-touch page fault. The
17153 /// buffers are handed back here instead and refilled in place.
17154 static PLANE_SCRATCH: std::cell::RefCell<Vec<Vec<u16>>> =
17155 const { std::cell::RefCell::new(Vec::new()) };
17156}
17157
17158/// A pooled buffer holding a copy of `src`.
17159fn scratch_from(src: &[u16]) -> Vec<u16> {
17160 let mut v = PLANE_SCRATCH.with(|p| p.borrow_mut().pop()).unwrap_or_default();
17161 v.clear();
17162 v.extend_from_slice(src);
17163 v
17164}
17165
17166/// An empty pooled buffer, for a caller that fills it itself.
17167fn scratch_empty() -> Vec<u16> {
17168 let mut v = PLANE_SCRATCH.with(|p| p.borrow_mut().pop()).unwrap_or_default();
17169 v.clear();
17170 v
17171}
17172
17173/// A plane's post-deblock snapshot, its samples taken from the pool (every
17174/// other field is `usize`).
17175fn plane_snapshot(p: &PlaneBuf) -> PlaneBuf {
17176 PlaneBuf { data: scratch_from(&p.data), ..*p }
17177}
17178
17179/// Hands a buffer back to the pool; the capacity is what is worth keeping.
17180fn scratch_return(v: Vec<u16>) {
17181 PLANE_SCRATCH.with(|p| p.borrow_mut().push(v));
17182}
17183
17184fn apply_cdef(
17185 y: &mut PlaneBuf,
17186 u: &mut PlaneBuf,
17187 v: &mut PlaneBuf,
17188 cdef: &CdefParams,
17189 skip_grid: &Neighbours,
17190 // This frame header's own CROPPED luma size, for the straddling-unit
17191 // counter only -- CDEF itself walks the mi-rounded plane.
17192 (frame_w, frame_h): (usize, usize),
17193) {
17194 // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling.
17195 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_CDEF") {
17196 return;
17197 }
17198 // lane-cdefstrip r1 instrument, BEFORE either early return so it is valid
17199 // for every frame: an 8x8 CDEF unit none of whose four mi cells a coded
17200 // block wrote this frame. `Neighbours` seeds `skip_grid` all-false, so a
17201 // decode arm that forgets `fill_skip_grid_rect` reads "not skip" and CDEF
17202 // filters a unit libaom's `is_8x8_block_skip` (`cdef.c:29-38`) may exclude.
17203 // Always 0 on every stream measured; a gate asserts it stays 0.
17204 {
17205 let mut r = 0usize;
17206 while r < skip_grid.mi_rows {
17207 let mut c = 0usize;
17208 while c < skip_grid.mi_cols {
17209 if (0..2).any(|rr| {
17210 (0..2).any(|cc| {
17211 !skip_grid
17212 .skip_written
17213 .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc))
17214 .copied()
17215 .unwrap_or(true)
17216 })
17217 }) {
17218 CDEF_UNWRITTEN_SKIP_UNITS.with(|c2| c2.set(c2.get() + 1));
17219 if crate::envflags::env_flag!("EC_AV1_DEBUG_CDEF_BAND") {
17220 eprintln!("cdef band unwritten at mi ({r},{c}) px ({},{})", r * 4, c * 4);
17221 }
17222 }
17223 let cell = |rr: usize, cc: usize| {
17224 skip_grid
17225 .skip_grid
17226 .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc))
17227 .copied()
17228 .unwrap_or(false)
17229 };
17230 let first = cell(0, 0);
17231 if (0..2).any(|rr| (0..2).any(|cc| cell(rr, cc) != first)) {
17232 CDEF_MIXED_SKIP_UNITS.with(|c2| c2.set(c2.get() + 1));
17233 }
17234 c += 2;
17235 }
17236 r += 2;
17237 }
17238 }
17239 // `cdef.bits == 0` still means "no filtering at all" whenever the single
17240 // (index 0) strength pair is all-zero -- the fast path every existing
17241 // gate stream takes. A `bits > 0` frame can still be all-zero-strength
17242 // at every index, but that is rare enough not to special-case; the
17243 // per-superblock lookup below degrades to the same index-0 read anyway
17244 // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`).
17245 if cdef.bits == 0
17246 && cdef.y_pri_strength[0] == 0
17247 && cdef.y_sec_strength[0] == 0
17248 && cdef.uv_pri_strength[0] == 0
17249 && cdef.uv_sec_strength[0] == 0
17250 {
17251 return;
17252 }
17253 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
17254 // One entry per superblock (a few hundred at 4K), so this clone is not
17255 // one of the per-frame copies lane-perf6 pooled below.
17256 let idx_grid = CDEF_IDX_GRID.with(|g| g.borrow().clone());
17257 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
17258 if sb_cols == 0 {
17259 return 0;
17260 }
17261 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
17262 idx_grid
17263 .get(sb_r * sb_cols + sb_c)
17264 .copied()
17265 .unwrap_or(0) as usize
17266 };
17267 let src_y = scratch_from(&y.data);
17268 let src_u = scratch_from(&u.data);
17269 let src_v = scratch_from(&v.data);
17270 // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`,
17271 // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`.
17272 let coeff_shift = i32::from(bit_depth()) - 8;
17273 let damping = i32::from(cdef.damping) + coeff_shift;
17274 let damping_uv = (damping - 1).max(0);
17275 // One scratch window per plane kind, reused by every unit (8x8 luma and
17276 // 4x4 chroma, each grown by the [`CDEF_BORDER`] tap ring).
17277 let mut win_y = [0i32; (8 + 2 * CDEF_BORDER) * (8 + 2 * CDEF_BORDER)];
17278 let mut win_uv = [0i32; (4 + 2 * CDEF_BORDER) * (4 + 2 * CDEF_BORDER)];
17279 let mut mi_r = 0usize;
17280 while mi_r < skip_grid.mi_rows {
17281 let mut mi_c = 0usize;
17282 while mi_c < skip_grid.mi_cols {
17283 if skip_grid.is_skip_txfm(mi_r, mi_c) {
17284 CDEF_SKIPPED_UNITS.with(|c| c.set(c.get() + 1));
17285 }
17286 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
17287 let sidx = strength_idx(mi_r, mi_c);
17288 let (ox, oy) = (mi_c * 4, mi_r * 4);
17289 // Nothing to do for this unit at all: the direction search is
17290 // only ever consumed through a strength, so a unit whose four
17291 // strengths are zero never needs its 8x8 window gathered.
17292 if cdef.y_pri_strength[sidx] == 0
17293 && cdef.y_sec_strength[sidx] == 0
17294 && cdef.uv_pri_strength[sidx] == 0
17295 && cdef.uv_sec_strength[sidx] == 0
17296 {
17297 mi_c += 2;
17298 continue;
17299 }
17300 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
17301 cdef_gather(&src_y, y_stride, y_true_w, y_true_h, ox, oy, 8, 8, &mut win_y);
17302 let sample_y = |r: i32, c: i32| -> i32 {
17303 win_y[(r + CDEF_BORDER as i32) as usize * (8 + 2 * CDEF_BORDER)
17304 + (c + CDEF_BORDER as i32) as usize]
17305 };
17306 // lane-cdef r1: the direction search reads the SAME padded
17307 // block the taps do -- libaom runs `cdef_find_dir` on the
17308 // prepared filter block (`cdef_block.c:296-320` over
17309 // `cdef_prepare_fb`'s buffer, `cdef.c:249-256`), whose columns
17310 // and rows past the mi-rounded frame extent are CDEF_VERY_LARGE.
17311 // Clamping to the last real sample instead made every straddling
17312 // edge 8x8 (odd `mi_cols`/`mi_rows`) pick a different var, hence
17313 // a different `adjust_strength`, hence a +-1 band at the crop edge.
17314 let (dir, var) = cdef_find_dir(coeff_shift, |r, c| sample_y(r as i32, c as i32));
17315
17316 // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
17317 // -- each plane zeroes the shared direction when *its own*
17318 // frame-level primary strength is 0, independent of the
17319 // per-block adjusted `t` and of the other plane's strength.
17320 let y_pri_strength = i32::from(cdef.y_pri_strength[sidx]) << coeff_shift;
17321 let y_sec_strength = i32::from(cdef.y_sec_strength[sidx]) << coeff_shift;
17322 let y_dir = if y_pri_strength != 0 { dir } else { 0 };
17323 let t = cdef_adjust_strength(y_pri_strength, var);
17324 // lane-cdef r1 rung: one line per filtered 8x8 luma CDEF unit.
17325 if crate::envflags::env_flag!("EC_AV1_CDEF_DBG") {
17326 eprintln!(
17327 "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}"
17328 );
17329 }
17330 let enable_primary = t != 0;
17331 let enable_secondary = y_sec_strength != 0;
17332 if (ox + 8 > frame_w || oy + 8 > frame_h)
17333 && (enable_primary
17334 || enable_secondary
17335 || cdef.uv_pri_strength[sidx] != 0
17336 || cdef.uv_sec_strength[sidx] != 0)
17337 {
17338 CDEF_STRADDLE_UNITS.with(|c| c.set(c.get() + 1));
17339 }
17340 if enable_primary || enable_secondary {
17341 cdef_filter_block(
17342 &win_y,
17343 y,
17344 ox,
17345 oy,
17346 8,
17347 8,
17348 t,
17349 y_sec_strength,
17350 y_dir,
17351 damping,
17352 damping,
17353 enable_primary,
17354 enable_secondary,
17355 coeff_shift,
17356 );
17357 }
17358
17359 let t_uv = i32::from(cdef.uv_pri_strength[sidx]) << coeff_shift;
17360 let uv_sec_strength = i32::from(cdef.uv_sec_strength[sidx]) << coeff_shift;
17361 let uv_dir = if t_uv != 0 { dir } else { 0 };
17362 let enable_primary_uv = t_uv != 0;
17363 let enable_secondary_uv = uv_sec_strength != 0;
17364 if enable_primary_uv || enable_secondary_uv {
17365 let (cox, coy) = (ox / 2, oy / 2);
17366 for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] {
17367 let (tw, th) = (plane.true_width, plane.true_height);
17368 let stride = plane.width;
17369 cdef_gather(src_p, stride, tw, th, cox, coy, 4, 4, &mut win_uv);
17370 cdef_filter_block(
17371 &win_uv,
17372 plane,
17373 cox,
17374 coy,
17375 4,
17376 4,
17377 t_uv,
17378 uv_sec_strength,
17379 uv_dir,
17380 damping_uv,
17381 damping_uv,
17382 enable_primary_uv,
17383 enable_secondary_uv,
17384 coeff_shift,
17385 );
17386 }
17387 }
17388 }
17389 mi_c += 2;
17390 }
17391 mi_r += 2;
17392 }
17393 scratch_return(src_y);
17394 scratch_return(src_u);
17395 scratch_return(src_v);
17396}
17397
17398/// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
17399/// ordering note: libaom also runs `superres_post_decode` between the two,
17400/// but this decoder never implements super-resolution, so there is nothing
17401/// to interleave). `deblocked_*` is each plane's post-deblock, pre-CDEF
17402/// buffer (the caller clones it before calling [`apply_cdef`]) -- loop
17403/// restoration's stripe-boundary rows read from it instead of the
17404/// CDEF-filtered plane, per `restoration.rs`'s own `lr_sample` doc comment.
17405#[allow(clippy::too_many_arguments)]
17406fn apply_loop_restoration(
17407 y: &mut PlaneBuf,
17408 u: &mut PlaneBuf,
17409 v: &mut PlaneBuf,
17410 deblocked_y: &PlaneBuf,
17411 deblocked_u: &PlaneBuf,
17412 deblocked_v: &PlaneBuf,
17413 lr: &LoopRestorationParams,
17414 grid: &crate::restoration::RestorationGrid,
17415 // lane-golomb r8: this frame header's own (cropped) luma size. Loop
17416 // restoration is the ONE post-decode filter that does NOT run over the
17417 // mi-rounded plane: libaom's `av1_loop_restoration_filter_frame` sizes
17418 // every plane with `av1_get_upsampled_plane_size` -- `plane_w =
17419 // ROUND_POWER_OF_TWO(cm->superres_upscaled_width, ss_x)`, `plane_h =
17420 // ROUND_POWER_OF_TWO(cm->height, ss_y)` (`av1/common/restoration.c:47`)
17421 // -- and asserts it equals the buffer's CROP width
17422 // (`restoration.c:1106`), then `av1_extend_frame(..., plane_w, plane_h,
17423 // ...)` (`restoration.c:1109`) replicates the right/bottom border from
17424 // that cropped edge before any unit is filtered. Deblock and CDEF DO
17425 // walk the mi grid, which is why passing `true_width`/`true_height`
17426 // here went unnoticed until a frame whose size is not a multiple of 8
17427 // (68 -> mi-rounded 72): the LR taps at the last four real columns then
17428 // read this decoder's own decoded samples at columns 68..71 where
17429 // libaom reads column 67 replicated -- +-1 over the straddling band
17430 // (class av1-truesize-lane: true frame size vs mi-rounded).
17431 (frame_w, frame_h): (usize, usize),
17432) {
17433 let mut out = scratch_empty();
17434 crate::restoration::apply_loop_restoration_plane(
17435 &y.data,
17436 &deblocked_y.data,
17437 y.width,
17438 frame_w,
17439 frame_h,
17440 0,
17441 lr.frame_restoration_type[0],
17442 lr.loop_restoration_size[0],
17443 grid,
17444 0,
17445 &mut out,
17446 );
17447 std::mem::swap(&mut y.data, &mut out);
17448 scratch_return(out);
17449 let mut out = scratch_empty();
17450 crate::restoration::apply_loop_restoration_plane(
17451 &u.data,
17452 &deblocked_u.data,
17453 u.width,
17454 frame_w.div_ceil(2),
17455 frame_h.div_ceil(2),
17456 1,
17457 lr.frame_restoration_type[1],
17458 lr.loop_restoration_size[1],
17459 grid,
17460 1,
17461 &mut out,
17462 );
17463 std::mem::swap(&mut u.data, &mut out);
17464 scratch_return(out);
17465 let mut out = scratch_empty();
17466 crate::restoration::apply_loop_restoration_plane(
17467 &v.data,
17468 &deblocked_v.data,
17469 v.width,
17470 frame_w.div_ceil(2),
17471 frame_h.div_ceil(2),
17472 1,
17473 lr.frame_restoration_type[2],
17474 lr.loop_restoration_size[2],
17475 grid,
17476 2,
17477 &mut out,
17478 );
17479 std::mem::swap(&mut v.data, &mut out);
17480 scratch_return(out);
17481}
17482
17483/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
17484/// returning the picture it reconstructs to.
17485///
17486/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
17487/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
17488/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
17489/// `compute_image_size` derives one from the other, but not losslessly: a
17490/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
17491/// what the reconstruction is cropped to on the way out, mirroring
17492/// [`crate::encode::crop_encoded`].
17493///
17494/// # Errors
17495/// Returns an error when a block's partition, mode, skip flag or transform
17496/// type is anything this decoder does not reconstruct (round 2: inter, tx
17497/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
17498/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
17499/// or when the tile payload runs out of the symbols this decode expects (a
17500/// genuinely foreign stream).
17501pub fn decode_key_frame_tile(
17502 data: &[u8],
17503 mi_cols: u32,
17504 mi_rows: u32,
17505 base_q_idx: u8,
17506 frame_width: u32,
17507 frame_height: u32,
17508 enable_filter_intra: bool,
17509 cdef: &CdefParams,
17510 loop_filter: &LoopFilterParams,
17511 tx_select: bool,
17512 reduced_tx_set: bool,
17513 allow_screen_content_tools: bool,
17514 allow_intrabc: bool,
17515) -> Result<Picture> {
17516 let delta = DeltaParams::default();
17517 let single_tile = TileInfo {
17518 mi_col_starts: vec![0, mi_cols],
17519 mi_row_starts: vec![0, mi_rows],
17520 ..TileInfo::default()
17521 };
17522 decode_key_frame_tile_with_cdfs(
17523 &[data],
17524 &single_tile,
17525 mi_cols,
17526 mi_rows,
17527 base_q_idx,
17528 crate::quant::QuantDeltas::default(),
17529 frame_width,
17530 frame_height,
17531 enable_filter_intra,
17532 false,
17533 cdef,
17534 loop_filter,
17535 &LoopRestorationParams::default(),
17536 None,
17537 tx_select,
17538 reduced_tx_set,
17539 allow_screen_content_tools,
17540 allow_intrabc,
17541 delta,
17542 )
17543 .map(|(picture, _)| picture)
17544}
17545
17546thread_local! {
17547 /// lane-superres r3: the real decoded margin beyond `frame_width` up to
17548 /// the mi-aligned `true_width`, set by the most recent
17549 /// [`decode_key_frame_tile_with_cdfs`] OR (lane-superres r10)
17550 /// [`decode_inter_frame_tile_with_cdfs`] call -- both frame kinds crop
17551 /// their reconstructed buffer down from the same mi-aligned extent, so
17552 /// they share this one slot. See each function's own comment at its
17553 /// write site. `None` when there was no margin to save.
17554 static LAST_FRAME_WIDE_MARGIN: std::cell::RefCell<Option<Picture>> =
17555 const { std::cell::RefCell::new(None) };
17556}
17557
17558/// The margin the most recent key- or inter-frame tile decode stashed
17559/// (see [`LAST_FRAME_WIDE_MARGIN`]) -- `stream.rs`'s superres path
17560/// reads this immediately after the call, before any other frame
17561/// decode can overwrite it.
17562pub(crate) fn take_last_frame_wide_margin() -> Option<Picture> {
17563 LAST_FRAME_WIDE_MARGIN.with(|m| m.borrow_mut().take())
17564}
17565
17566/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
17567/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
17568/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
17569/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs,
17570/// since a key frame's own header always forces `primary_ref_frame ==
17571/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table
17572/// alongside the picture, for the caller to save into whichever reference
17573/// slots this frame's `refresh_frame_flags` names.
17574/// The order the 64x64 superblock quadrants of a tile are decoded in.
17575///
17576/// At `sb_size == 64` this is plain raster order over the tile's own
17577/// superblock grid. At `sb_size == 128` libaom's `decode_partition` recurses
17578/// each 128x128 superblock in raster order and visits its four 64x64
17579/// quadrants (TL, TR, BL, BR) before moving to the next superblock, so the
17580/// 64-level bodies must run in that nested order. `row_start` marks the first
17581/// item of each *superblock* row (where the left neighbour context resets),
17582/// `sb_start` the first item of each superblock (where the 128 root's own
17583/// loop-restoration units and partition symbol are read).
17584fn sb_visit_order(r0: u32, r1: u32, c0: u32, c1: u32, sb128: bool) -> Vec<(u32, u32, bool, bool)> {
17585 let mut out = Vec::new();
17586 if !sb128 {
17587 for r in r0..r1 {
17588 for c in c0..c1 {
17589 out.push((r, c, c == c0, true));
17590 }
17591 }
17592 return out;
17593 }
17594 let mut r = r0;
17595 while r < r1 {
17596 let mut first_in_row = true;
17597 let mut c = c0;
17598 while c < c1 {
17599 let mut first_in_sb = true;
17600 for qr in 0..2 {
17601 for qc in 0..2 {
17602 let (rr, cc) = (r + qr, c + qc);
17603 if rr >= r1 || cc >= c1 {
17604 continue;
17605 }
17606 out.push((rr, cc, first_in_row, first_in_sb));
17607 first_in_row = false;
17608 first_in_sb = false;
17609 }
17610 }
17611 c += 2;
17612 }
17613 r += 2;
17614 }
17615 out
17616}
17617
17618/// lane-sb128 r2: the 128x128 superblock root, shared by the key-frame and
17619/// the inter tile loop. Its loop-restoration units are read once for the whole
17620/// 128x128 (spec 5.11.57 is called with the superblock's own size), then one
17621/// partition symbol off the `BLOCK_128X128` CDF (8 symbols, no HORZ_4/VERT_4)
17622/// decides the root -- only SPLIT recurses into the four 64x64 quadrants this
17623/// decoder codes, the other seven arms refuse by name.
17624#[allow(clippy::too_many_arguments)]
17625thread_local! {
17626 /// How many 128x128 superblock roots resolved to `PARTITION_NONE` -- one
17627 /// whole 128x128 block (lane-sb128b r1's gate counter).
17628 pub(crate) static PART128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
17629 /// 128 roots that resolved to PARTITION_HORZ (two 128x64 pieces, or one
17630 /// when the bottom half is out of frame) -- lane-sb128c r7.
17631 pub(crate) static PART128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
17632 /// 128 roots that resolved to PARTITION_VERT (two 64x128 pieces).
17633 pub(crate) static PART128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
17634 /// Of those, the ones decided by the GATHERED bit at a frame edge -- the
17635 /// only shape a 1080p (mi_rows = 270) stream reaches.
17636 pub(crate) static PART128_EDGE_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
17637 pub(crate) static PART128_EDGE_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
17638 /// lane-sb128c r9: 128 roots that resolved to one of the four AB shapes,
17639 /// in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order.
17640 pub(crate) static PART128_AB_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
17641}
17642
17643/// [`PART128_AB_HITS`], for a gate's own before/after delta.
17644pub(crate) fn part128_ab_hits() -> [usize; 4] {
17645 PART128_AB_HITS.with(std::cell::Cell::get)
17646}
17647
17648/// [`PART128_NONE_HITS`], for a gate's own before/after delta.
17649pub(crate) fn part128_none_hits() -> usize {
17650 PART128_NONE_HITS.with(std::cell::Cell::get)
17651}
17652
17653/// [`PART128_HORZ_HITS`], for a gate's own before/after delta.
17654pub(crate) fn part128_horz_hits() -> usize {
17655 PART128_HORZ_HITS.with(std::cell::Cell::get)
17656}
17657
17658/// [`PART128_VERT_HITS`], for a gate's own before/after delta.
17659pub(crate) fn part128_vert_hits() -> usize {
17660 PART128_VERT_HITS.with(std::cell::Cell::get)
17661}
17662
17663/// [`PART128_EDGE_HORZ_HITS`] -- gathered-bit HORZ at the bottom frame edge.
17664pub(crate) fn part128_edge_horz_hits() -> usize {
17665 PART128_EDGE_HORZ_HITS.with(std::cell::Cell::get)
17666}
17667
17668/// [`PART128_EDGE_VERT_HITS`] -- gathered-bit VERT at the right frame edge.
17669pub(crate) fn part128_edge_vert_hits() -> usize {
17670 PART128_EDGE_VERT_HITS.with(std::cell::Cell::get)
17671}
17672
17673thread_local! {
17674 /// How many CHROMA transform units were coded inside a block whose uv
17675 /// plane block is more than one unit (lane-sb128b r2 -- only a 128x128
17676 /// block, four per plane).
17677 pub(crate) static CHROMA_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
17678}
17679
17680/// [`CHROMA_SPLIT_TX_HITS`], for a gate's own before/after delta.
17681pub(crate) fn chroma_split_tx_hits() -> usize {
17682 CHROMA_SPLIT_TX_HITS.with(std::cell::Cell::get)
17683}
17684
17685fn read_sb128_root(
17686 dec: &mut SymbolDecoder,
17687 cdfs: &mut Cdfs,
17688 neighbours: &Neighbours,
17689 lr: &LoopRestorationParams,
17690 lr_grid: &mut crate::restoration::RestorationGrid,
17691 lr_reference: &mut [(
17692 crate::restoration::WienerInfo,
17693 crate::restoration::SgrprojInfo,
17694 ); 3],
17695 sb_r: u32,
17696 sb_c: u32,
17697 mi_cols: u32,
17698 mi_rows: u32,
17699) -> Result<usize> {
17700 let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI);
17701 crate::restoration::read_lr(
17702 dec,
17703 cdfs,
17704 lr,
17705 lr_grid,
17706 lr_reference,
17707 mi_r128,
17708 mi_c128,
17709 SB_MI * 2,
17710 );
17711 let at128 = ((mi_r128 / SUB_MI) as usize, (mi_c128 / SUB_MI) as usize);
17712 let ctx128 = neighbours.partition_ctx(at128, 128);
17713 let (has_cols128, has_rows128) = (mi_c128 + SB_MI < mi_cols, mi_r128 + SB_MI < mi_rows);
17714 let part128 = if has_cols128 && has_rows128 {
17715 PART128_SYMBOLS.with(|c| c.set(c.get() + 1));
17716 let p = dec.symbol(&mut cdfs.partition_w128[ctx128]);
17717 if crate::envflags::env_flag!("EC_AV1_TRACE") {
17718 eprintln!("TRACE partition_w128 ctx={ctx128} value={p}");
17719 }
17720 p
17721 } else {
17722 // lane-sb128 r4: the gathered half-out-of-frame reads DECIDE the
17723 // partition, they are not a forced split -- exactly the discarded-bit
17724 // defect the 64 root carries a comment about at `partition_w64`'s
17725 // gathered arm. Value 1 is SPLIT; 0 is HORZ (rows out of frame) or
17726 // VERT (cols out of frame), which the refusal below then names
17727 // instead of silently reconstructing a split.
17728 PART128_GATHERED_SYMBOLS.with(|c| c.set(c.get() + 1));
17729 match (has_cols128, has_rows128) {
17730 (true, false) => {
17731 if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &VERT_ALIKE128)) == 1 {
17732 PARTITION_SPLIT
17733 } else {
17734 PART128_EDGE_HORZ_HITS.with(|c| c.set(c.get() + 1));
17735 PARTITION_HORZ
17736 }
17737 }
17738 (false, true) => {
17739 if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &HORZ_ALIKE128)) == 1 {
17740 PARTITION_SPLIT
17741 } else {
17742 PART128_EDGE_VERT_HITS.with(|c| c.set(c.get() + 1));
17743 PARTITION_VERT
17744 }
17745 }
17746 _ => {
17747 PART128_GATHERED_SYMBOLS.with(|c| c.set(c.get() - 1));
17748 bump_edge_both_cut(3);
17749 PARTITION_SPLIT
17750 }
17751 }
17752 };
17753 // lane-sb128b r1: `PARTITION_NONE` -- one 128x128 block -- is decoded by
17754 // the key-frame caller below. The six remaining arms (HORZ/VERT and the
17755 // four AB shapes) still need the rect/AB machinery at this size.
17756 // lane-sb128c r7: HORZ (two 128x64) and VERT (two 64x128) now decode on
17757 // both tile paths. The four AB shapes (libaom `decode_partition`'s
17758 // PARTITION_HORZ_A..VERT_B, decodeframe.c) still need the mixed
17759 // 128x64 + 64x64 + 64x64 visit order and stay refused by name; a 128
17760 // root has no 1:4 arm at all (`PARTITION_HORZ_4`/`VERT_4` are excluded
17761 // for BLOCK_128X128 by `av1_get_partition_cdf`'s 8-symbol alphabet,
17762 // which stops at VERT_B).
17763 match part128 {
17764 PARTITION_SPLIT => PART128_SPLIT_HITS.with(|c| c.set(c.get() + 1)),
17765 PARTITION_NONE => PART128_NONE_HITS.with(|c| c.set(c.get() + 1)),
17766 PARTITION_HORZ => PART128_HORZ_HITS.with(|c| c.set(c.get() + 1)),
17767 PARTITION_VERT => PART128_VERT_HITS.with(|c| c.set(c.get() + 1)),
17768 // lane-sb128c r9: the four AB shapes at the 128 root -- one
17769 // 128x64/64x128 half plus two 64x64 quadrants, decoded by both tile
17770 // paths below in libaom `decode_partition`'s own visit order.
17771 p if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&p) => {
17772 PART128_AB_HITS.with(|c| {
17773 let mut h = c.get();
17774 h[p - PARTITION_HORZ_A] += 1;
17775 c.set(h);
17776 });
17777 }
17778 _ => {
17779 return Err(unsupported(
17780 "a 128x128 superblock partition value outside the 8-symbol alphabet",
17781 ));
17782 }
17783 }
17784 Ok(part128)
17785}
17786
17787pub(crate) fn decode_key_frame_tile_with_cdfs(
17788 tiles: &[&[u8]],
17789 tile_info: &TileInfo,
17790 mi_cols: u32,
17791 mi_rows: u32,
17792 base_q_idx: u8,
17793 // lane-sbpart r11: this frame header's own per-plane DC/AC quantizer
17794 // deltas (spec 5.9.12), threaded to [`QUANT_DELTAS`] at the top of every
17795 // tile alongside [`CURRENT_Q_IDX`].
17796 deltas: crate::quant::QuantDeltas,
17797 frame_width: u32,
17798 frame_height: u32,
17799 enable_filter_intra: bool,
17800 enable_edge_filter: bool,
17801 cdef: &CdefParams,
17802 loop_filter: &LoopFilterParams,
17803 lr: &LoopRestorationParams,
17804 initial_cdfs: Option<Cdfs>,
17805 tx_select: bool,
17806 reduced_tx_set: bool,
17807 allow_screen_content_tools: bool,
17808 allow_intrabc: bool,
17809 // lane-realworld r4: this frame header's own `delta` (spec 5.9.17/5.9.18)
17810 // -- only `q_present`/`q_res` are actually read ([`maybe_read_delta_q`]);
17811 // `stream.rs` still refuses a frame with `lf_present` set before this
17812 // function is ever called.
17813 delta: DeltaParams,
17814) -> Result<(Picture, Cdfs)> {
17815 // lane-frame80: [`TX_SELECT_INTER`] is set by the INTER tile decoder
17816 // only, so a key frame decoded after an inter frame on this thread would
17817 // otherwise inherit it and read its `tx_depth` context off the inter
17818 // frame's stale `TXFM_CONTEXT` bands.
17819 TX_SELECT_INTER.with(|c| c.set(false));
17820 if mi_cols == 0 || mi_rows == 0 {
17821 return Err(unsupported("a frame with no mode-info grid"));
17822 }
17823 ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));
17824 let sb128 = sb128();
17825 if sb128 && allow_intrabc {
17826 return Err(unsupported(
17827 "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)",
17828 ));
17829 }
17830 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
17831 INTRABC_MI_GRID.with(|g| {
17832 *g.borrow_mut() = allow_intrabc.then(|| {
17833 (
17834 crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize),
17835 mi_cols as usize,
17836 mi_rows as usize,
17837 )
17838 });
17839 });
17840 INTRABC_DV.with(|c| c.set(None));
17841 CDEF_BITS.with(|c| c.set(cdef.bits));
17842 CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
17843 CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
17844 DELTA_Q_PRESENT.with(|c| c.set(delta.q_present));
17845 DELTA_Q_RES.with(|c| c.set(1i32 << delta.q_res));
17846 DELTA_LF_PRESENT.with(|c| c.set(delta.lf_present));
17847 DELTA_LF_RES.with(|c| c.set(1i32 << delta.lf_res));
17848 DELTA_LF_MULTI.with(|c| c.set(delta.lf_multi));
17849 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
17850 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
17851 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
17852
17853 let mut y = PlaneBuf {
17854 data: vec![0u16; width * height],
17855 width,
17856 height,
17857 true_width,
17858 true_height,
17859 tile_x0: 0,
17860 tile_y0: 0,
17861 tile_x1: width,
17862 tile_y1: height,
17863 };
17864 let mut u = PlaneBuf {
17865 data: vec![0u16; width * height / 4],
17866 width: width / 2,
17867 height: height / 2,
17868 true_width: true_width / 2,
17869 true_height: true_height / 2,
17870 tile_x0: 0,
17871 tile_y0: 0,
17872 tile_x1: width / 2,
17873 tile_y1: height / 2,
17874 };
17875 let mut v = PlaneBuf {
17876 data: vec![0u16; width * height / 4],
17877 width: width / 2,
17878 height: height / 2,
17879 true_width: true_width / 2,
17880 true_height: true_height / 2,
17881 tile_x0: 0,
17882 tile_y0: 0,
17883 tile_x1: width / 2,
17884 tile_y1: height / 2,
17885 };
17886
17887 let scan32 = default_scan(TX32);
17888 let scan16 = default_scan(TX16);
17889 let scan8 = default_scan(TX8);
17890 let scan4 = default_scan(TX4);
17891
17892 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
17893 let mut result_cdfs = base_cdfs.clone();
17894 let mut neighbours = Neighbours::new(
17895 cols32 as usize * 2,
17896 rows32 as usize * 2,
17897 mi_cols as usize,
17898 mi_rows as usize,
17899 );
17900 // spec 7.16/libaom `av1_alloc_restoration_struct`: the unit grid is
17901 // sized from `av1_get_upsampled_plane_size`, i.e. the UPSCALED width --
17902 // loop restoration runs after the superres upscale.
17903 let mut lr_grid = crate::restoration::RestorationGrid::new(
17904 lr,
17905 superres().map_or(frame_width, |(w, _)| w),
17906 frame_height,
17907 );
17908
17909 // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its
17910 // own byte range and its own fresh copy of the frame's initial CDFs
17911 // (spec 5.11.2 `decode_tile`'s `init_symbol`); only the tile named by
17912 // `context_update_tile_id` has its end-of-tile adapted table kept as the
17913 // frame's own output (spec `exit_symbol`) -- every other tile's
17914 // adaptation is discarded, matching the refusal this replaces.
17915 for (tile_idx, &tile_bytes) in tiles.iter().enumerate() {
17916 let tile_num = tile_idx as u32;
17917 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
17918 let mi_row0 = tile_info.mi_row_starts[trow as usize];
17919 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
17920 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
17921 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
17922 // Tile boundaries are always superblock-aligned in mi units (spec
17923 // 5.9.15's uniform/non-uniform derivation both only ever emit
17924 // multiples of the superblock's own mi size), so plain division is
17925 // exact here -- no rounding needed.
17926 // `mi_row0`/`mi_col0` (this tile's own start, `0` or an interior
17927 // tile boundary) are always superblock-aligned by spec 5.9.15; the
17928 // frame's own true final edge (`mi_row_starts`/`mi_col_starts`'
17929 // last entry) is not, so the upper bound needs `div_ceil` the same
17930 // way the whole-frame `sb_rows`/`sb_cols` above does, to keep the
17931 // trailing partial superblock row/column in scope.
17932 let (sb_r0, sb_r1) = ((mi_row0 / SB_MI).min(sb_rows), mi_row1.div_ceil(SB_MI).min(sb_rows));
17933 let (sb_c0, sb_c1) = ((mi_col0 / SB_MI).min(sb_cols), mi_col1.div_ceil(SB_MI).min(sb_cols));
17934
17935 // lane-t900 r19: spec 5.11.2 `decode_tile` resets `RefLrWiener` /
17936 // `RefSgrXqd` to the midpoint filter at the top of EVERY tile, not
17937 // once per frame. Carried across a tile boundary, the loop-restoration
17938 // coefficients of the next tile decode off the previous tile's
17939 // reference -- same symbol count, so entropy and reconstruction stay
17940 // exact and only the filtered pixels of every tile after the first
17941 // are wrong.
17942 let mut lr_reference = [(
17943 crate::restoration::WienerInfo::default(),
17944 crate::restoration::SgrprojInfo::default(),
17945 ); 3];
17946 let mut cdfs = base_cdfs.clone();
17947 // spec `decode_tile`: `CurrentQIndex` resets to the frame's own
17948 // `base_q_idx` at the top of every tile, not once per frame.
17949 CURRENT_Q_IDX.with(|c| c.set(i32::from(base_q_idx)));
17950 QUANT_DELTAS.with(|c| c.set(deltas));
17951 CURRENT_DELTA_LF.with(|c| c.set([0; 4]));
17952 if crate::envflags::env_flag!("EC_AV1_TRACE") {
17953 eprintln!(
17954 "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
17955 tile_bytes.len(),
17956 &tile_bytes[..tile_bytes.len().min(8)]
17957 );
17958 }
17959 let mut dec = SymbolDecoder::new(tile_bytes);
17960 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize);
17961 y.set_tile_origin(
17962 mi_col0 as usize * 4,
17963 mi_row0 as usize * 4,
17964 (mi_col1 as usize * 4).min(y.width),
17965 (mi_row1 as usize * 4).min(y.height),
17966 );
17967 u.set_tile_origin(
17968 mi_col0 as usize * 2,
17969 mi_row0 as usize * 2,
17970 (mi_col1 as usize * 2).min(u.width),
17971 (mi_row1 as usize * 2).min(u.height),
17972 );
17973 v.set_tile_origin(
17974 mi_col0 as usize * 2,
17975 mi_row0 as usize * 2,
17976 (mi_col1 as usize * 2).min(v.width),
17977 (mi_row1 as usize * 2).min(v.height),
17978 );
17979 TILE_HITS.with(|c| c.set(c.get() + 1));
17980
17981 // lane-sb128b r1: set when the 128 root resolved to `PARTITION_NONE` --
17982 // its one block covers all four 64x64 quadrants, so the remaining three
17983 // visits of this superblock code nothing at all.
17984 let mut sb128_none = false;
17985 for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) {
17986 if row_start {
17987 neighbours.start_row();
17988 }
17989 if sb_start {
17990 sb128_none = false;
17991 }
17992 if sb128_none {
17993 continue;
17994 }
17995 {
17996 // lane-sb128 r1: the 128 root. Its loop-restoration units are read
17997 // once for the whole 128x128 (spec 5.11.57 is called with the
17998 // superblock's own size), then one partition symbol off the
17999 // `BLOCK_128X128` CDF (8 symbols) decides the root -- only SPLIT
18000 // recurses into the four 64x64 quadrants this decoder codes.
18001 if sb128 && sb_start {
18002 let part128 = read_sb128_root(
18003 &mut dec,
18004 &mut cdfs,
18005 &neighbours,
18006 lr,
18007 &mut lr_grid,
18008 &mut lr_reference,
18009 sb_r,
18010 sb_c,
18011 mi_cols,
18012 mi_rows,
18013 )?;
18014 if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part128) {
18015 // lane-sb128c r9: the four AB shapes at the 128 root.
18016 // libaom `decode_partition` (decodeframe.c) codes each as
18017 // two `bsize2` (64x64) squares plus one `subsize`
18018 // (128x64 / 64x128) half, visited HORZ_A = TL, TR, bottom
18019 // half; HORZ_B = top half, BL, BR; VERT_A = TL, BL, right
18020 // half; VERT_B = left half, TR, BR. AB values only come
18021 // from the FULL alphabet symbol, which is only read when
18022 // both halves of the root are inside the frame, so no
18023 // piece needs libaom's `i > 0` frame-edge break (a piece
18024 // may still overhang the bottom/right, which
18025 // `PlaneBuf::reconstruct`'s r8 clip handles).
18026 sb128_none = true;
18027 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
18028 let (br, bc) = (at128.0 + 4, at128.1 + 4);
18029 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
18030 // Only the VERTICAL arms reorder the squares (TL, BL, TR,
18031 // BR), so only they switch libaom's `has_tr_vert_*` /
18032 // `has_bl_vert_*` tables (lane-sb128c r6 visit order).
18033 let _vert_ab =
18034 (part128 == PARTITION_VERT_A || part128 == PARTITION_VERT_B)
18035 .then(crate::encode::Reach::vert_ab_partition);
18036 // One `cdef_idx` literal per CODED BLOCK, at the first
18037 // non-skip one of each 64x64 CDEF unit; the 128x64 /
18038 // 64x128 half covers two units and its read lands in the
18039 // unit holding its origin, so that value is copied to the
18040 // other one (libaom: every mi of the block points at the
18041 // same `MB_MODE_INFO`).
18042 let cdef_copy = |src: (usize, usize), dst: (usize, usize)| {
18043 CDEF_IDX_GRID.with(|g| {
18044 let mut g = g.borrow_mut();
18045 let cols = CDEF_SB_COLS.with(|c| c.get());
18046 if cols == 0 {
18047 return;
18048 }
18049 let (si, di) = (
18050 (q_r + src.0) * cols + q_c + src.1,
18051 (q_r + dst.0) * cols + q_c + dst.1,
18052 );
18053 if q_c + src.1 < cols
18054 && q_c + dst.1 < cols
18055 && si < g.len()
18056 && di < g.len()
18057 {
18058 g[di] = g[si];
18059 }
18060 });
18061 };
18062 macro_rules! square64 {
18063 ($at:expr) => {{
18064 CDEF_TRANSMITTED.with(|c| c.set(false));
18065 decode_block(
18066 &mut dec,
18067 &mut cdfs,
18068 &mut neighbours,
18069 $at,
18070 SB,
18071 TxbSet::Luma64,
18072 TxbSet::Chroma32,
18073 TX32,
18074 TX32,
18075 (&scan32, &scan32),
18076 false,
18077 &mut y,
18078 &mut u,
18079 &mut v,
18080 base_q_idx,
18081 enable_filter_intra,
18082 allow_screen_content_tools,
18083 allow_intrabc,
18084 &scan32,
18085 &scan16,
18086 &scan8,
18087 &scan4,
18088 tx_select,
18089 reduced_tx_set,
18090 )?
18091 }};
18092 }
18093 macro_rules! half128 {
18094 ($at:expr, $bw:expr, $bh:expr, $src:expr, $dst:expr) => {{
18095 CDEF_TRANSMITTED.with(|c| c.set(false));
18096 decode_block_128rect(
18097 &mut dec,
18098 &mut cdfs,
18099 &mut neighbours,
18100 $at,
18101 $bw,
18102 $bh,
18103 &mut y,
18104 &mut u,
18105 &mut v,
18106 base_q_idx,
18107 enable_filter_intra,
18108 allow_screen_content_tools,
18109 tx_select,
18110 reduced_tx_set,
18111 )?;
18112 cdef_copy($src, $dst);
18113 }};
18114 }
18115 match part128 {
18116 PARTITION_HORZ_A => {
18117 square64!(at128);
18118 square64!((at128.0, bc));
18119 half128!((br, at128.1), 128, 64, (1, 0), (1, 1));
18120 }
18121 PARTITION_HORZ_B => {
18122 half128!(at128, 128, 64, (0, 0), (0, 1));
18123 square64!((br, at128.1));
18124 square64!((br, bc));
18125 }
18126 PARTITION_VERT_A => {
18127 square64!(at128);
18128 square64!((br, at128.1));
18129 half128!((at128.0, bc), 64, 128, (0, 1), (1, 1));
18130 }
18131 _ => {
18132 half128!(at128, 64, 128, (0, 0), (1, 0));
18133 square64!((at128.0, bc));
18134 square64!((br, bc));
18135 }
18136 }
18137 continue;
18138 }
18139 if matches!(part128, PARTITION_HORZ | PARTITION_VERT) {
18140 // lane-sb128c r8: libaom `decode_partition`
18141 // (decodeframe.c:1554) codes PARTITION_HORZ at the 128
18142 // root as `subsize = BLOCK_128X64` at (mi_row, mi_col)
18143 // plus a second one at (mi_row + hbs, mi_col) only
18144 // `if (mi_row + hbs < mi_rows)`; PARTITION_VERT mirrors it
18145 // on the column. `hbs` is `mi_size_high[BLOCK_128X128]/2`
18146 // = 16 mi. Both halves together cover the whole root, so
18147 // the remaining three 64x64 quadrant visits code nothing
18148 // (same flag the NONE arm sets).
18149 sb128_none = true;
18150 let horz = part128 == PARTITION_HORZ;
18151 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
18152 let (bw, bh) = if horz { (128usize, 64usize) } else { (64, 128) };
18153 for i in 0..2 {
18154 let at = if horz {
18155 (at128.0 + i * 4, at128.1)
18156 } else {
18157 (at128.0, at128.1 + i * 4)
18158 };
18159 let (blk_mi_r, blk_mi_c) = (at.0 * (SUB / MI), at.1 * (SUB / MI));
18160 if i > 0
18161 && (blk_mi_r >= mi_rows as usize || blk_mi_c >= mi_cols as usize)
18162 {
18163 break;
18164 }
18165 // Each half reads its OWN `cdef_idx` literal
18166 // (libaom `read_cdef` keys the `-1` test on the
18167 // block's own `MB_MODE_INFO`, and the two halves have
18168 // different ones).
18169 CDEF_TRANSMITTED.with(|c| c.set(false));
18170 decode_block_128rect(
18171 &mut dec,
18172 &mut cdfs,
18173 &mut neighbours,
18174 at,
18175 bw,
18176 bh,
18177 &mut y,
18178 &mut u,
18179 &mut v,
18180 base_q_idx,
18181 enable_filter_intra,
18182 allow_screen_content_tools,
18183 tx_select,
18184 reduced_tx_set,
18185 )?;
18186 }
18187 // One `cdef_idx` per BLOCK, copied to every 64x64 CDEF
18188 // unit it covers (the inter path's own fan-out).
18189 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
18190 CDEF_IDX_GRID.with(|g| {
18191 let mut g = g.borrow_mut();
18192 let cols = CDEF_SB_COLS.with(|c| c.get());
18193 if cols == 0 {
18194 return;
18195 }
18196 for (src, dst) in if horz {
18197 [((0, 0), (0, 1)), ((1, 0), (1, 1))]
18198 } else {
18199 [((0, 0), (1, 0)), ((0, 1), (1, 1))]
18200 } {
18201 let (si, di) = (
18202 (q_r + src.0) * cols + q_c + src.1,
18203 (q_r + dst.0) * cols + q_c + dst.1,
18204 );
18205 if q_c + src.1 < cols
18206 && q_c + dst.1 < cols
18207 && si < g.len()
18208 && di < g.len()
18209 {
18210 g[di] = g[si];
18211 }
18212 }
18213 });
18214 continue;
18215 }
18216 if part128 == PARTITION_NONE {
18217 // One 128x128 intra block: four TX_64X64 luma units and a
18218 // single 64x64 chroma unit per plane (`av1_get_max_uv_txsize`
18219 // of a 128x128 block is TX_64X64 over its 64x64 uv plane
18220 // block). No CfL, no filter intra, no palette at this size --
18221 // [`read_intra_mode`]'s own size gates already say so.
18222 sb128_none = true;
18223 CDEF_TRANSMITTED.with(|c| c.set(false));
18224 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
18225 decode_block(
18226 &mut dec,
18227 &mut cdfs,
18228 &mut neighbours,
18229 at128,
18230 SB * 2,
18231 TxbSet::Luma64,
18232 TxbSet::Chroma32,
18233 TX32,
18234 TX32,
18235 (&scan32, &scan32),
18236 false,
18237 &mut y,
18238 &mut u,
18239 &mut v,
18240 base_q_idx,
18241 enable_filter_intra,
18242 allow_screen_content_tools,
18243 allow_intrabc,
18244 &scan32,
18245 &scan16,
18246 &scan8,
18247 &scan4,
18248 tx_select,
18249 reduced_tx_set,
18250 )?;
18251 // libaom writes one `cdef_strength` into the block's own
18252 // `MB_MODE_INFO`, which every mi cell of the block --
18253 // hence all four 64x64 CDEF units -- points at; our grid
18254 // is per-unit, so the read (which only ever lands in the
18255 // top-left unit, `read_cdef`'s index 0) is copied across.
18256 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
18257 CDEF_IDX_GRID.with(|g| {
18258 let mut g = g.borrow_mut();
18259 let cols = CDEF_SB_COLS.with(|c| c.get());
18260 if cols > 0 && q_r * cols + q_c < g.len() {
18261 let idx = g[q_r * cols + q_c];
18262 for (dr, dc) in [(0, 1), (1, 0), (1, 1)] {
18263 let i = (q_r + dr) * cols + q_c + dc;
18264 if q_c + dc < cols && i < g.len() {
18265 g[i] = idx;
18266 }
18267 }
18268 }
18269 });
18270 continue;
18271 }
18272 }
18273 if !sb128 {
18274 crate::restoration::read_lr(
18275 &mut dec,
18276 &mut cdfs,
18277 lr,
18278 &mut lr_grid,
18279 &mut lr_reference,
18280 sb_r * SB_MI,
18281 sb_c * SB_MI,
18282 SB_MI,
18283 );
18284 }
18285 CDEF_TRANSMITTED.with(|c| c.set(false));
18286 let at = (sb_r as usize * 4, sb_c as usize * 4);
18287 let ctx = neighbours.partition_ctx(at, SB);
18288 let (has_cols, has_rows) = (
18289 sb_c * SB_MI + SB_MI / 2 < mi_cols,
18290 sb_r * SB_MI + SB_MI / 2 < mi_rows,
18291 );
18292 // Recomputed at this superblock's own half (spec
18293 // `decode_partition`): a full alphabet symbol when both halves are
18294 // inside the true frame, a single gathered bit when just one is
18295 // (the superblock cannot be left whole, so this is forced split),
18296 // and nothing at all (SPLIT inferred, no bits) when neither is —
18297 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
18298 // three-way write exactly.
18299 let part = if has_cols && has_rows {
18300 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
18301 if crate::envflags::env_flag!("EC_AV1_TRACE") {
18302 eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
18303 }
18304 p
18305 } else {
18306 // lane-hgkf r1 (class `parsed-then-discarded`, same finding as
18307 // the unmerged lane-golomb r1): the gathered bit IS the
18308 // partition -- libaom `ec_read_partition_impl` returns
18309 // PARTITION_HORZ (resp. VERT) for 0 and only SPLIT for 1.
18310 // Forcing SPLIT desynced the last superblock row of every
18311 // frame whose height is not a multiple of 64: the ReelB key frames (3840x1608) diverge at mi_row=400 mi_col=0,
18312 // the first block of that row.
18313 match (has_cols, has_rows) {
18314 (true, false) => {
18315 trace_edge((sb_r * SB_MI) as usize, (sb_c * SB_MI) as usize, 12, ctx, dec.debug_state().0 as u32);
18316 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
18317 bump_edge32(4 + b.min(1) as usize);
18318 bump_edge_part(b.min(1) as usize);
18319 if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ }
18320 }
18321 (false, true) => {
18322 trace_edge((sb_r * SB_MI) as usize, (sb_c * SB_MI) as usize, 12, ctx, dec.debug_state().0 as u32);
18323 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
18324 bump_edge32(4 + b.min(1) as usize);
18325 bump_edge_part(b.min(1) as usize);
18326 if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT }
18327 }
18328 _ => {
18329 bump_edge_both_cut(2);
18330 PARTITION_SPLIT
18331 }
18332 }
18333 };
18334 match part {
18335 PARTITION_NONE => {
18336 decode_block(
18337 &mut dec,
18338 &mut cdfs,
18339 &mut neighbours,
18340 at,
18341 SB,
18342 TxbSet::Luma64,
18343 TxbSet::Chroma32,
18344 TX32,
18345 TX32,
18346 (&scan32, &scan32),
18347 false,
18348 &mut y,
18349 &mut u,
18350 &mut v,
18351 base_q_idx,
18352 enable_filter_intra,
18353 allow_screen_content_tools,
18354 allow_intrabc,
18355 &scan32,
18356 &scan16,
18357 &scan8,
18358 &scan4,
18359 tx_select,
18360 reduced_tx_set,
18361 )?;
18362 }
18363 PARTITION_SPLIT => {
18364 for q in 0..4 {
18365 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
18366 if r32 >= rows32 || c32 >= cols32 {
18367 continue;
18368 }
18369 let at32 = (r32 as usize * 2, c32 as usize * 2);
18370 let ctx32 = neighbours.partition_ctx(at32, BLOCK);
18371 let (has_cols32, has_rows32) = (
18372 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
18373 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
18374 );
18375 let part32 = if has_cols32 && has_rows32 {
18376 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
18377 if crate::envflags::env_flag!("EC_AV1_TRACE") {
18378 let (rng, _) = dec.debug_state();
18379 eprintln!(
18380 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p} rng={rng}",
18381 r32 * BLOCK_MI,
18382 c32 * BLOCK_MI
18383 );
18384 }
18385 p
18386 } else {
18387 // lane-hgkf r1: the 32-level frame-edge bit is the
18388 // partition too (same libaom reader as the
18389 // superblock level above).
18390 match (has_cols32, has_rows32) {
18391 (true, false) => {
18392 trace_edge((r32 * BLOCK_MI) as usize, (c32 * BLOCK_MI) as usize, 9, ctx32, dec.debug_state().0 as u32);
18393 let b = dec.symbol_fixed(&gather(
18394 &cdfs.partition_w32[ctx32],
18395 VERT_ALIKE,
18396 ));
18397 bump_edge32(b.min(1) as usize);
18398 bump_edge_part(2 + b.min(1) as usize);
18399 if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ }
18400 }
18401 (false, true) => {
18402 trace_edge((r32 * BLOCK_MI) as usize, (c32 * BLOCK_MI) as usize, 9, ctx32, dec.debug_state().0 as u32);
18403 let b = dec.symbol_fixed(&gather(
18404 &cdfs.partition_w32[ctx32],
18405 HORZ_ALIKE,
18406 ));
18407 bump_edge32(b.min(1) as usize);
18408 bump_edge_part(2 + b.min(1) as usize);
18409 if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT }
18410 }
18411 _ => {
18412 bump_edge_both_cut(1);
18413 PARTITION_SPLIT
18414 }
18415 }
18416 };
18417 match part32 {
18418 PARTITION_NONE => {
18419 decode_block(
18420 &mut dec,
18421 &mut cdfs,
18422 &mut neighbours,
18423 at32,
18424 BLOCK,
18425 TxbSet::Luma32,
18426 TxbSet::Chroma16,
18427 TX32,
18428 TX16,
18429 (&scan32, &scan16),
18430 true,
18431 &mut y,
18432 &mut u,
18433 &mut v,
18434 base_q_idx,
18435 enable_filter_intra,
18436 allow_screen_content_tools,
18437 allow_intrabc,
18438 &scan32,
18439 &scan16,
18440 &scan8,
18441 &scan4,
18442 tx_select,
18443 reduced_tx_set,
18444 )?;
18445 }
18446 PARTITION_SPLIT => {
18447 for sub in 0..4 {
18448 let (sr, sc) =
18449 (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
18450 if (sr as u32) * SUB_MI >= mi_rows
18451 || (sc as u32) * SUB_MI >= mi_cols
18452 {
18453 continue;
18454 }
18455 let (has_cols16, has_rows16) = (
18456 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
18457 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
18458 );
18459 let at16 = (sr, sc);
18460 let ctx16 = neighbours.partition_ctx(at16, SUB);
18461 if has_cols16 && has_rows16 {
18462 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
18463 if crate::envflags::env_flag!("EC_AV1_TRACE") {
18464 eprintln!(
18465 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}",
18466 at16.0, at16.1
18467 );
18468 }
18469 if part16 == PARTITION_NONE {
18470 decode_block(
18471 &mut dec,
18472 &mut cdfs,
18473 &mut neighbours,
18474 at16,
18475 SUB,
18476 TxbSet::Luma16,
18477 TxbSet::Chroma8,
18478 TX16,
18479 TX8,
18480 (&scan16, &scan8),
18481 true,
18482 &mut y,
18483 &mut u,
18484 &mut v,
18485 base_q_idx,
18486 enable_filter_intra,
18487 allow_screen_content_tools,
18488 allow_intrabc,
18489 &scan32,
18490 &scan16,
18491 &scan8,
18492 &scan4,
18493 tx_select,
18494 reduced_tx_set,
18495 )?;
18496 continue;
18497 }
18498 if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part16) {
18499 // lane-ab16 r1: the four AB (T-shaped) partitions at the 16x16
18500 // level -- two 8x8 squares plus one 16x8/8x16 strip. libaom's
18501 // `decode_partition` visit order (decodeframe.c):
18502 // HORZ_A: TL 8x8, TR 8x8, bottom 16x8
18503 // HORZ_B: top 16x8, BL 8x8, BR 8x8
18504 // VERT_A: TL 8x8, BL 8x8, right 8x16
18505 // VERT_B: left 8x16, TR 8x8, BR 8x8
18506 // The squares go through `decode_leaf8`, the strip through
18507 // `decode_leaf_rect` (real, non-skip 16x8/8x16 coefficients --
18508 // lane-rectx r2-r4; the older `decode_block_rect` this VERT_B arm
18509 // used refuses the non-skip case at this size). Both writers keep
18510 // mi-granular mode/skip/palette records, so a later block's
18511 // `above_mi`/`left_mi` sees the real sub-block, not the coarse
18512 // 16x16 cell.
18513 //
18514 // VERT_A/VERT_B visit TL,BL,TR,BR, so the bottom-left square's
18515 // top-right neighbour is the partition's own not-yet-decoded
18516 // rectangle: libaom switches those squares onto `has_tr_vert_*`/
18517 // `has_bl_vert_*` (`reconintra.c` `get_has_tr_table`), which is
18518 // `Reach::vert_ab_partition()` (lane-part32 r5, cherry-picked here).
18519 let arm = part16 - PARTITION_HORZ_A;
18520 bump_ab16(arm);
18521 if part16 == PARTITION_VERT_B {
18522 VERT_B_INTRA_HITS.with(|c| c.set(c.get() + 1));
18523 }
18524 let _vert_guard = if part16 == PARTITION_VERT_A || part16 == PARTITION_VERT_B {
18525 Some(crate::encode::Reach::vert_ab_partition())
18526 } else {
18527 None
18528 };
18529 let (mi_row0, mi_col0) = (sr * SUB_MI as usize, sc * SUB_MI as usize);
18530 macro_rules! ab_leaf8 {
18531 ($mi:expr, $prev:expr) => {
18532 decode_leaf8(
18533 &mut dec,
18534 &mut cdfs,
18535 &mut neighbours,
18536 at16,
18537 $mi,
18538 (&scan8, &scan4),
18539 $prev,
18540 &mut y,
18541 &mut u,
18542 &mut v,
18543 base_q_idx,
18544 enable_filter_intra,
18545 allow_screen_content_tools,
18546 allow_intrabc,
18547 tx_select,
18548 reduced_tx_set,
18549 )?
18550 };
18551 }
18552 macro_rules! ab_strip {
18553 ($mi:expr, $bw:expr, $bh:expr, $prev:expr) => {
18554 decode_leaf_rect(
18555 &mut dec,
18556 &mut cdfs,
18557 &mut neighbours,
18558 at16,
18559 $mi,
18560 $bw,
18561 $bh,
18562 $prev,
18563 &mut y,
18564 &mut u,
18565 &mut v,
18566 enable_filter_intra,
18567 allow_screen_content_tools,
18568 base_q_idx,
18569 tx_select,
18570 reduced_tx_set,
18571 )?
18572 };
18573 }
18574 let tl = (mi_row0, mi_col0);
18575 let tr = (mi_row0, mi_col0 + 2);
18576 let bl = (mi_row0 + 2, mi_col0);
18577 let br = (mi_row0 + 2, mi_col0 + 2);
18578 let mut done: Vec<((usize, usize), usize)> = Vec::new();
18579 match part16 {
18580 PARTITION_HORZ_A => {
18581 let m_tl = ab_leaf8!(tl, done.last().copied());
18582 done.push((tl, m_tl));
18583 let m_tr = ab_leaf8!(tr, done.last().copied());
18584 done.push((tr, m_tr));
18585 let m_bot = ab_strip!(bl, 16, 8, Some((tl, m_tl)));
18586 done.push((bl, m_bot));
18587 }
18588 PARTITION_HORZ_B => {
18589 let m_top = ab_strip!(tl, 16, 8, None);
18590 done.push((tl, m_top));
18591 let m_bl = ab_leaf8!(bl, done.last().copied());
18592 done.push((bl, m_bl));
18593 let m_br = ab_leaf8!(br, done.last().copied());
18594 done.push((br, m_br));
18595 }
18596 PARTITION_VERT_A => {
18597 let m_tl = ab_leaf8!(tl, done.last().copied());
18598 done.push((tl, m_tl));
18599 let m_bl = ab_leaf8!(bl, done.last().copied());
18600 done.push((bl, m_bl));
18601 let m_right = ab_strip!(tr, 8, 16, Some((tl, m_tl)));
18602 done.push((tr, m_right));
18603 }
18604 _ => {
18605 let m_left = ab_strip!(tl, 8, 16, None);
18606 done.push((tl, m_left));
18607 let m_tr = ab_leaf8!(tr, done.last().copied());
18608 done.push((tr, m_tr));
18609 let m_br = ab_leaf8!(br, done.last().copied());
18610 done.push((br, m_br));
18611 }
18612 }
18613 // Same coarse-slot write-back the real SPLIT path takes: the
18614 // 16x16 cell's single `above_mode`/`left_mode` entry gets the
18615 // sub-block on the parent's bottom / right edge (the mi-exact map
18616 // above wins wherever it has an entry).
18617 write_back_split_modes(&mut neighbours, &done, (mi_row0, mi_col0), (sr, sc));
18618 continue;
18619 }
18620 if part16 == PARTITION_HORZ {
18621 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
18622 let (mi_row0, mi_col0) = (
18623 sr as u32 * SUB_MI,
18624 sc as u32 * SUB_MI,
18625 );
18626 let top = (mi_row0 as usize, mi_col0 as usize);
18627 let bot = (mi_row0 as usize + 2, mi_col0 as usize);
18628 let mode_top = decode_leaf_rect(
18629 &mut dec,
18630 &mut cdfs,
18631 &mut neighbours,
18632 at16,
18633 top,
18634 16,
18635 8,
18636 None,
18637 &mut y,
18638 &mut u,
18639 &mut v,
18640 enable_filter_intra,
18641 allow_screen_content_tools,
18642 base_q_idx,
18643 tx_select,
18644 reduced_tx_set,
18645 )?;
18646 let mode_bot = decode_leaf_rect(
18647 &mut dec,
18648 &mut cdfs,
18649 &mut neighbours,
18650 at16,
18651 bot,
18652 16,
18653 8,
18654 Some((top, mode_top)),
18655 &mut y,
18656 &mut u,
18657 &mut v,
18658 enable_filter_intra,
18659 allow_screen_content_tools,
18660 base_q_idx,
18661 tx_select,
18662 reduced_tx_set,
18663 )?;
18664 neighbours.above_mode[sc] = mode_bot;
18665 neighbours.left_mode[sr] = mode_bot;
18666 continue;
18667 }
18668 if part16 == PARTITION_VERT {
18669 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
18670 let (mi_row0, mi_col0) = (
18671 sr as u32 * SUB_MI,
18672 sc as u32 * SUB_MI,
18673 );
18674 let left = (mi_row0 as usize, mi_col0 as usize);
18675 let right = (mi_row0 as usize, mi_col0 as usize + 2);
18676 let mode_left = decode_leaf_rect(
18677 &mut dec,
18678 &mut cdfs,
18679 &mut neighbours,
18680 at16,
18681 left,
18682 8,
18683 16,
18684 None,
18685 &mut y,
18686 &mut u,
18687 &mut v,
18688 enable_filter_intra,
18689 allow_screen_content_tools,
18690 base_q_idx,
18691 tx_select,
18692 reduced_tx_set,
18693 )?;
18694 let mode_right = decode_leaf_rect(
18695 &mut dec,
18696 &mut cdfs,
18697 &mut neighbours,
18698 at16,
18699 right,
18700 8,
18701 16,
18702 Some((left, mode_left)),
18703 &mut y,
18704 &mut u,
18705 &mut v,
18706 enable_filter_intra,
18707 allow_screen_content_tools,
18708 base_q_idx,
18709 tx_select,
18710 reduced_tx_set,
18711 )?;
18712 neighbours.above_mode[sc] = mode_right;
18713 neighbours.left_mode[sr] = mode_right;
18714 continue;
18715 }
18716 if part16 == PARTITION_HORZ_4
18717 || part16 == PARTITION_VERT_4
18718 {
18719 decode_rect4_16(
18720 &mut dec,
18721 &mut cdfs,
18722 &mut neighbours,
18723 at16,
18724 part16 == PARTITION_HORZ_4,
18725 &mut y,
18726 &mut u,
18727 &mut v,
18728 enable_filter_intra,
18729 allow_screen_content_tools,
18730 base_q_idx,
18731 tx_select,
18732 reduced_tx_set,
18733 )?;
18734 continue;
18735 }
18736 // lane-r14 r2 (verifier note): every
18737 // one of the 10 symbols this CDF can
18738 // produce is handled above, so SPLIT
18739 // is the only value that reaches
18740 // here -- the refusal that used to
18741 // stand here was unreachable and is
18742 // gone from `refusal_inventory`.
18743 debug_assert_eq!(part16, PARTITION_SPLIT);
18744 // A real (non-straddle) SPLIT of a
18745 // whole 16x16 into four 8x8 leaves --
18746 // the same recursion the straddle
18747 // path below already runs when the
18748 // true frame edge forces it, just
18749 // over all four positions instead of
18750 // the one or two the edge leaves.
18751 let (mi_row0, mi_col0) =
18752 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
18753 // Each 8x8 leaf's intra-mode context
18754 // must see its own siblings: the
18755 // bottom-left leaf's ABOVE neighbour
18756 // is leaf 0, not the previously
18757 // decoded leaf 1 (and the bottom-right
18758 // leaf's above is leaf 1, while
18759 // `prev_leaf` only ever carried the
18760 // immediately preceding one). The
18761 // coarse `above_mode`/`left_mode`
18762 // arrays hold one slot per 16x16, so
18763 // the sibling modes are swapped in
18764 // around each leaf call and restored
18765 // after; the loop tail writes the last
18766 // leaf's mode as before.
18767 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
18768 for i in 0..4 {
18769 let (mr, mc) =
18770 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
18771 let leaf_mi = (mr as usize, mc as usize);
18772 let li = i as usize;
18773 let saved_modes =
18774 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
18775 if li >= 2 {
18776 if let Some((below, _)) = sib_modes[li - 2] {
18777 neighbours.above_mode[sc] = below;
18778 }
18779 }
18780 if li % 2 == 1 {
18781 if let Some((_, right)) = sib_modes[li - 1] {
18782 neighbours.left_mode[sr] = right;
18783 }
18784 }
18785 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
18786 let part8 =
18787 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
18788 if crate::envflags::env_flag!("EC_AV1_TRACE") {
18789 eprintln!(
18790 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
18791 );
18792 }
18793 let leaf_mode = if part8 == PARTITION_NONE {
18794 decode_leaf8(
18795 &mut dec,
18796 &mut cdfs,
18797 &mut neighbours,
18798 at16,
18799 leaf_mi,
18800 (&scan8, &scan4),
18801 None,
18802 &mut y,
18803 &mut u,
18804 &mut v,
18805 base_q_idx,
18806 enable_filter_intra,
18807 allow_screen_content_tools,
18808 allow_intrabc,
18809 tx_select,
18810 reduced_tx_set,
18811 ).map(|m| (m, m))?
18812 } else if part8 == PARTITION_SPLIT {
18813 decode_leaf_split4(
18814 &mut dec,
18815 &mut cdfs,
18816 &mut neighbours,
18817 at16,
18818 leaf_mi,
18819 &scan4,
18820 None,
18821 &mut y,
18822 &mut u,
18823 &mut v,
18824 base_q_idx,
18825 enable_filter_intra,
18826 allow_intrabc,
18827 reduced_tx_set,
18828 )?
18829 } else if part8 == PARTITION_HORZ
18830 || part8 == PARTITION_VERT
18831 {
18832 decode_leaf_rect8(
18833 &mut dec,
18834 &mut cdfs,
18835 &mut neighbours,
18836 at16,
18837 leaf_mi,
18838 part8 == PARTITION_VERT,
18839 &scan4,
18840 &mut y,
18841 &mut u,
18842 &mut v,
18843 base_q_idx,
18844 enable_filter_intra,
18845 allow_intrabc,
18846 tx_select,
18847 reduced_tx_set,
18848 )?
18849 } else {
18850 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
18851 };
18852 neighbours.above_mode[sc] = saved_modes.0;
18853 neighbours.left_mode[sr] = saved_modes.1;
18854 sib_modes[li] = Some(leaf_mode);
18855 }
18856 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
18857 neighbours.above_mode[sc] = below;
18858 }
18859 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
18860 neighbours.left_mode[sr] = right;
18861 }
18862 continue;
18863 }
18864 // The true edge falls inside this 16x16
18865 // leaf itself (mod-32==8 target sizes,
18866 // lane-av1-rect): one axis only -- an 8x8
18867 // leaf never itself straddles, so the
18868 // block splits cleanly along whichever
18869 // axis is short.
18870 // lane-edgeboth r1: when the true frame
18871 // edge cuts BOTH axes libaom's
18872 // `decode_partition` takes
18873 // `else if (!has_rows && !has_cols)
18874 // partition = PARTITION_SPLIT;` -- no
18875 // symbol of any kind is read, and the four
18876 // 8x8 children are then visited by the
18877 // same loop below, whose
18878 // `mr < mi_rows && mc < mi_cols` filter IS
18879 // libaom's own
18880 // `if (mi_row >= mi_rows || mi_col >= mi_cols) return;`
18881 // early return, so the three out-of-frame
18882 // quadrants get no neighbour or tx-grid
18883 // write.
18884 if !has_cols16 && !has_rows16 {
18885 bump_edge_both_cut(0);
18886 } else {
18887 // lane-golomb r1 (class
18888 // `parsed-then-discarded`): the gathered
18889 // bit IS the partition -- 0 names
18890 // PARTITION_HORZ (resp. VERT), only 1 is
18891 // SPLIT (libaom `ec_read_partition_impl`).
18892 // This path can only walk the four SPLIT
18893 // leaves, so a 0 refuses by name instead
18894 // of desyncing.
18895 trace_edge(sr * SUB_MI as usize, sc * SUB_MI as usize, 6, ctx16, dec.debug_state().0 as u32);
18896 let edge_split = if has_cols16 {
18897 dec.symbol_fixed(&gather(
18898 &cdfs.partition_w16[ctx16],
18899 VERT_ALIKE,
18900 ))
18901 } else {
18902 dec.symbol_fixed(&gather(
18903 &cdfs.partition_w16[ctx16],
18904 HORZ_ALIKE,
18905 ))
18906 };
18907 // lane-hgkf r1: slots 2/3 of
18908 // [`EDGE_PART_HITS`], the gate's proof the
18909 // non-SPLIT edge arm actually decoded.
18910 bump_edge_part(if edge_split == 1 { 3 } else { 2 });
18911 if edge_split == 0 {
18912 // lane-oddh r1: the strip IS decodable
18913 // -- libaom's `decode_partition` codes
18914 // only the FIRST half of an edge
18915 // HORZ/VERT (the second call is
18916 // guarded by the same has_rows/
18917 // has_cols test that made the
18918 // partition non-square), so one
18919 // 16x8 (resp. 8x16) strip covers the
18920 // whole visible band of a frame whose
18921 // height (resp. width) is 8 mod 16 --
18922 // the user's 3840x1608 film.
18923 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
18924 EDGE_RECT_STRIP_HITS.with(|c| c.set(c.get() + 1));
18925 let (mi_row0, mi_col0) =
18926 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
18927 let (bw, bh) = if has_cols16 { (16, 8) } else { (8, 16) };
18928 let mode = decode_leaf_rect(
18929 &mut dec,
18930 &mut cdfs,
18931 &mut neighbours,
18932 at16,
18933 (mi_row0 as usize, mi_col0 as usize),
18934 bw,
18935 bh,
18936 None,
18937 &mut y,
18938 &mut u,
18939 &mut v,
18940 enable_filter_intra,
18941 allow_screen_content_tools,
18942 base_q_idx,
18943 tx_select,
18944 reduced_tx_set,
18945 )?;
18946 neighbours.above_mode[sc] = mode;
18947 neighbours.left_mode[sr] = mode;
18948 continue;
18949 }
18950 }
18951 let (mi_row0, mi_col0) =
18952 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
18953 let leaf_positions: Vec<(u32, u32)> = (0..4)
18954 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
18955 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
18956 .collect();
18957 // See the sibling-mode note in the clean
18958 // SPLIT path above.
18959 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
18960 for (mr, mc) in leaf_positions {
18961 let leaf_mi = (mr as usize, mc as usize);
18962 let li = (((mr - mi_row0) / 2) * 2 + (mc - mi_col0) / 2)
18963 as usize;
18964 let saved_modes =
18965 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
18966 if li >= 2 {
18967 if let Some((below, _)) = sib_modes[li - 2] {
18968 neighbours.above_mode[sc] = below;
18969 }
18970 }
18971 if li % 2 == 1 {
18972 if let Some((_, right)) = sib_modes[li - 1] {
18973 neighbours.left_mode[sr] = right;
18974 }
18975 }
18976 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
18977 let pre8 = dec.debug_state().0;
18978 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
18979 if crate::envflags::env_flag!("EC_AV1_TRACE") {
18980 eprintln!(
18981 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8} pre_rng={pre8}"
18982 );
18983 }
18984 let leaf_mode = if part8 == PARTITION_NONE {
18985 decode_leaf8(
18986 &mut dec,
18987 &mut cdfs,
18988 &mut neighbours,
18989 at16,
18990 leaf_mi,
18991 (&scan8, &scan4),
18992 None,
18993 &mut y,
18994 &mut u,
18995 &mut v,
18996 base_q_idx,
18997 enable_filter_intra,
18998 allow_screen_content_tools,
18999 allow_intrabc,
19000 tx_select,
19001 reduced_tx_set,
19002 ).map(|m| (m, m))?
19003 } else if part8 == PARTITION_SPLIT {
19004 decode_leaf_split4(
19005 &mut dec,
19006 &mut cdfs,
19007 &mut neighbours,
19008 at16,
19009 leaf_mi,
19010 &scan4,
19011 None,
19012 &mut y,
19013 &mut u,
19014 &mut v,
19015 base_q_idx,
19016 enable_filter_intra,
19017 allow_intrabc,
19018 reduced_tx_set,
19019 )?
19020 } else if part8 == PARTITION_HORZ
19021 || part8 == PARTITION_VERT
19022 {
19023 decode_leaf_rect8(
19024 &mut dec,
19025 &mut cdfs,
19026 &mut neighbours,
19027 at16,
19028 leaf_mi,
19029 part8 == PARTITION_VERT,
19030 &scan4,
19031 &mut y,
19032 &mut u,
19033 &mut v,
19034 base_q_idx,
19035 enable_filter_intra,
19036 allow_intrabc,
19037 tx_select,
19038 reduced_tx_set,
19039 )?
19040 } else {
19041 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
19042 };
19043 neighbours.above_mode[sc] = saved_modes.0;
19044 neighbours.left_mode[sr] = saved_modes.1;
19045 sib_modes[li] = Some(leaf_mode);
19046 }
19047 // `record()`'s `above_mode`/`left_mode`
19048 // write is a no-op at an 8x8 leaf's own
19049 // side, so force the write once the whole
19050 // 16x16 slot's leaves are done, from the
19051 // last leaf (mirrors the writer's r15
19052 // fix).
19053 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
19054 neighbours.above_mode[sc] = below;
19055 }
19056 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
19057 neighbours.left_mode[sr] = right;
19058 }
19059 }
19060 }
19061 PARTITION_HORZ => {
19062 // lane-intradisp r1: two true 32x16 strips.
19063 decode_block_rect(
19064 &mut dec,
19065 &mut cdfs,
19066 &mut neighbours,
19067 at32,
19068 32,
19069 16,
19070 &mut y,
19071 &mut u,
19072 &mut v,
19073 enable_filter_intra,
19074 allow_screen_content_tools,
19075 base_q_idx,
19076 tx_select,
19077 reduced_tx_set,
19078 )?;
19079 if !has_rows32 {
19080 bump_edge32(2);
19081 }
19082 // lane-hgkf r1: at the frame edge only the first half of the strip is
19083 // coded (libaom `decode_partition` guards the second half with the same
19084 // test that made this partition non-square).
19085 if has_rows32 {
19086 decode_block_rect(
19087 &mut dec,
19088 &mut cdfs,
19089 &mut neighbours,
19090 (at32.0 + 1, at32.1),
19091 32,
19092 16,
19093 &mut y,
19094 &mut u,
19095 &mut v,
19096 enable_filter_intra,
19097 allow_screen_content_tools,
19098 base_q_idx,
19099 tx_select,
19100 reduced_tx_set,
19101 )?;
19102 }
19103 }
19104 PARTITION_VERT => {
19105 // lane-intradisp r1: mirror of PARTITION_HORZ
19106 // above with width/height swapped.
19107 decode_block_rect(
19108 &mut dec,
19109 &mut cdfs,
19110 &mut neighbours,
19111 at32,
19112 16,
19113 32,
19114 &mut y,
19115 &mut u,
19116 &mut v,
19117 enable_filter_intra,
19118 allow_screen_content_tools,
19119 base_q_idx,
19120 tx_select,
19121 reduced_tx_set,
19122 )?;
19123 if !has_cols32 {
19124 bump_edge32(3);
19125 }
19126 // lane-hgkf r1: at the frame edge only the first half of the strip is
19127 // coded (libaom `decode_partition` guards the second half with the same
19128 // test that made this partition non-square).
19129 if has_cols32 {
19130 decode_block_rect(
19131 &mut dec,
19132 &mut cdfs,
19133 &mut neighbours,
19134 (at32.0, at32.1 + 1),
19135 16,
19136 32,
19137 &mut y,
19138 &mut u,
19139 &mut v,
19140 enable_filter_intra,
19141 allow_screen_content_tools,
19142 base_q_idx,
19143 tx_select,
19144 reduced_tx_set,
19145 )?;
19146 }
19147 }
19148 PARTITION_HORZ_A => {
19149 // lane-part32 r1: two 16x16 squares on top +
19150 // a true 32x16 strip below (mirrors
19151 // decode_inter_block's cd6cb6d HORZ_A: TL,
19152 // TR, bottom strip).
19153 INTRA_HORZ_A_HITS.with(|c| c.set(c.get() + 1));
19154 decode_block(
19155 &mut dec,
19156 &mut cdfs,
19157 &mut neighbours,
19158 at32,
19159 SUB,
19160 TxbSet::Luma16,
19161 TxbSet::Chroma8,
19162 TX16,
19163 TX8,
19164 (&scan16, &scan8),
19165 true,
19166 &mut y,
19167 &mut u,
19168 &mut v,
19169 base_q_idx,
19170 enable_filter_intra,
19171 allow_screen_content_tools,
19172 allow_intrabc,
19173 &scan32,
19174 &scan16,
19175 &scan8,
19176 &scan4,
19177 tx_select,
19178 reduced_tx_set,
19179 )?;
19180 decode_block(
19181 &mut dec,
19182 &mut cdfs,
19183 &mut neighbours,
19184 (at32.0, at32.1 + 1),
19185 SUB,
19186 TxbSet::Luma16,
19187 TxbSet::Chroma8,
19188 TX16,
19189 TX8,
19190 (&scan16, &scan8),
19191 true,
19192 &mut y,
19193 &mut u,
19194 &mut v,
19195 base_q_idx,
19196 enable_filter_intra,
19197 allow_screen_content_tools,
19198 allow_intrabc,
19199 &scan32,
19200 &scan16,
19201 &scan8,
19202 &scan4,
19203 tx_select,
19204 reduced_tx_set,
19205 )?;
19206 decode_block_rect(
19207 &mut dec,
19208 &mut cdfs,
19209 &mut neighbours,
19210 (at32.0 + 1, at32.1),
19211 32,
19212 16,
19213 &mut y,
19214 &mut u,
19215 &mut v,
19216 enable_filter_intra,
19217 allow_screen_content_tools,
19218 base_q_idx,
19219 tx_select,
19220 reduced_tx_set,
19221 )?;
19222 }
19223 PARTITION_HORZ_B => {
19224 // lane-part32 r1: a true 32x16 strip on top +
19225 // two 16x16 squares below (mirrors HORZ_A
19226 // with the strip/squares order flipped, same
19227 // shape as libaom decode_partition's HORZ_B).
19228 INTRA_HORZ_B_HITS.with(|c| c.set(c.get() + 1));
19229 decode_block_rect(
19230 &mut dec,
19231 &mut cdfs,
19232 &mut neighbours,
19233 at32,
19234 32,
19235 16,
19236 &mut y,
19237 &mut u,
19238 &mut v,
19239 enable_filter_intra,
19240 allow_screen_content_tools,
19241 base_q_idx,
19242 tx_select,
19243 reduced_tx_set,
19244 )?;
19245 decode_block(
19246 &mut dec,
19247 &mut cdfs,
19248 &mut neighbours,
19249 (at32.0 + 1, at32.1),
19250 SUB,
19251 TxbSet::Luma16,
19252 TxbSet::Chroma8,
19253 TX16,
19254 TX8,
19255 (&scan16, &scan8),
19256 true,
19257 &mut y,
19258 &mut u,
19259 &mut v,
19260 base_q_idx,
19261 enable_filter_intra,
19262 allow_screen_content_tools,
19263 allow_intrabc,
19264 &scan32,
19265 &scan16,
19266 &scan8,
19267 &scan4,
19268 tx_select,
19269 reduced_tx_set,
19270 )?;
19271 decode_block(
19272 &mut dec,
19273 &mut cdfs,
19274 &mut neighbours,
19275 (at32.0 + 1, at32.1 + 1),
19276 SUB,
19277 TxbSet::Luma16,
19278 TxbSet::Chroma8,
19279 TX16,
19280 TX8,
19281 (&scan16, &scan8),
19282 true,
19283 &mut y,
19284 &mut u,
19285 &mut v,
19286 base_q_idx,
19287 enable_filter_intra,
19288 allow_screen_content_tools,
19289 allow_intrabc,
19290 &scan32,
19291 &scan16,
19292 &scan8,
19293 &scan4,
19294 tx_select,
19295 reduced_tx_set,
19296 )?;
19297 }
19298 PARTITION_VERT_A => {
19299 // lane-part32 r1: mirror of HORZ_A with
19300 // width/height swapped (TL, BL, right 16x32
19301 // strip).
19302 INTRA_VERT_A_HITS.with(|c| c.set(c.get() + 1));
19303 let _vert_ab = crate::encode::Reach::vert_ab_partition();
19304 decode_block(
19305 &mut dec,
19306 &mut cdfs,
19307 &mut neighbours,
19308 at32,
19309 SUB,
19310 TxbSet::Luma16,
19311 TxbSet::Chroma8,
19312 TX16,
19313 TX8,
19314 (&scan16, &scan8),
19315 true,
19316 &mut y,
19317 &mut u,
19318 &mut v,
19319 base_q_idx,
19320 enable_filter_intra,
19321 allow_screen_content_tools,
19322 allow_intrabc,
19323 &scan32,
19324 &scan16,
19325 &scan8,
19326 &scan4,
19327 tx_select,
19328 reduced_tx_set,
19329 )?;
19330 decode_block(
19331 &mut dec,
19332 &mut cdfs,
19333 &mut neighbours,
19334 (at32.0 + 1, at32.1),
19335 SUB,
19336 TxbSet::Luma16,
19337 TxbSet::Chroma8,
19338 TX16,
19339 TX8,
19340 (&scan16, &scan8),
19341 true,
19342 &mut y,
19343 &mut u,
19344 &mut v,
19345 base_q_idx,
19346 enable_filter_intra,
19347 allow_screen_content_tools,
19348 allow_intrabc,
19349 &scan32,
19350 &scan16,
19351 &scan8,
19352 &scan4,
19353 tx_select,
19354 reduced_tx_set,
19355 )?;
19356 decode_block_rect(
19357 &mut dec,
19358 &mut cdfs,
19359 &mut neighbours,
19360 (at32.0, at32.1 + 1),
19361 16,
19362 32,
19363 &mut y,
19364 &mut u,
19365 &mut v,
19366 enable_filter_intra,
19367 allow_screen_content_tools,
19368 base_q_idx,
19369 tx_select,
19370 reduced_tx_set,
19371 )?;
19372 }
19373 PARTITION_VERT_B => {
19374 // lane-part32 r1: a true 16x32 strip on the
19375 // left + two 16x16 squares on the right
19376 // (libaom decode_partition VERT_B: left
19377 // strip, TR, BR).
19378 INTRA_VERT_B_HITS.with(|c| c.set(c.get() + 1));
19379 let _vert_ab = crate::encode::Reach::vert_ab_partition();
19380 decode_block_rect(
19381 &mut dec,
19382 &mut cdfs,
19383 &mut neighbours,
19384 at32,
19385 16,
19386 32,
19387 &mut y,
19388 &mut u,
19389 &mut v,
19390 enable_filter_intra,
19391 allow_screen_content_tools,
19392 base_q_idx,
19393 tx_select,
19394 reduced_tx_set,
19395 )?;
19396 decode_block(
19397 &mut dec,
19398 &mut cdfs,
19399 &mut neighbours,
19400 (at32.0, at32.1 + 1),
19401 SUB,
19402 TxbSet::Luma16,
19403 TxbSet::Chroma8,
19404 TX16,
19405 TX8,
19406 (&scan16, &scan8),
19407 true,
19408 &mut y,
19409 &mut u,
19410 &mut v,
19411 base_q_idx,
19412 enable_filter_intra,
19413 allow_screen_content_tools,
19414 allow_intrabc,
19415 &scan32,
19416 &scan16,
19417 &scan8,
19418 &scan4,
19419 tx_select,
19420 reduced_tx_set,
19421 )?;
19422 decode_block(
19423 &mut dec,
19424 &mut cdfs,
19425 &mut neighbours,
19426 (at32.0 + 1, at32.1 + 1),
19427 SUB,
19428 TxbSet::Luma16,
19429 TxbSet::Chroma8,
19430 TX16,
19431 TX8,
19432 (&scan16, &scan8),
19433 true,
19434 &mut y,
19435 &mut u,
19436 &mut v,
19437 base_q_idx,
19438 enable_filter_intra,
19439 allow_screen_content_tools,
19440 allow_intrabc,
19441 &scan32,
19442 &scan16,
19443 &scan8,
19444 &scan4,
19445 tx_select,
19446 reduced_tx_set,
19447 )?;
19448 }
19449 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
19450 // lane-tx64x16 r3: the 1:4 pair at the 32x32
19451 // level -- four 32x8 (or 8x32) strips in
19452 // raster order, `quarter_step` = 2 mi, with
19453 // libaom `decode_partition`'s own `i > 0`
19454 // frame-edge break.
19455 let horz = part32 == PARTITION_HORZ_4;
19456 let base_mi = (at32.0 * (SUB / MI), at32.1 * (SUB / MI));
19457 let mut prev: Option<((usize, usize), usize)> = None;
19458 for i in 0..4 {
19459 let strip_mi = if horz {
19460 (base_mi.0 + i * 2, base_mi.1)
19461 } else {
19462 (base_mi.0, base_mi.1 + i * 2)
19463 };
19464 if i > 0
19465 && (strip_mi.0 >= mi_rows as usize
19466 || strip_mi.1 >= mi_cols as usize)
19467 {
19468 break;
19469 }
19470 let (bw, bh) = if horz { (32, 8) } else { (8, 32) };
19471 let (mode, _uv) = decode_block_rect4(
19472 &mut dec,
19473 &mut cdfs,
19474 &mut neighbours,
19475 strip_mi,
19476 bw,
19477 bh,
19478 prev,
19479 &mut y,
19480 &mut u,
19481 &mut v,
19482 enable_filter_intra,
19483 allow_screen_content_tools,
19484 base_q_idx,
19485 tx_select,
19486 )?;
19487 prev = Some((strip_mi, mode));
19488 }
19489 }
19490 _ => {
19491 return Err(unsupported(format!(
19492 "a 32x32 partition type this decoder does not code (value={part32})"
19493 )));
19494 }
19495 }
19496 }
19497 }
19498 PARTITION_HORZ => {
19499 // lane-sbpart r2: two true 64x32 strips.
19500 decode_block_rect64(
19501 &mut dec,
19502 &mut cdfs,
19503 &mut neighbours,
19504 at,
19505 64,
19506 32,
19507 &mut y,
19508 &mut u,
19509 &mut v,
19510 enable_filter_intra,
19511 allow_screen_content_tools,
19512 base_q_idx,
19513 tx_select,
19514 reduced_tx_set,
19515 )?;
19516 if !has_rows {
19517 bump_edge32(6);
19518 }
19519 // lane-golomb r1: at the frame edge only the first half of the
19520 // strip is coded (libaom `decode_partition` guards the second
19521 // with the same has_rows test that made this partition non-square).
19522 if has_rows {
19523 decode_block_rect64(
19524 &mut dec,
19525 &mut cdfs,
19526 &mut neighbours,
19527 (at.0 + 2, at.1),
19528 64,
19529 32,
19530 &mut y,
19531 &mut u,
19532 &mut v,
19533 enable_filter_intra,
19534 allow_screen_content_tools,
19535 base_q_idx,
19536 tx_select,
19537 reduced_tx_set,
19538 )?;
19539 }
19540 }
19541 PARTITION_VERT => {
19542 // lane-sbpart r2: mirror of PARTITION_HORZ above with
19543 // width/height swapped.
19544 decode_block_rect64(
19545 &mut dec,
19546 &mut cdfs,
19547 &mut neighbours,
19548 at,
19549 32,
19550 64,
19551 &mut y,
19552 &mut u,
19553 &mut v,
19554 enable_filter_intra,
19555 allow_screen_content_tools,
19556 base_q_idx,
19557 tx_select,
19558 reduced_tx_set,
19559 )?;
19560 if !has_cols {
19561 bump_edge32(7);
19562 }
19563 // lane-golomb r1: at the frame edge only the first half of the
19564 // strip is coded (libaom `decode_partition` guards the second
19565 // with the same has_cols test that made this partition non-square).
19566 if has_cols {
19567 decode_block_rect64(
19568 &mut dec,
19569 &mut cdfs,
19570 &mut neighbours,
19571 (at.0, at.1 + 2),
19572 32,
19573 64,
19574 &mut y,
19575 &mut u,
19576 &mut v,
19577 enable_filter_intra,
19578 allow_screen_content_tools,
19579 base_q_idx,
19580 tx_select,
19581 reduced_tx_set,
19582 )?;
19583 }
19584 }
19585 PARTITION_HORZ_A | PARTITION_HORZ_B | PARTITION_VERT_A | PARTITION_VERT_B => {
19586 // lane-part32 r4: the four superblock-level AB arms, each
19587 // two 32x32 squares plus one 64x32/32x64 strip, in
19588 // libaom's own `decode_partition` order (decodeframe.c:
19589 // HORZ_A = TL, TR, bottom strip; HORZ_B = top strip, BL,
19590 // BR; VERT_A = TL, BL, right strip; VERT_B = left strip,
19591 // TR, BR). The pieces are exactly the ones already proven
19592 // by the `PARTITION_NONE`-under-SPLIT (32x32 square) and
19593 // `PARTITION_HORZ`/`VERT` (rect64 strip) arms above.
19594 SB_AB_HITS.with(|c| {
19595 let mut h = c.get();
19596 h[part - PARTITION_HORZ_A] += 1;
19597 c.set(h);
19598 });
19599 // lane-part32 r5: only the two VERTICAL arms reorder the
19600 // square sub-blocks (TL, BL, TR, BR), so only they switch
19601 // libaom's `has_tr`/`has_bl` tables.
19602 let _vert_ab = (part == PARTITION_VERT_A || part == PARTITION_VERT_B)
19603 .then(crate::encode::Reach::vert_ab_partition);
19604 macro_rules! square32 {
19605 ($at:expr) => {
19606 decode_block(
19607 &mut dec,
19608 &mut cdfs,
19609 &mut neighbours,
19610 $at,
19611 BLOCK,
19612 TxbSet::Luma32,
19613 TxbSet::Chroma16,
19614 TX32,
19615 TX16,
19616 (&scan32, &scan16),
19617 true,
19618 &mut y,
19619 &mut u,
19620 &mut v,
19621 base_q_idx,
19622 enable_filter_intra,
19623 allow_screen_content_tools,
19624 allow_intrabc,
19625 &scan32,
19626 &scan16,
19627 &scan8,
19628 &scan4,
19629 tx_select,
19630 reduced_tx_set,
19631 )?
19632 };
19633 }
19634 macro_rules! strip64 {
19635 ($at:expr, $bw:expr, $bh:expr) => {
19636 decode_block_rect64(
19637 &mut dec,
19638 &mut cdfs,
19639 &mut neighbours,
19640 $at,
19641 $bw,
19642 $bh,
19643 &mut y,
19644 &mut u,
19645 &mut v,
19646 enable_filter_intra,
19647 allow_screen_content_tools,
19648 base_q_idx,
19649 tx_select,
19650 reduced_tx_set,
19651 )?
19652 };
19653 }
19654 let (br, bc) = (at.0 + 2, at.1 + 2);
19655 match part {
19656 PARTITION_HORZ_A => {
19657 square32!(at);
19658 square32!((at.0, bc));
19659 strip64!((br, at.1), 64, 32);
19660 }
19661 PARTITION_HORZ_B => {
19662 strip64!(at, 64, 32);
19663 square32!((br, at.1));
19664 square32!((br, bc));
19665 }
19666 PARTITION_VERT_A => {
19667 square32!(at);
19668 square32!((br, at.1));
19669 strip64!((at.0, bc), 32, 64);
19670 }
19671 _ => {
19672 strip64!(at, 32, 64);
19673 square32!((at.0, bc));
19674 square32!((br, bc));
19675 }
19676 }
19677 }
19678 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
19679 // lane-tx64x16: the 1:4 pair at 64x64 -- four 64x16 (or
19680 // 16x64) strips in raster order. `decode_partition`
19681 // (`decodeframe.c`) steps by `quarter_step = mi_size / 4`
19682 // (4 mi = 16 px = one SUB unit here) and BREAKS at the
19683 // frame edge for `i > 0`, so a partial superblock codes
19684 // only the strips whose origin is inside the frame.
19685 let horz = part == PARTITION_HORZ_4;
19686 for i in 0..4 {
19687 let step_mi = i * (SB_MI as usize / 4);
19688 let (this_r_mi, this_c_mi) = if horz {
19689 (sb_r as usize * SB_MI as usize + step_mi, sb_c as usize * SB_MI as usize)
19690 } else {
19691 (sb_r as usize * SB_MI as usize, sb_c as usize * SB_MI as usize + step_mi)
19692 };
19693 if i > 0
19694 && (this_r_mi >= mi_rows as usize || this_c_mi >= mi_cols as usize)
19695 {
19696 break;
19697 }
19698 let strip_at = if horz { (at.0 + i, at.1) } else { (at.0, at.1 + i) };
19699 let (bw, bh) = if horz { (64, 16) } else { (16, 64) };
19700 decode_block_rect64(
19701 &mut dec,
19702 &mut cdfs,
19703 &mut neighbours,
19704 strip_at,
19705 bw,
19706 bh,
19707 &mut y,
19708 &mut u,
19709 &mut v,
19710 enable_filter_intra,
19711 allow_screen_content_tools,
19712 base_q_idx,
19713 tx_select,
19714 reduced_tx_set,
19715 )?;
19716 }
19717 }
19718 _ => {
19719 return Err(unsupported(
19720 "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4",
19721 ));
19722 }
19723 }
19724 }
19725 }
19726
19727 if tile_num == tile_info.context_update_tile_id {
19728 result_cdfs = cdfs;
19729 }
19730 }
19731
19732 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
19733 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
19734 // that isolate whether a decode-order frame's mismatch already exists
19735 // in reconstruction (this dump) vs is introduced by the loop filter
19736 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
19737 // Decode-order frame marker for the EC_OBMC / EC_TRACE_MODE ladders.
19738 if crate::envflags::env_flag!("EC_OBMC")
19739 || crate::envflags::env_flag!("EC_TRACE_MODE")
19740 || crate::envflags::env_flag!("EC_PRED")
19741 {
19742 eprintln!(
19743 "EC_PICT idx={}",
19744 PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst)
19745 );
19746 }
19747 dump_stage16("EC_AV1_PREFILT_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
19748 if let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_DUMP") {
19749 use std::io::Write;
19750 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
19751 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
19752 let narrow = |p: &PlaneBuf| -> Vec<u8> { p.data.iter().map(|&s| s as u8).collect() };
19753 let _ = f.write_all(&narrow(&y));
19754 let _ = f.write_all(&narrow(&u));
19755 let _ = f.write_all(&narrow(&v));
19756 }
19757 } else {
19758 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
19759 }
19760 if let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_WIDE_DUMP") {
19761 use std::io::Write;
19762 static IDX2: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
19763 let idx = IDX2.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
19764 let crop_wide = |plane: &PlaneBuf| -> Vec<u8> {
19765 let mut out = Vec::with_capacity(plane.true_width * plane.true_height);
19766 for row in 0..plane.true_height {
19767 out.extend(plane.data[row * plane.width..][..plane.true_width].iter().map(|&s| s as u8));
19768 }
19769 out
19770 };
19771 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
19772 let _ = f.write_all(&crop_wide(&y));
19773 let _ = f.write_all(&crop_wide(&u));
19774 let _ = f.write_all(&crop_wide(&v));
19775 }
19776 }
19777 apply_deblock(
19778 &mut y,
19779 &mut u,
19780 &mut v,
19781 loop_filter,
19782 &neighbours,
19783 frame_width as usize,
19784 frame_height as usize,
19785 );
19786 // lane-perf4: loop restoration is the only reader of the pre-CDEF planes,
19787 // and a frame that restores nothing copied every plane twice for nothing
19788 // (three `PlaneBuf` clones here plus the `cdef.to_vec()` inside
19789 // [`crate::restoration::apply_loop_restoration_plane`], which returns its
19790 // input unchanged when the plane's type is `None`). Clone only when some
19791 // plane actually restores.
19792 let lr_active = (0..3).any(|p| {
19793 lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None
19794 && lr.loop_restoration_size[p] != 0
19795 });
19796 let deblocked =
19797 lr_active.then(|| (plane_snapshot(&y), plane_snapshot(&u), plane_snapshot(&v)));
19798 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
19799 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
19800 // dump above these bisect WHICH filter stage introduced a mismatch.
19801 dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v);
19802 dump_stage16("EC_AV1_POSTDEBLOCK_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
19803 apply_cdef(
19804 &mut y,
19805 &mut u,
19806 &mut v,
19807 cdef,
19808 &neighbours,
19809 (frame_width as usize, frame_height as usize),
19810 );
19811 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
19812 dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
19813 // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called
19814 // between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`):
19815 // the horizontal upscale runs HERE -- after CDEF, before loop
19816 // restoration, not after the whole filter chain. Both the post-CDEF
19817 // frame and the post-deblock frame that LR substitutes at its stripe
19818 // boundaries are upscaled (`save_deblock_boundary_lines` runs
19819 // `av1_upscale_normative_rows` over its saved rows when the frame is
19820 // scaled), so every LR coordinate from here on is in upscaled space.
19821 let mut deblocked = deblocked;
19822 let mut lr_w = frame_width as usize;
19823 if let Some((upscaled_w, _)) = superres() {
19824 let bd = u32::from(bit_depth());
19825 let (uw, fw, fh) = (upscaled_w as usize, frame_width as usize, frame_height as usize);
19826 let up = |p: &PlaneBuf, in_w: usize, in_h: usize, out_w: usize| PlaneBuf {
19827 data: crate::superres::upscale_plane_strided(
19828 &p.data, p.width, in_w, in_h, p.true_width, out_w, bd,
19829 ),
19830 width: out_w,
19831 height: in_h,
19832 true_width: out_w,
19833 true_height: in_h,
19834 tile_x0: 0,
19835 tile_y0: 0,
19836 tile_x1: out_w,
19837 tile_y1: in_h,
19838 };
19839 let (cw, ch, cuw) = (fw.div_ceil(2), fh.div_ceil(2), uw.div_ceil(2));
19840 y = up(&y, fw, fh, uw);
19841 u = up(&u, cw, ch, cuw);
19842 v = up(&v, cw, ch, cuw);
19843 if let Some((dy, du, dv)) = deblocked.take() {
19844 deblocked = Some((up(&dy, fw, fh, uw), up(&du, cw, ch, cuw), up(&dv, cw, ch, cuw)));
19845 }
19846 lr_w = uw;
19847 crate::superres::note_upscaled_picture();
19848 }
19849 if let Some((deblocked_y, deblocked_u, deblocked_v)) = &deblocked {
19850 apply_loop_restoration(
19851 &mut y, &mut u, &mut v, deblocked_y, deblocked_u, deblocked_v, lr, &lr_grid,
19852 (lr_w, frame_height as usize),
19853 );
19854 }
19855 if let Some((db_y, db_u, db_v)) = deblocked {
19856 scratch_return(db_y.data);
19857 scratch_return(db_u.data);
19858 scratch_return(db_v.data);
19859 }
19860
19861 let (fw, fh) = (lr_w, frame_height as usize);
19862 // An upscaled frame is already at its final size with no mi-aligned
19863 // margin beyond it (the upscale consumed those columns), so the
19864 // wide-margin stash below has nothing left to hand out.
19865 let (true_width, true_height) = if superres().is_some() {
19866 (fw, fh)
19867 } else {
19868 (true_width, true_height)
19869 };
19870 if fw == width && fh == height {
19871 LAST_FRAME_WIDE_MARGIN.with(|m| *m.borrow_mut() = None);
19872 return Ok((
19873 Picture {
19874 width,
19875 height,
19876 y: y.data,
19877 u: u.data,
19878 v: v.data,
19879 },
19880 result_cdfs,
19881 ));
19882 }
19883 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u16> {
19884 let mut out = Vec::with_capacity(w * h);
19885 for row in 0..h {
19886 out.extend(plane.data[row * plane.width..][..w].iter().copied());
19887 }
19888 out
19889 };
19890 // lane-superres r3: `true_width`/`true_height` (`mi_cols`/`mi_rows` * 4)
19891 // is the real reconstructed extent -- columns `[fw, true_width)` hold
19892 // genuine decoded samples (the last coding block straddles the frame
19893 // edge whenever `frame_width` isn't 8-sample aligned), not padding.
19894 // libaom's superres upscale runs on that buffer's own border-extended
19895 // margin, so it reads those real columns, not a synthetic replicate of
19896 // column `fw - 1`. Stash them for `stream.rs`'s superres path (a real
19897 // aomenc 43->64 stream pinned column-by-column against libaom's own
19898 // `av1_convolve_horiz_rs_c` via `scripts/superres-pin-harness.c` --
19899 // `row6-realedgeval` proved the replicate-of-`fw-1` padding this
19900 // decoder used before was off by 1 at the columns the tap window
19901 // reaches into that real margin; `None` when there is no margin (this
19902 // frame's `true_width`/`true_height` already equal `fw`/`fh`, e.g. a
19903 // non-superres frame whose width just isn't 32-block aligned).
19904 LAST_FRAME_WIDE_MARGIN.with(|m| {
19905 *m.borrow_mut() = if true_width > fw || true_height > fh {
19906 let yc = crop(&y, true_width, true_height);
19907 if let Ok(path) = crate::envflags::var("EC_AV1_MARGIN_DUMP") {
19908 use std::io::Write;
19909 static IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
19910 let idx = IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
19911 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
19912 // corner-cut: this diagnostic dump stays 8-bit-narrowed
19913 // regardless of the stream's real bit depth (debug-only,
19914 // never read by a gate); widen if a >8-bit margin dump
19915 // is ever needed.
19916 let _ = f.write_all(&yc.iter().map(|&s| s as u8).collect::<Vec<u8>>());
19917 }
19918 }
19919 Some(Picture {
19920 width: true_width,
19921 height: true_height,
19922 y: yc,
19923 u: crop(&u, true_width.div_ceil(2), true_height.div_ceil(2)),
19924 v: crop(&v, true_width.div_ceil(2), true_height.div_ceil(2)),
19925 })
19926 } else {
19927 None
19928 }
19929 });
19930 Ok((
19931 Picture {
19932 width: fw,
19933 height: fh,
19934 y: crop(&y, fw, fh),
19935 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
19936 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
19937 },
19938 result_cdfs,
19939 ))
19940}
19941
19942/// `av1_get_pred_context_switchable_interp`'s context for `interp_filter[dir]`
19943/// -- `above`/`left` are the neighbour's own resolved index for this
19944/// direction (0..=2, or `3` = no info, spec `SWITCHABLE_FILTERS`).
19945/// `is_compound` folds in libaom `av1_get_pred_context_switchable_interp`'s
19946/// own `ctx_offset` term (`INTER_FILTER_COMP_OFFSET` = 4, added when *this*
19947/// block itself has a second reference) -- lane-av1idx: a stale "this
19948/// decoder never codes a compound reference" assumption baked this to
19949/// always-0, which desynced the CDF context bucket (not the decoded value
19950/// outright, hence small pixel deltas rather than a hard desync) the moment
19951/// lane-av1blend unmasked plain-average compound blocks on a Switchable-
19952/// filter frame.
19953fn switchable_interp_ctx(above: u8, left: u8, dir: usize, is_compound: bool) -> usize {
19954 let base = dir * 8 + if is_compound { 4 } else { 0 };
19955 let term = if left == above {
19956 left
19957 } else if left == 3 {
19958 above
19959 } else if above == 3 {
19960 left
19961 } else {
19962 3
19963 };
19964 base + term as usize
19965}
19966
19967/// Resolves the interpolation filter kernel(s) an inter block's motion
19968/// compensation reads (spec 5.11.10/5.11.20): a fixed-filter frame
19969/// (`interp_fixed = Some`) never reads a symbol; a `Switchable` frame
19970/// (`interp_fixed = None`) reads `interp_filter[0]` and, when
19971/// `enable_dual_filter`, a second `interp_filter[1]` -- unless
19972/// `force_regular` (this block's own `needs_interp_filter() == 0` case: a
19973/// `GLOBALMV` block, whose global motion is always `IDENTITY` in this
19974/// decoder's scope, spec 5.11.10's `large && YMode == GLOBALMV` branch),
19975/// which forces `EIGHTTAP` without reading anything.
19976#[allow(clippy::too_many_arguments)]
19977fn resolve_interp_filter(
19978 dec: &mut SymbolDecoder,
19979 cdfs: &mut Cdfs,
19980 interp_fixed: Option<mc::InterpFilterKind>,
19981 enable_dual_filter: bool,
19982 force_regular: bool,
19983 above: [u8; 2],
19984 left: [u8; 2],
19985 is_compound: bool,
19986) -> (mc::InterpFilterKind, mc::InterpFilterKind, [u8; 2]) {
19987 if let Some(kind) = interp_fixed {
19988 return (kind, kind, [3, 3]);
19989 }
19990 if force_regular {
19991 return (
19992 mc::InterpFilterKind::Regular,
19993 mc::InterpFilterKind::Regular,
19994 [0, 0],
19995 );
19996 }
19997 // libaom `av1_extract_interp_filter`/`read_mb_interp_filter`: the
19998 // symbol read at `dir=0` becomes the block's *vertical* (`y_filter`)
19999 // kernel, `dir=1` the *horizontal* (`x_filter`) one -- `dir` is not
20000 // "horizontal then vertical" despite `predict_with_filters`' own
20001 // `h_kind`/`v_kind` argument order, which is why this function returns
20002 // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`).
20003 let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound);
20004 if crate::envflags::env_flag!("EC_AV1_IFDBG") {
20005 eprintln!(
20006 "IFDBG dir=0 ctx={ctx0} above={above:?} left={left:?} cdf={:?}",
20007 &cdfs.switchable_interp[ctx0][..3]
20008 );
20009 }
20010 let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8;
20011 let sym1 = if enable_dual_filter {
20012 let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound);
20013 if crate::envflags::env_flag!("EC_AV1_IFDBG") {
20014 eprintln!(
20015 "IFDBG dir=1 ctx={ctx1} above={above:?} left={left:?} cdf={:?} sym0={sym0}",
20016 &cdfs.switchable_interp[ctx1][..3]
20017 );
20018 }
20019 dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8
20020 } else {
20021 sym0
20022 };
20023 if enable_dual_filter && sym0 != sym1 {
20024 DUAL_FILTER_DIFF_HITS.with(|c| c.set(c.get() + 1));
20025 }
20026 if crate::envflags::env_flag!("EC_TRACE_MODE") {
20027 eprintln!(
20028 "EC_IF ctx0={ctx0} above={above:?} left={left:?} sym0={sym0} sym1={sym1} rng={}",
20029 dec.debug_state().0
20030 );
20031 }
20032 (
20033 mc::InterpFilterKind::from_switchable_symbol(sym1 as usize),
20034 mc::InterpFilterKind::from_switchable_symbol(sym0 as usize),
20035 [sym0, sym1],
20036 )
20037}
20038
20039/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`),
20040/// duplicating [`crate::tile`]'s private copy of the same rule.
20041pub(crate) fn intra_inter_ctx(
20042 has_above: bool,
20043 has_left: bool,
20044 above_inter: bool,
20045 left_inter: bool,
20046) -> usize {
20047 match (has_above, has_left) {
20048 (true, true) => {
20049 let (above_intra, left_intra) = (!above_inter, !left_inter);
20050 if above_intra && left_intra {
20051 3
20052 } else {
20053 usize::from(above_intra || left_intra)
20054 }
20055 }
20056 (true, false) => 2 * usize::from(!above_inter),
20057 (false, true) => 2 * usize::from(!left_inter),
20058 (false, false) => 0,
20059 }
20060}
20061
20062/// `CLASS0_SIZE << (class + 2)`, duplicating `crate::tile`'s private
20063/// `mv_class_base` (spec 3): the magnitude an `MV_CLASS_n` component's own
20064/// bits start counting from.
20065fn mv_class_base(class: usize) -> i32 {
20066 if class == 0 { 0 } else { 2i32 << (class + 2) }
20067}
20068
20069/// One motion vector component's non-zero diff (spec 5.11.32
20070/// `read_mv_component`), the inverse of [`crate::tile`]'s private
20071/// `write_mv_component`.
20072fn read_mv_component(
20073 dec: &mut SymbolDecoder,
20074 c: &mut MvComponentCdfs,
20075 allow_high_precision_mv: bool,
20076 force_integer_mv: bool,
20077) -> i32 {
20078 let sign = dec.symbol(&mut c.sign);
20079 let class = dec.symbol(&mut c.class);
20080 let local = if class == 0 {
20081 let bit = dec.symbol(&mut c.class0_bit);
20082 // spec 5.11.32 `mv_class0_fr`: not coded at all when the frame
20083 // forces integer motion vectors -- implicitly `3` (the top
20084 // fractional value) rather than read, else every symbol after it
20085 // in the tile desyncs by one read.
20086 let fr = if force_integer_mv {
20087 3
20088 } else {
20089 dec.symbol(&mut c.class0_fr[bit])
20090 };
20091 // spec 5.11.32 `mv_class0_hp`: read only when the frame allows
20092 // high-precision motion vectors, else implicitly 1 (the low bit
20093 // stays at half-pel precision) -- this crate's own writer always
20094 // leaves the flag off, but a foreign stream can set it per frame.
20095 let hp = if allow_high_precision_mv {
20096 dec.symbol(&mut c.class0_hp)
20097 } else {
20098 1
20099 };
20100 (bit << 3) | (fr << 1) | hp
20101 } else {
20102 let mut d = 0;
20103 for i in 0..class {
20104 d |= dec.symbol(&mut c.bit[i]) << i;
20105 }
20106 // spec 5.11.32 `mv_fr`: same force_integer_mv carve-out as
20107 // `mv_class0_fr` above.
20108 let fr = if force_integer_mv { 3 } else { dec.symbol(&mut c.fr) };
20109 let hp = if allow_high_precision_mv {
20110 dec.symbol(&mut c.hp)
20111 } else {
20112 1
20113 };
20114 (d << 3) | (fr << 1) | hp
20115 };
20116 let mag = mv_class_base(class) + local as i32 + 1;
20117 if sign == 1 { -mag } else { mag }
20118}
20119
20120/// A motion vector coded as a residual against `pred` (spec 5.11.32
20121/// `read_mv`), the inverse of [`crate::tile`]'s private `write_mv`.
20122fn read_mv(
20123 dec: &mut SymbolDecoder,
20124 mv_comp: &mut [MvComponentCdfs; 2],
20125 mv_joint: &mut [u16; 5],
20126 pred: (i32, i32),
20127 allow_high_precision_mv: bool,
20128 force_integer_mv: bool,
20129) -> (i32, i32) {
20130 let joint = dec.symbol(mv_joint);
20131 let mut diff = (0, 0);
20132 if joint == 2 || joint == 3 {
20133 diff.0 = read_mv_component(dec, &mut mv_comp[0], allow_high_precision_mv, force_integer_mv);
20134 }
20135 if joint == 1 || joint == 3 {
20136 diff.1 = read_mv_component(dec, &mut mv_comp[1], allow_high_precision_mv, force_integer_mv);
20137 }
20138 (pred.0 + diff.0, pred.1 + diff.1)
20139}
20140
20141/// One intrabc block's block vector (spec 5.11.13 `read_intrabc_info` ->
20142/// `assign_mv` with `use_intrabc`, libaom `assign_dv`/`av1_find_ref_dv`).
20143///
20144/// The predictor is the ordinary MV stack built against `INTRA_FRAME`
20145/// (`av1_find_mv_refs(..., INTRA_FRAME, ...)`): `nearestmv`, or `nearmv`
20146/// when that is zero, or -- when both are -- the fixed fallback DV one
20147/// superblock up, or `INTRABC_DELAY_PIXELS` (256) plus one superblock to the
20148/// left when this is the tile's first superblock row. The predictor is then
20149/// rounded to full pel, and the difference reads off the *dv* nmv context
20150/// (libaom `ndvc`) at full-pel precision (`MV_SUBPEL_NONE`: no `fr`/`hp`
20151/// symbols, exactly this decoder's `force_integer_mv` carve-out). No DRL
20152/// symbol is coded for a DV, so none of this can move the bitstream
20153/// position -- only the reconstructed vector.
20154fn read_intrabc_dv(
20155 dec: &mut SymbolDecoder,
20156 cdfs: &mut Cdfs,
20157 mi_r: usize,
20158 mi_c: usize,
20159 side: usize,
20160) -> (i32, i32) {
20161 const INTRABC_DELAY_PIXELS: i32 = 256;
20162 let n4 = side / MI;
20163 let stack_pred = INTRABC_MI_GRID.with(|g| {
20164 let g = g.borrow();
20165 g.as_ref().map(|(grid, mi_cols, mi_rows)| {
20166 let stack = crate::mvstack::find_mv_stack(
20167 grid, mi_r, mi_c, n4, n4, 0, /* INTRA_FRAME */
20168 *mi_cols, *mi_rows,
20169 );
20170 if stack.nearest_mv == (0, 0) {
20171 stack.near_mv
20172 } else {
20173 stack.nearest_mv
20174 }
20175 })
20176 });
20177 let mut pred = stack_pred.unwrap_or((0, 0));
20178 if pred == (0, 0) {
20179 // `av1_find_ref_dv` (mvref_common.c). Tile row start is 0 here (the
20180 // single-tile-row case every intrabc gate stream is).
20181 let sb_px = SB_MI as i32 * MI as i32;
20182 pred = if mi_r < SB_MI as usize {
20183 (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8)
20184 } else {
20185 (-sb_px * 8, 0)
20186 };
20187 }
20188 // "Ref DV should not have sub-pel" (`assign_dv`): floor to full pel.
20189 let pred = ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8);
20190 read_mv(dec, &mut cdfs.dv_comp, &mut cdfs.dv_joint, pred, false, true)
20191}
20192
20193/// A 1/8-pel motion vector component converted to the 1/16-pel offset
20194/// [`mc::predict`] takes, duplicating [`crate::encode`]'s private `mv_to_q4`
20195/// (its own doc comment explains the `*2`/`*1` luma/chroma split).
20196fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
20197 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
20198}
20199
20200impl PlaneBuf {
20201 /// Adds `residual` onto an already-computed `prediction` (motion
20202 /// compensation's output, rather than [`predict`]'s intra one), writing
20203 /// the clamped reconstruction into the plane at `(x, y)` -- the inter
20204 /// counterpart of [`PlaneBuf::reconstruct`].
20205 fn reconstruct_mc(
20206 &mut self,
20207 x: usize,
20208 y: usize,
20209 side: usize,
20210 prediction: &[u16],
20211 residual: &[i32],
20212 ) {
20213 self.reconstruct_mc_rect(x, y, side, side, side, prediction, residual);
20214 }
20215
20216 /// [`Self::reconstruct_mc`], writing only a `w`x`h` sub-rectangle of the
20217 /// `side`x`side` `prediction`/`residual` buffers (which stay `side`-square
20218 /// for stride/indexing) -- lane-partitions r1: a true rectangular HORZ/
20219 /// VERT strip is predicted at its enclosing square `side` (matching
20220 /// `HORZ_B`'s already-accepted square-context corner-cut, lane-warp r5)
20221 /// but only its own true `w`x`h` footprint is committed to the plane, so
20222 /// two strips sharing a square's coordinate origin never clobber each
20223 /// other's real pixels.
20224 fn reconstruct_mc_rect(
20225 &mut self,
20226 x: usize,
20227 y: usize,
20228 side: usize,
20229 w: usize,
20230 h: usize,
20231 prediction: &[u16],
20232 residual: &[i32],
20233 ) {
20234 // lane-sb128c r7: a 128x64 half of a 128 root at the BOTTOM frame edge
20235 // is the first block shape whose true footprint overhangs the padded
20236 // coding surface (mi_rows = 198 -> a plane 800 rows tall, block rows
20237 // 768..832). libaom reconstructs those rows into the frame buffer's
20238 // border; nothing reads them back, so they are simply dropped here.
20239 let (h, w) = (h.min(self.height.saturating_sub(y)), w.min(self.width.saturating_sub(x)));
20240 // lane-perf4: one row of each operand at a time. `side` is the
20241 // prediction/residual stride and `self.width` the plane's, so the
20242 // three row bases are computed once per row instead of a
20243 // multiply-add per sample (the samples themselves are unchanged).
20244 let max = crate::decode::sample_max();
20245 for row in 0..h {
20246 let src = row * side;
20247 let dst = (y + row) * self.width + x;
20248 let pred = &prediction[src..src + w];
20249 let res = &residual[src..src + w];
20250 let out = &mut self.data[dst..dst + w];
20251 for ((o, &p), &r) in out.iter_mut().zip(pred).zip(res) {
20252 *o = (i32::from(p) + r).clamp(0, max) as u16;
20253 }
20254 }
20255 }
20256}
20257
20258/// Reads one inter-coded plane's transform block and reconstructs it by
20259/// adding its residual onto a motion-compensated `prediction` -- the inter
20260/// counterpart of [`read_plane`] (every inter transform this decoder reads is
20261/// `side`-square with no oversized-64 case, so there is no padded-grid
20262/// branch to mirror).
20263#[allow(clippy::too_many_arguments)]
20264fn read_inter_plane(
20265 dec: &mut SymbolDecoder,
20266 cdfs: &mut Cdfs,
20267 set: TxbSet,
20268 scan: &[u16],
20269 plane_idx: usize,
20270 around: (bool, bool, i32),
20271 tx_mode: usize,
20272 plane: &mut PlaneBuf,
20273 x: usize,
20274 y: usize,
20275 side: usize,
20276 base_q_idx: u8,
20277 prediction: &[u16],
20278 // lane-chromau: this block's own luma transform's *actual coded*
20279 // `tx_type` -- `av1_get_tx_type` (libaom `blockd.h`): an inter block's
20280 // chroma plane never codes its own `tx_type` symbol, but (unlike an
20281 // intra block, which falls back to `Intra_Mode_To_Tx_Type`) it inherits
20282 // the colocated luma transform's coded type, narrowed to the extended
20283 // set the CHROMA size selects ([`reduce_inherited_chroma_tx_type`]).
20284 // `None` for the luma call itself
20285 // (`plane_idx == 0`), where the `TxbSet`'s own symbol (or the true
20286 // `DCT_DCT` default at 32-point+) already resolves it without help.
20287 inherited_luma_tx_type: Option<TxType>,
20288 // lane-txselect: the luma `txb_skip_ctx` of a transform unit smaller than
20289 // its own block (spec `get_txb_ctx_general`'s `plane_bsize != tx_size`
20290 // branch, [`Neighbours::luma_skip_ctx`]) -- `None` for the whole-block
20291 // transform every non-var-tx caller reads, whose plane-0 context is the
20292 // lone-transform-unit 0.
20293 luma_skip_ctx: Option<usize>,
20294) -> Result<(Vec<i32>, TxType)> {
20295 let skip_ctx = if plane_idx == 0 {
20296 luma_skip_ctx.unwrap_or(0)
20297 } else {
20298 // lane-sb128c r1: on a CHROMA plane this same parameter carries
20299 // `get_txb_ctx`'s own offset instead -- `combine_entropy_contexts(..)`
20300 // is +7 normally and +10 when the plane block is LARGER than the
20301 // transform (a 128x128 block's 64x64 uv plane block with TX_32X32
20302 // units, AV1's only such case), and the `txb_skip_chroma_32` table
20303 // carries the offset-10 rows at +3 (lane-sb128b r3).
20304 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
20305 };
20306 let mut coding = cdfs.txb(set, tx_mode);
20307 let default_tx_type = match inherited_luma_tx_type {
20308 Some(t) => reduce_inherited_chroma_tx_type(t, side, side),
20309 None => TxType::DctDct,
20310 };
20311 let (grid, tx_type) = read_coeffs(
20312 dec,
20313 &mut coding,
20314 scan,
20315 skip_ctx,
20316 dc_sign_ctx(around.2),
20317 default_tx_type,
20318 None,
20319 )?;
20320 note_chroma_class1(plane_idx, tx_type);
20321 if crate::envflags::env_flag!("EC_TRACE_TXTYPE") {
20322 eprintln!("OUR_TXTYPE plane={plane_idx} x={x} y={y} side={side} tx_type={tx_type:?} inh={inherited_luma_tx_type:?}");
20323 }
20324 // lane-inter8 r1: a 64-point transform covers the whole 64x64 area but
20325 // codes only its top-left 32x32 of frequencies (spec 5.11.40) -- the
20326 // caller hands the 32-point `scan` there, and the coded corner goes into
20327 // the top-left of the true `side`-sized grid before dequantization
20328 // (dqDenom is keyed by the true size, not the corner's), mirroring
20329 // [`read_plane`]'s own `tx_side != side` branch. Every other transform
20330 // this decoder codes has `tx_side == side`, so this is inert below 64.
20331 let tx_side = side.min(32);
20332 let grid = if tx_side == side {
20333 grid
20334 } else {
20335 let mut full = vec![0i32; side * side];
20336 for row in 0..tx_side {
20337 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
20338 }
20339 full
20340 };
20341 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
20342 let residual = dequant_and_inverse_typed(&grid, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type);
20343 plane.reconstruct_mc(x, y, side, prediction, &residual);
20344 Ok((grid, tx_type))
20345}
20346
20347/// Spec 5.11.25's `single_ref_p1`..`p6` tree (reachable only once `comp_mode`
20348/// is known `SINGLE_REFERENCE` -- `decode_stream` refuses any frame with
20349/// `reference_select` set before this is ever called, so that read is never
20350/// needed here). `above_ref`/`left_ref` are `-1` for an intra/unavailable
20351/// neighbour, else the `1..=7` reference that neighbour coded (lane-av1refs).
20352fn read_single_ref(
20353 dec: &mut SymbolDecoder,
20354 cdfs: &mut Cdfs,
20355 above_ref: i8,
20356 above_ref1: Option<i8>,
20357 left_ref: i8,
20358 left_ref1: Option<i8>,
20359) -> i8 {
20360 let above = (above_ref > 0).then_some(above_ref);
20361 let left = (left_ref > 0).then_some(left_ref);
20362 let p1 = dec.symbol(&mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0]);
20363 let ref_frame = if p1 == 1 {
20364 let p2 = dec.symbol(&mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1]);
20365 if p2 == 1 {
20366 ALTREF_FRAME
20367 } else {
20368 let p6 = dec.symbol(&mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5]);
20369 if p6 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
20370 }
20371 } else {
20372 let p3 = dec.symbol(&mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2]);
20373 if p3 == 1 {
20374 let p5 = dec.symbol(&mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4]);
20375 if p5 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
20376 } else {
20377 let p4 = dec.symbol(&mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3]);
20378 if p4 == 1 { LAST2_FRAME } else { LAST_FRAME }
20379 }
20380 };
20381 if ref_frame != LAST_FRAME {
20382 NON_LAST_REF_HITS.with(|c| c.set(c.get() + 1));
20383 let c = match ref_frame {
20384 LAST2_FRAME => &LAST2_HITS,
20385 LAST3_FRAME => &LAST3_HITS,
20386 GOLDEN_FRAME => &GOLDEN_HITS,
20387 BWDREF_FRAME => &BWDREF_HITS,
20388 ALTREF2_FRAME => &ALTREF2_HITS,
20389 ALTREF_FRAME => &ALTREF_HITS,
20390 _ => unreachable!("read_single_ref only ever returns LAST_FRAME..=ALTREF_FRAME"),
20391 };
20392 c.with(|v| v.set(v.get() + 1));
20393 }
20394 ref_frame
20395}
20396
20397/// Spec 5.11.25's `comp_mode` (lane-av1comp): whether an inter block reads
20398/// `SINGLE_REFERENCE` or `COMPOUND_REFERENCE`, only reached once a frame's
20399/// `reference_select` header bit lets a block choose per-block instead of
20400/// fixing the mode. `above`/`left` are `None` for an intra/unavailable
20401/// neighbour, [`NeighbourRef`] for a coded one -- [`reference_mode_ctx`]'s
20402/// own doc. Called from [`decode_inter_block`] once its own `reference_select`
20403/// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same
20404/// way with a coarser (`LAST_FRAME`-only) neighbour shape.
20405/// Resolves a compound reference's own planes -- the same `ref_frame ==
20406/// LAST_FRAME -> ref_y/u/v, else other_refs[ref_frame]` lookup
20407/// [`decode_inter_block`]'s single-ref path already does, factored out so
20408/// the compound path can call it twice (lane-av1comp).
20409fn ref_planes<'a>(
20410 ref_frame: i8,
20411 ref_y: &'a PlaneBuf,
20412 ref_u: &'a PlaneBuf,
20413 ref_v: &'a PlaneBuf,
20414 other_refs: &'a RefSlots,
20415) -> Result<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)> {
20416 if ref_frame == LAST_FRAME {
20417 Ok((ref_y, ref_u, ref_v))
20418 } else {
20419 match other_refs[ref_frame as usize] {
20420 Some((ry, ru, rv)) => Ok((ry, ru, rv)),
20421 None => Err(unsupported(
20422 "a reference frame selected with no picture at this frame's own \
20423 ref_frame_idx slot for it",
20424 )),
20425 }
20426 }
20427}
20428
20429/// libaom `foreach_overlappable_nb_above` (`obmc.h`): walks the mi row
20430/// directly above this block's own column span, one bordering block at a
20431/// time (stepping by that neighbour's own `MiInfo::size`, which is always
20432/// `<= 16` since no block this decoder ever codes exceeds 64x64), collecting
20433/// every *inter* neighbour found (an intra or unset cell is skipped, one mi
20434/// unit at a time, and does not itself count as a step). `max_neighbors`
20435/// caller-bounds the scan: `1` for the eligibility check (any hit at all),
20436/// `av1_build_obmc_inter_prediction`'s own `max_neighbor_obmc` table for the
20437/// real blend pass. lane-intra16x4 r2: libaom's own "4-wide block, treat as
20438/// half of a chroma pair" merge (`obmc.h`'s `mi_step == 1` special case) IS
20439/// ported below -- the round-1 note that no block is narrower than 8px stopped
20440/// being true when the 1:4 partitions landed. A 16x4 / 4x16 strip has
20441/// `mi_size_high`/`mi_size_wide` 1, so libaom snaps the walk back to the pair's
20442/// even index, reads the ODD (chroma-carrying) half as the neighbour and steps
20443/// by 2. Measured: the 16x16 block right of a 16x16-level HORZ_4 partition
20444/// whose strip 0 is inter and strips 1..3 intra counted that inter strip as
20445/// overlappable here, while libaom's pair merge reads the INTRA strip 1 and
20446/// counts none -- so we read a `motion_mode` symbol libaom never wrote (class
20447/// `symbol-consumption-gap`), desyncing the tile at the next coefficient.
20448fn overlappable_above(
20449 grid: &MiGrid,
20450 mi_row: usize,
20451 mi_col: usize,
20452 bw4: usize,
20453 mi_cols: usize,
20454 max_neighbors: usize,
20455) -> Vec<(usize, usize, MiInfo, usize)> {
20456 let mut out = Vec::new();
20457 if mi_row == 0 {
20458 return out;
20459 }
20460 let end_col = (mi_col + bw4).min(mi_cols);
20461 let mut col = mi_col;
20462 while col < end_col && out.len() < max_neighbors {
20463 let cell = grid.get(mi_row - 1, col);
20464 let mut step = cell.map_or(1, |c| c.size).max(1).min(SB_MI as usize);
20465 let mut nb = cell;
20466 // lane-obmcrec r1: the mi the neighbour's `MiInfo` is actually taken
20467 // from -- the pair merge below moves it, and libaom reads that same
20468 // `mbmi`'s `interp_filters` (`av1_setup_build_prediction_by_above_pred`).
20469 let mut src = col;
20470 if step == 1 {
20471 // The pair merge: the walk snaps back to the pair's even column
20472 // and the ODD half (the chroma-carrying one) is the neighbour for
20473 // both -- a 4-wide 1:4 strip is never an OBMC source on its own.
20474 col &= !1;
20475 src = col + 1;
20476 nb = grid.get(mi_row - 1, src);
20477 step = 2;
20478 }
20479 if let Some(info) = nb {
20480 if info.is_inter {
20481 if src != col {
20482 OBMC_PAIR_FILTER_HITS.with(|c| c.set(c.get() + 1));
20483 }
20484 // lane-t900 r14: libaom passes `AOMMIN(xd->width, mi_step)`
20485 // as `op_mi_size` -- the block's OWN width, never the
20486 // frame-edge clamp `end_col` carries. Clamping here shrank the
20487 // neighbour PREDICTION at a frame edge, which picks the
20488 // 4-tap kernel below 8 px (class narrow-block-sharp-kernel);
20489 // the destination clip stays in `obmc_blend`.
20490 out.push((col - mi_col, step.min(bw4), *info, src - mi_col));
20491 }
20492 }
20493 col += step;
20494 }
20495 out
20496}
20497
20498/// `foreach_overlappable_nb_left`'s left-column mirror of
20499/// [`overlappable_above`] -- see its doc for the shared corner-cut.
20500fn overlappable_left(
20501 grid: &MiGrid,
20502 mi_row: usize,
20503 mi_col: usize,
20504 bh4: usize,
20505 mi_rows: usize,
20506 max_neighbors: usize,
20507) -> Vec<(usize, usize, MiInfo, usize)> {
20508 let mut out = Vec::new();
20509 if mi_col == 0 {
20510 return out;
20511 }
20512 let end_row = (mi_row + bh4).min(mi_rows);
20513 let mut row = mi_row;
20514 while row < end_row && out.len() < max_neighbors {
20515 let cell = grid.get(row, mi_col - 1);
20516 // Vertical walk steps by the neighbour's HEIGHT -- a 32x16 strip's
20517 // width (8) would swallow the strip below it.
20518 let mut step = cell.map_or(1, |c| c.size_h).max(1).min(SB_MI as usize);
20519 let mut nb = cell;
20520 // lane-obmcrec r1: see `overlappable_above`'s `src`.
20521 let mut src = row;
20522 if step == 1 {
20523 // The pair merge, left-column mirror: a 4-TALL neighbour (a 16x4
20524 // strip) is half of a chroma pair and the pair's SECOND row is the
20525 // neighbour for both.
20526 row &= !1;
20527 src = row + 1;
20528 nb = grid.get(src, mi_col - 1);
20529 step = 2;
20530 }
20531 if let Some(info) = nb {
20532 if info.is_inter {
20533 if src != row {
20534 OBMC_PAIR_FILTER_HITS.with(|c| c.set(c.get() + 1));
20535 }
20536 // lane-t900 r14: `AOMMIN(xd->height, mi_step)` -- see
20537 // `overlappable_above`.
20538 out.push((row - mi_row, step.min(bh4), *info, src - mi_row));
20539 }
20540 }
20541 row += step;
20542 }
20543 out
20544}
20545
20546/// The warp-sample gather's own `has_top_right` probe (libaom `av1_findSamples`
20547/// calls the same `mvref_common.c` function the MV stack does). lane-sb128 r2:
20548/// this used to hardcode `SB_MI` (a 64x64 superblock) -- at `sb_size == 128`
20549/// libaom's mask loop runs one level further and strips the top-right sample
20550/// off blocks whose neighbour IS decoded, so a warped 128-superblock frame
20551/// picked up wrong warp parameters (frame 6 of the 128 inter gate). Delegates
20552/// to the single sb-aware port in [`crate::mvstack::has_top_right`]; `bs` is
20553/// the block's own side in 4x4 (`mi`) units (square inter leaves only here).
20554fn has_top_right(mi_row: usize, mi_col: usize, bs: usize) -> bool {
20555 crate::mvstack::has_top_right(mi_row, mi_col, bs, bs)
20556}
20557
20558/// `av1_findSamples` (`mvref_common.c`), full port: the up to
20559/// `LEAST_SQUARES_SAMPLES_MAX` (8) above/left/top-left/top-right neighbour
20560/// samples (`record_samples`) that share this block's own single reference
20561/// frame and are themselves single-ref -- `mbmi->num_proj_ref` is
20562/// `.len()` of the returned vec. `bw4` is the block's own side in 4x4 units
20563/// (square, so also `bh4`; a real block's `xd->width`/`xd->height` in
20564/// libaom are also mi units of that same square side here). Each sample's
20565/// own `bw`/`bh` (fed to [`crate::warp::record_sample`]'s offset formula)
20566/// come from the *neighbour* cell's own coded size, not this block's.
20567#[allow(clippy::too_many_arguments)]
20568fn find_samples(
20569 grid: &MiGrid,
20570 mi_row: usize,
20571 mi_col: usize,
20572 bw4: usize,
20573 bh4: usize,
20574 mi_cols: usize,
20575 mi_rows: usize,
20576 ref_frame: i8,
20577) -> Vec<crate::warp::Sample> {
20578 const MAX: usize = crate::warp::LEAST_SQUARES_SAMPLES_MAX;
20579 let up_available = mi_row > 0;
20580 let left_available = mi_col > 0;
20581 let mut samples = Vec::with_capacity(MAX);
20582 // lane-t900 r9: `EC_PROJ_MI=<mi_row>,<mi_col>` lists this block's warp
20583 // sample candidates in libaom's own order (above, left, top-left,
20584 // top-right) -- `num_proj_ref >= 1` is what picks the 3-symbol
20585 // motion_mode alphabet over the 2-symbol obmc one.
20586 let proj_dbg = crate::envflags::var("EC_PROJ_MI")
20587 .is_ok_and(|v| v == format!("{mi_row},{mi_col}"));
20588 let single_ref_match = |info: &MiInfo| {
20589 let m = info.ref_frame == ref_frame && info.ref_frame1.is_none();
20590 if proj_dbg {
20591 eprintln!(
20592 "EC_PROJ cand ref={} ref1={:?} size={} size_h={} is_inter={} want={ref_frame} match={m}",
20593 info.ref_frame, info.ref_frame1, info.size, info.size_h, info.is_inter
20594 );
20595 }
20596 m
20597 };
20598 let mut do_tl = true;
20599 let mut do_tr = true;
20600 let rec = |info: &MiInfo, row_offset: i32, sign_r: i32, col_offset: i32, sign_c: i32| {
20601 let nb_bw = (info.size * 4) as i32;
20602 // lane-rect r2: the neighbour's own true height -- a rect strip
20603 // neighbour donates its sample at ITS center (aom pts y=-72 for a
20604 // 32x16 above strip; the square assumption put it at -136).
20605 let nb_bh = (info.size_h * 4) as i32;
20606 crate::warp::record_sample(nb_bw, nb_bh, info.mv, row_offset, sign_r, col_offset, sign_c)
20607 };
20608
20609 'outer: {
20610 if up_available {
20611 let above = grid.get(mi_row - 1, mi_col);
20612 let superblock_width = above.map_or(1, |c| c.size).max(1);
20613 if bw4 <= superblock_width {
20614 let col_offset = -((mi_col % superblock_width) as isize);
20615 if col_offset < 0 {
20616 do_tl = false;
20617 }
20618 if col_offset + superblock_width as isize > bw4 as isize {
20619 do_tr = false;
20620 }
20621 if let Some(info) = above {
20622 if single_ref_match(info) {
20623 samples.push(rec(info, 0, -1, col_offset as i32, 1));
20624 if samples.len() >= MAX {
20625 break 'outer;
20626 }
20627 }
20628 }
20629 } else {
20630 let mut i = 0usize;
20631 let limit = bw4.min(mi_cols.saturating_sub(mi_col));
20632 while i < limit {
20633 let cell = grid.get(mi_row - 1, mi_col + i);
20634 let sw = cell.map_or(1, |c| c.size).max(1);
20635 if let Some(info) = cell {
20636 if single_ref_match(info) {
20637 samples.push(rec(info, 0, -1, i as i32, 1));
20638 if samples.len() >= MAX {
20639 break 'outer;
20640 }
20641 }
20642 }
20643 i += sw;
20644 }
20645 }
20646 }
20647
20648 if left_available {
20649 let left = grid.get(mi_row, mi_col - 1);
20650 let superblock_height = left.map_or(1, |c| c.size_h).max(1);
20651 if bh4 <= superblock_height {
20652 let row_offset = -((mi_row % superblock_height) as isize);
20653 if row_offset < 0 {
20654 do_tl = false;
20655 }
20656 if let Some(info) = left {
20657 if single_ref_match(info) {
20658 samples.push(rec(info, row_offset as i32, 1, 0, -1));
20659 if samples.len() >= MAX {
20660 break 'outer;
20661 }
20662 }
20663 }
20664 } else {
20665 let mut i = 0usize;
20666 let limit = bh4.min(mi_rows.saturating_sub(mi_row));
20667 while i < limit {
20668 let cell = grid.get(mi_row + i, mi_col - 1);
20669 let sh = cell.map_or(1, |c| c.size_h).max(1);
20670 if let Some(info) = cell {
20671 if single_ref_match(info) {
20672 samples.push(rec(info, i as i32, 1, 0, -1));
20673 if samples.len() >= MAX {
20674 break 'outer;
20675 }
20676 }
20677 }
20678 i += sh;
20679 }
20680 }
20681 }
20682
20683 if do_tl && left_available && up_available {
20684 if let Some(info) = grid.get(mi_row - 1, mi_col - 1) {
20685 if single_ref_match(info) {
20686 samples.push(rec(info, 0, -1, 0, -1));
20687 if samples.len() >= MAX {
20688 break 'outer;
20689 }
20690 }
20691 }
20692 }
20693
20694 // lane-t900 r9: libaom passes `AOMMAX(xd->width, xd->height)` here
20695 // (`mvref_common.c:1235`), NOT the block's width -- a rect block's
20696 // top-right reach is probed at its LONGER side. With `bw4` a 64x128
20697 // block found a top-right sample libaom never sees, so
20698 // `num_proj_ref >= 1` picked the 3-symbol `motion_mode_cdf` where
20699 // libaom reads the 2-symbol `obmc_cdf` (class
20700 // wrong-alphabet-same-value).
20701 let tr_reach = crate::mvstack::has_top_right(mi_row, mi_col, bw4, bh4);
20702 if do_tr && bw4 != bh4 && tr_reach != has_top_right(mi_row, mi_col, bw4) {
20703 TR_REACH_LONGER_SIDE_HITS.with(|c| c.set(c.get() + 1));
20704 }
20705 if do_tr && tr_reach {
20706 let tr_col = mi_col + bw4;
20707 if mi_row > 0 && tr_col < mi_cols {
20708 if let Some(info) = grid.get(mi_row - 1, tr_col) {
20709 if single_ref_match(info) {
20710 samples.push(rec(info, 0, -1, bw4 as i32, 1));
20711 }
20712 }
20713 }
20714 }
20715 }
20716 samples
20717}
20718
20719/// `mbmi->num_proj_ref`: [`find_samples`]'s own count, all that
20720/// `motion_mode_allowed` needs to pick the 3-symbol `motion_mode_cdf` over
20721/// the 2-symbol `obmc_cdf` (spec 5.11.24).
20722#[allow(clippy::too_many_arguments)]
20723fn num_proj_ref(
20724 grid: &MiGrid,
20725 mi_row: usize,
20726 mi_col: usize,
20727 bw4: usize,
20728 bh4: usize,
20729 mi_cols: usize,
20730 mi_rows: usize,
20731 ref_frame: i8,
20732) -> u8 {
20733 find_samples(grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame).len() as u8
20734}
20735
20736/// `av1_get_obmc_mask` (`reconinter.c`): the per-position blend weight
20737/// (`AOM_BLEND_A64` numerator, out of 64) for the neighbour's own
20738/// contribution's *complement* -- i.e. `dst = (mask*orig + (64-mask)*nbr +
20739/// 32) >> 6`, low near the shared border (heavier neighbour weight) rising
20740/// to 64 (no neighbour contribution) away from it. Only the lengths this
20741/// decoder's own overlap sizes ever produce (luma 8/16/32, chroma 4/8/16)
20742/// are transcribed.
20743fn obmc_mask(len: usize) -> &'static [u8] {
20744 // lane-gmaffine r1: the two SHORT masks (libaom `reconinter.c`
20745 // `obmc_mask_1`/`obmc_mask_2`) -- an 8x8 leaf's chroma plane is 4x4, so
20746 // its overlap is 2 (and 1 at a half-block edge). Unreachable until this
20747 // round wired interior 16x16 splits down to real 8x8 leaves, where the
20748 // old `unreachable!()` below fired as a hard panic.
20749 const M1: [u8; 1] = [64];
20750 // lane-inter8 r1: `obmc_mask_2` (`reconinter.c` 753) -- reached by the
20751 // LEFT pass of an 8x8 block's chroma plane (overlap 4 luma columns, 2
20752 // chroma), which only became live once 8x8 inter leaves stopped being
20753 // refused.
20754 const M2: [u8; 2] = [45, 64];
20755 const M4: [u8; 4] = [39, 50, 59, 64];
20756 const M8: [u8; 8] = [36, 42, 48, 53, 57, 61, 64, 64];
20757 const M16: [u8; 16] = [
20758 34, 37, 40, 43, 46, 49, 52, 54, 56, 58, 60, 61, 64, 64, 64, 64,
20759 ];
20760 const M32: [u8; 32] = [
20761 33, 35, 36, 38, 40, 41, 43, 44, 45, 47, 48, 50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 60,
20762 61, 62, 64, 64, 64, 64, 64, 64, 64, 64,
20763 ];
20764 match len {
20765 1 => &M1,
20766 2 => &M2,
20767 4 => &M4,
20768 8 => &M8,
20769 16 => &M16,
20770 32 => &M32,
20771 _ => unreachable!("obmc overlap length outside this decoder's own block-size range"),
20772 }
20773}
20774
20775/// A bordering block's own resolved interp filter kernel, `(h, v)` --
20776/// mirrors [`resolve_interp_filter`]'s own return order from its stored
20777/// `[u8; 2]` (`Neighbours::above_filter`/`left_filter`, `[sym0, sym1]` =
20778/// `[v_sym, h_sym]`). The `[3, 3]` sentinel is only ever stored for an intra
20779/// neighbour (excluded by [`overlappable_above`]/[`overlappable_left`]'s
20780/// `is_inter` gate) or when `interp_fixed` is `Some` for the whole frame
20781/// (handled here first) -- so a sentinel reaching the kernel lookup means the
20782/// stream desynced upstream, and this refuses instead of panicking.
20783fn neighbour_filter(
20784 interp_fixed: Option<mc::InterpFilterKind>,
20785 sym: [u8; 2],
20786) -> Result<(mc::InterpFilterKind, mc::InterpFilterKind)> {
20787 if let Some(kind) = interp_fixed {
20788 return Ok((kind, kind));
20789 }
20790 // lane-golomb r9: this used to hand the sentinel straight to
20791 // `from_switchable_symbol`, which PANICS on any value above 2 -- a crash
20792 // on stream data (measured on a real 192x68 cq40 aomenc stream, where an
20793 // inter leaf below 8x8 desyncs upstream and leaves an unrecorded filter
20794 // behind). A decoder must refuse such a stream by name, never abort the
20795 // process; the desync that produces the sentinel belongs to lane-intersub8.
20796 if sym[0] > 2 || sym[1] > 2 {
20797 return Err(unsupported(
20798 "an OBMC neighbour whose switchable interp filter was never recorded",
20799 ));
20800 }
20801 OBMC_FILTER_BAND_READS.with(|c| c.set(c.get() + 1));
20802 Ok((
20803 mc::InterpFilterKind::from_switchable_symbol(sym[1] as usize),
20804 mc::InterpFilterKind::from_switchable_symbol(sym[0] as usize),
20805 ))
20806}
20807
20808/// lane-obmcrec r1 MEASUREMENT rung (`EC_OBMCREC=1`): every OBMC neighbour whose
20809/// recorded switchable-filter symbols are the `[3, 3]` "never recorded" sentinel
20810/// -- names the neighbour's own position/shape/reference so the decode path that
20811/// failed to record its filter can be identified. Read-only, off by default.
20812#[allow(clippy::too_many_arguments)]
20813fn obmcrec_probe(
20814 dir: &str,
20815 mi_row: usize,
20816 mi_col: usize,
20817 write_w: usize,
20818 write_h: usize,
20819 off4: usize,
20820 span4: usize,
20821 nb: &MiInfo,
20822 syms: [u8; 2],
20823 cell: Option<MiInfo>,
20824 fixed: bool,
20825) {
20826 if (syms[0] <= 2 && syms[1] <= 2) || !crate::envflags::env_flag!("EC_OBMCREC") {
20827 return;
20828 }
20829 eprintln!(
20830 "OBMCREC {dir} cur_mi=({mi_row},{mi_col}) cur_wh=({write_w}x{write_h}) off4={off4} \
20831span4={span4} syms={syms:?} fixed={fixed} nb_size=({}x{}) nb_ref={} nb_ref1={:?} nb_mv=({},{}) \
20832nb_newmv={} cell_size={:?} cell_inter={:?} cell_ref={:?} sb_row_off={} sb_col_off={}",
20833 nb.size * 4,
20834 nb.size_h * 4,
20835 nb.ref_frame,
20836 nb.ref_frame1,
20837 nb.mv.0,
20838 nb.mv.1,
20839 nb.is_new_mv,
20840 cell.map(|c| (c.size * 4, c.size_h * 4)),
20841 cell.map(|c| c.is_inter),
20842 cell.map(|c| c.ref_frame),
20843 mi_row % 32,
20844 mi_col % 32,
20845 );
20846}
20847
20848/// One neighbour's own re-prediction over a `w`x`h` region, MC'd fresh
20849/// against its own `mv`/reference/filter (libaom `av1_build_inter_predictor`
20850/// under `av1_setup_build_prediction_by_{above,left}_pred`).
20851#[allow(clippy::too_many_arguments)]
20852fn obmc_neighbour_pred(
20853 refplane: &PlaneBuf,
20854 x: usize,
20855 y: usize,
20856 mv: (i32, i32),
20857 w: usize,
20858 h: usize,
20859 luma: bool,
20860 h_kind: mc::InterpFilterKind,
20861 v_kind: mc::InterpFilterKind,
20862 // lane-scaledref r1: spec 7.11.3.3's x_scale_fp for THIS neighbour's own
20863 // reference (derived from luma widths, applied unchanged to chroma whose
20864 // x_q4 is already in its own plane's pixel units). `REF_NO_SCALE` takes
20865 // the ordinary stride-1 path bit-exact.
20866 x_scale_fp: i64,
20867) -> Vec<u16> {
20868 let mut out = vec![0u16; w * h];
20869 if x_scale_fp == mc::REF_NO_SCALE {
20870 mc::predict_with_filters(
20871 &refplane.data,
20872 refplane.width,
20873 refplane.true_width,
20874 refplane.true_height,
20875 mv_to_q4(x, mv.1, luma),
20876 mv_to_q4(y, mv.0, luma),
20877 w,
20878 h,
20879 h_kind,
20880 v_kind,
20881 &mut out,
20882 );
20883 } else {
20884 mc::predict_scaled(
20885 &refplane.data,
20886 refplane.width,
20887 refplane.true_width,
20888 refplane.true_height,
20889 mv_to_q4(x, mv.1, luma),
20890 mv_to_q4(y, mv.0, luma),
20891 x_scale_fp,
20892 w,
20893 h,
20894 h_kind,
20895 v_kind,
20896 &mut out,
20897 );
20898 }
20899 out
20900}
20901
20902/// Blends `tmp` into `dst` (stride `stride`) at `(ox, oy)`, mask varying by
20903/// row (the above-neighbour pass, `aom_blend_a64_vmask`).
20904/// `ii_weights1d` (reconinter.c:524): the interintra smooth-mask falloff.
20905const II_WEIGHTS_1D: [u8; 128] = [
20906 60, 58, 56, 54, 52, 50, 48, 47, 45, 44, 42, 41, 39, 38, 37, 35, 34, 33, 32,
20907 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 22, 21, 20, 19, 19, 18, 18, 17, 16,
20908 16, 15, 15, 14, 14, 13, 13, 12, 12, 12, 11, 11, 10, 10, 10, 9, 9, 9, 8,
20909 8, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4,
20910 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2,
20911 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1,
20912 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
20913];
20914
20915/// lane-interintra r1: non-wedge interintra prediction for one plane
20916/// (reconinter.c `av1_build_interintra_predictor` + `combine_interintra` +
20917/// `build_smooth_interintra_mask`). Builds the intra predictor for the
20918/// block's II mode (DC/V/H/SMOOTH, angle 0, no filter-intra) from `plane`'s
20919/// own decoded edges at `(x, y)`, then blends it over the inter prediction
20920/// in `pred`: `comp = (mask*intra + (64-mask)*inter + 32) >> 6`
20921/// (`aom_blend_a64_mask`, intra as src0). `ii_size_scales[plane_bsize]`
20922/// reduces to `128 / side` for the square plane sizes this decoder reaches.
20923/// lane-wii r2: `wedge == Some(..)` replaces the mode mask with the wedge
20924/// codebook mask (fixed sign 0; luma stride, 2x2 box-averaged for chroma).
20925fn interintra_blend(
20926 plane: &PlaneBuf,
20927 x: usize,
20928 y: usize,
20929 bw: usize,
20930 bh: usize,
20931 stride: usize,
20932 ii_mode: u8,
20933 wedge: Option<(&'static [u8], usize)>,
20934 pred: &mut [u16],
20935) {
20936 // `interintra_to_intra_mode`: II_DC/II_V/II_H/II_SMOOTH.
20937 let intra_mode = match ii_mode {
20938 0 => crate::intra::DC_PRED,
20939 1 => crate::intra::V_PRED,
20940 2 => crate::intra::H_PRED,
20941 _ => crate::intra::SMOOTH_PRED,
20942 };
20943 let (above, left, corner) = plane.edges_rect(
20944 x,
20945 y,
20946 bw,
20947 bh,
20948 crate::encode::Reach {
20949 above_right: false,
20950 below_left: false,
20951 },
20952 );
20953 let mut intra = vec![0u16; bw * bh];
20954 // Edge filtering never applies here: V/H at delta 0 are plain edge
20955 // copies (angle 90/180 skip the directional walk), DC/SMOOTH carry no
20956 // angle at all.
20957 predict(
20958 intra_mode,
20959 0,
20960 above.as_deref(),
20961 left.as_deref(),
20962 corner,
20963 bw,
20964 bh,
20965 false,
20966 false,
20967 &mut intra,
20968 );
20969 // `ii_size_scales[bsize]` is keyed on the block's LONGER side
20970 // (`MAX_SB_SIZE >> max(bw,bh)` order), not on the square this decoder
20971 // builds the predictor buffer at.
20972 let scale = 128 / bw.max(bh);
20973 for i in 0..bh {
20974 for j in 0..bw {
20975 let m = u32::from(match wedge {
20976 // lane-wii r2: wedge-interintra mask (aom_blend_a64_mask
20977 // over the wedge codebook, intra as src0, fixed sign 0).
20978 // Luma plane: mask rows are luma-resolution, ms == side.
20979 // 4:2:0 chroma: 2x2 box average (reconinter.c sub8x8 --
20980 // subw == subh == 1).
20981 Some((mask, ms)) if ms == stride => mask[i * stride + j],
20982 Some((mask, ms)) => {
20983 let t = 2 * i * ms + 2 * j;
20984 ((u32::from(mask[t])
20985 + u32::from(mask[t + 1])
20986 + u32::from(mask[t + ms])
20987 + u32::from(mask[t + ms + 1])
20988 + 2)
20989 >> 2) as u8
20990 }
20991 None => match ii_mode {
20992 0 => 32,
20993 1 => II_WEIGHTS_1D[i * scale],
20994 2 => II_WEIGHTS_1D[j * scale],
20995 _ => II_WEIGHTS_1D[i.min(j) * scale],
20996 },
20997 });
20998 let idx = i * stride + j;
20999 pred[idx] = ((m * u32::from(intra[i * bw + j]) + (64 - m) * u32::from(pred[idx]) + 32)
21000 >> 6) as u16;
21001 }
21002 }
21003}
21004
21005/// `w` is the number of columns actually written (clipped to the block's own
21006/// buffer at a frame edge); `ts` is `tmp`'s own stride, the neighbour
21007/// prediction's full width.
21008#[allow(clippy::too_many_arguments)]
21009fn obmc_blend_v(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, ts: usize, tmp: &[u16]) {
21010 let mask = obmc_mask(h);
21011 for row in 0..h {
21012 let m = u32::from(mask[row]);
21013 for col in 0..w {
21014 let d = &mut dst[(oy + row) * stride + ox + col];
21015 let t = u32::from(tmp[row * ts + col]);
21016 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
21017 }
21018 }
21019}
21020
21021/// Blends `tmp` into `dst` at `(ox, oy)`, mask varying by column (the
21022/// left-neighbour pass, `aom_blend_a64_hmask`).
21023fn obmc_blend_h(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u16]) {
21024 let mask = obmc_mask(w);
21025 for row in 0..h {
21026 for col in 0..w {
21027 let m = u32::from(mask[col]);
21028 let d = &mut dst[(oy + row) * stride + ox + col];
21029 let t = u32::from(tmp[row * w + col]);
21030 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
21031 }
21032 }
21033}
21034
21035/// libaom's own `BLOCK_SIZE` enum index for a `w4`x`h4` (mi-unit) block --
21036/// only for the `EC_OBMC` trace rung below, so it reads byte-identical to
21037/// the instrumented aomdec's `backup_mbmi.bsize`.
21038fn ec_obmc_bsize(w4: usize, h4: usize) -> i32 {
21039 match (w4, h4) {
21040 (1, 1) => 0,
21041 (1, 2) => 1,
21042 (2, 1) => 2,
21043 (2, 2) => 3,
21044 (2, 4) => 4,
21045 (4, 2) => 5,
21046 (4, 4) => 6,
21047 (4, 8) => 7,
21048 (8, 4) => 8,
21049 (8, 8) => 9,
21050 (8, 16) => 10,
21051 (16, 8) => 11,
21052 (16, 16) => 12,
21053 (1, 4) => 16,
21054 (4, 1) => 17,
21055 (2, 8) => 18,
21056 (8, 2) => 19,
21057 (4, 16) => 20,
21058 (16, 4) => 21,
21059 _ => -1,
21060 }
21061}
21062
21063/// The `EC_OBMC` rung: one line per blended neighbour, in the instrumented
21064/// aomdec's own byte format (`decodeframe.c`
21065/// `dec_build_prediction_by_{above,left}_pred`), so the two decoders' OBMC
21066/// neighbour lists diff line for line. `filt` is libaom's packed
21067/// `interp_filters.as_int` = `y_filter | (x_filter << 16)`.
21068#[allow(clippy::too_many_arguments)]
21069fn ec_obmc_trace(
21070 dir: &str,
21071 mi_row: usize,
21072 mi_col: usize,
21073 write_w: usize,
21074 write_h: usize,
21075 rel: usize,
21076 op: usize,
21077 nb: &MiInfo,
21078 h_kind: mc::InterpFilterKind,
21079 v_kind: mc::InterpFilterKind,
21080) {
21081 if !crate::envflags::env_flag!("EC_OBMC") {
21082 return;
21083 }
21084 let sym = |k: mc::InterpFilterKind| match k {
21085 mc::InterpFilterKind::Smooth => 1u32,
21086 mc::InterpFilterKind::Sharp => 2,
21087 _ => 0,
21088 };
21089 eprintln!(
21090 "EC_OBMC {dir} mi=({mi_row},{mi_col}) wh=({write_w}x{write_h}) rel={rel} op={op} \
21091nbmv=({},{}) nbref={} nbbsize={} filt={}",
21092 nb.mv.0,
21093 nb.mv.1,
21094 nb.ref_frame,
21095 ec_obmc_bsize(nb.size, nb.size_h),
21096 sym(v_kind) | (sym(h_kind) << 16),
21097 );
21098}
21099
21100/// `av1_build_obmc_inter_prediction` (libaom `reconinter.c`): re-predicts
21101/// the overlap strip against each bordering above/left inter neighbour's own
21102/// mv/ref/filter and blends it into this block's just-built single-reference
21103/// prediction, luma then both 4:2:0 chroma planes -- above pass first, then
21104/// left, each reading only the *original* prediction this function was
21105/// handed (never the other pass's own output), matching libaom's own
21106/// independence between the two. `max_neighbor_obmc`'s own cap table
21107/// (`{0,1,2,3,4,4}` indexed by `mi_size_wide_log2`/`_high_log2`, this
21108/// decoder's own square blocks always index the same value both ways) bounds
21109/// how many bordering blocks actually get blended, separate from the
21110/// eligibility scan's own unbounded ("any at all") walk.
21111#[allow(clippy::too_many_arguments)]
21112fn obmc_blend(
21113 grid: &MiGrid,
21114 neighbours: &Neighbours,
21115 mi_row: usize,
21116 mi_col: usize,
21117 bw4: usize,
21118 bh4: usize,
21119 mi_rows: usize,
21120 mi_cols: usize,
21121 side: usize,
21122 write_w: usize,
21123 write_h: usize,
21124 chroma_side: usize,
21125 px: usize,
21126 py: usize,
21127 cpx: usize,
21128 cpy: usize,
21129 ref_y: &PlaneBuf,
21130 ref_u: &PlaneBuf,
21131 ref_v: &PlaneBuf,
21132 other_refs: &RefSlots,
21133 interp_fixed: Option<mc::InterpFilterKind>,
21134 // lane-scaledref r1: this frame's own coded luma width -- each OBMC
21135 // neighbour is re-predicted against ITS OWN reference, which may be
21136 // scaled differently from this block's (spec 7.11.3.3 / libaom
21137 // `av1_setup_build_prediction_by_above_pred` passing that ref's own
21138 // `scale_factors`).
21139 frame_width: usize,
21140 pred_y: &mut [u16],
21141 pred_u: &mut [u16],
21142 pred_v: &mut [u16],
21143) -> Result<()> {
21144 // lane-rect r2 (libaom av1_build_obmc_inter_prediction): each pass has
21145 // its OWN neighbour cap (width-log2 for above, height-log2 for left) and
21146 // overlap (bh/2 rows above, bw/2 cols left) -- one square `side` was
21147 // right only for square blocks.
21148 // libaom `max_neighbor_obmc[6] = { 0, 1, 2, 3, 4, 4 }` indexed by
21149 // `mi_size_wide_log2[bsize]` (above pass) / `mi_size_high_log2` (left):
21150 // 1 mi -> 0, 2 -> 1, 4 -> 2, 8 -> 3, 16+ -> 4. lane-inter4 r3: the old
21151 // `1..=4 => 2` row was right only for blocks at least 16 px on that axis
21152 // -- a 16x8 leaf's LEFT pass (bh4 = 2) walked up to two neighbours where
21153 // libaom walks one, blending an extra 8-px-tall neighbour into every
21154 // rect leaf with two of them on its left edge (class table-narrowed-to-
21155 // the-reachable-sizes; the square gates could never expose it).
21156 let max_nb = |n4: usize| match n4 {
21157 0..=1 => 0,
21158 2 => 1,
21159 3..=4 => 2,
21160 5..=8 => 3,
21161 _ => 4,
21162 };
21163 // lane-inter4 r4: r3 refused OBMC on a 16x8/8x16 leaf (5302 luma pixels
21164 // of one frame wrong). Re-measured on this tree with an `EC_OBMC` rung in
21165 // both decoders on that exact stream: the neighbour lists agree entry for
21166 // entry (position, span, mv, ref, size, filter) and all six pre-filter
21167 // frames are byte-identical to the instrumented aomdec's. The refusal is
21168 // gone; the counter below is what the gate's `--enable-obmc=1` arm reads.
21169 // The only decode-path change between r3's measurement and this one is the
21170 // lane-interbis merge (`build_motion_field`'s compound slot walk), which
21171 // moves temporal MV candidates -- not bisected further.
21172 if matches!((write_w, write_h), (16, 8) | (8, 16)) {
21173 OBMC_RECT_LEAF_HITS.with(|c| c.set(c.get() + 1));
21174 }
21175 // lane-sb128c r1: libaom caps the overlap strip at a 64x64 block's own
21176 // half (`reconinter.c` 860/899: `AOMMIN(block_size_high[bsize],
21177 // block_size_high[BLOCK_64X64]) >> 1`, and the `block_size_wide` mirror) --
21178 // inert below 128, where a 128x128 block would otherwise blend a 64-row
21179 // strip `obmc_mask` has no table for.
21180 let overlap_above = write_h.min(64) / 2;
21181 let overlap_left = write_w.min(64) / 2;
21182 // lane-inter8 r1 / lane-scaledref r1: `av1_skip_u4x4_pred_in_obmc`
21183 // (`reconinter.c` 820, `DISABLE_CHROMA_U8X8_OBMC == 0` -- "one-sided
21184 // obmc") returns `dir == 0` when the chroma plane's own block is
21185 // BLOCK_4X4/8X4/4X8 (an 8x8, 16x8 or 8x16 luma block at 4:2:0): the
21186 // ABOVE pass skips chroma entirely, the LEFT pass still blends it.
21187 let skip_chroma_above = matches!((write_w, write_h), (8, 8) | (16, 8) | (8, 16));
21188
21189 // lane-t900 r13 rung: EC_MCB="<plane>:<px>:<py>[:<frame>]" (chroma plane
21190 // 1 only) prints this block's chroma prediction rows before and after the
21191 // OBMC blend, matching the instrumented aomdec's EC_MCB dump.
21192 let ec_mcb: Option<(usize, usize, i64)> = crate::envflags::var("EC_MCB").ok().and_then(|v| {
21193 let f: Vec<&str> = v.split(':').collect();
21194 if f.len() < 3 || f[0] != "1" {
21195 return None;
21196 }
21197 let (x, y) = (f[1].parse::<usize>().ok()?, f[2].parse::<usize>().ok()?);
21198 let fr = f.get(3).and_then(|s| s.parse::<i64>().ok()).unwrap_or(-1);
21199 let idx = PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst) as i64;
21200 if x >= cpx && x < cpx + write_w / 2 && y >= cpy && y < cpy + write_h / 2
21201 && (fr < 0 || fr == idx)
21202 {
21203 Some((x, y, idx))
21204 } else {
21205 None
21206 }
21207 });
21208 if let Some((_, _, idx)) = ec_mcb {
21209 eprintln!(
21210 "OUR_MCB pre f={idx} cpx={cpx} cpy={cpy} cw={} ch={}",
21211 write_w / 2,
21212 write_h / 2
21213 );
21214 for r in 0..write_h / 2 {
21215 let row: Vec<u16> = (0..write_w / 2).map(|c| pred_u[r * chroma_side + c]).collect();
21216 eprintln!("OUR_MCB prerow{r}: {row:?}");
21217 }
21218 }
21219 for (off4, span4, nb, src4) in overlappable_above(grid, mi_row, mi_col, bw4, mi_cols, max_nb(bw4))
21220 {
21221 // `Neighbours::above_filter` is indexed in `SUB`(16px)-wide columns
21222 // (this decoder's own outer block-loop granularity), one step
21223 // coarser than the mi(4px) units `overlappable_above` walks in --
21224 // divide back down to that column.
21225 // lane-gmaffine r2: the neighbour's OWN mi-granular filter
21226 // (libaom `av1_setup_build_prediction_by_above_pred` reads
21227 // `above_mbmi->interp_filters`); the 16px-granular `Neighbours` slot
21228 // stays as the fallback for paths that do not record one yet
21229 // (compound), which is what every earlier round used.
21230 let above_syms = neighbours.above_filter[mi_col + src4];
21231 obmcrec_probe(
21232 "above", mi_row, mi_col, write_w, write_h, off4, span4, &nb, above_syms,
21233 grid.get(mi_row - 1, mi_col + src4).copied(), interp_fixed.is_some(),
21234 );
21235 let (h_kind, v_kind) = neighbour_filter(interp_fixed, above_syms)?;
21236 ec_obmc_trace("above", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind);
21237 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
21238 let nb_scale = mc::scale_factor(ny.width, frame_width);
21239 if mi_col + off4 + span4 > mi_cols {
21240 OBMC_EDGE_SPAN_HITS.with(|c| c.set(c.get() + 1));
21241 }
21242 let (bw, bh, ox) = (span4 * 4, overlap_above, off4 * 4);
21243 // lane-t900 r14: the prediction is `op_mi_size` wide (kernel choice
21244 // included); only the WRITE is clipped to this block's own buffer.
21245 let tmp_y = obmc_neighbour_pred(ny, px + ox, py, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale);
21246 obmc_blend_v(pred_y, side, ox, 0, bw.min(write_w - ox), bh, bw, &tmp_y);
21247 if !skip_chroma_above {
21248 // lane-t900 r13 (measured, NOT a defect): libaom's min-4 clamp
21249 // (`dec_build_prediction_by_above_pred`) sizes only the OBMC
21250 // PREDICTION buffer; the blend length is the plain half
21251 // (`build_obmc_inter_pred_above`: `overlap >> ss_y`), so flooring
21252 // this at 4 blends rows libaom never blends -- on a 10-bit
21253 // 1920x792 cut that went 36 differing frames -> 266, worst
21254 // 13 B -> 11007 B.
21255 let (cbw, cbh, cox) = (bw / 2, overlap_above / 2, ox / 2);
21256 let cw = cbw.min(write_w / 2 - cox);
21257 let tmp_u = obmc_neighbour_pred(nu, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
21258 obmc_blend_v(pred_u, chroma_side, cox, 0, cw, cbh, cbw, &tmp_u);
21259 let tmp_v = obmc_neighbour_pred(nv, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
21260 obmc_blend_v(pred_v, chroma_side, cox, 0, cw, cbh, cbw, &tmp_v);
21261 }
21262 }
21263
21264 for (off4, span4, nb, src4) in overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, max_nb(bh4))
21265 {
21266 let left_syms = neighbours.left_filter[mi_row + src4];
21267 obmcrec_probe(
21268 "left", mi_row, mi_col, write_w, write_h, off4, span4, &nb, left_syms,
21269 grid.get(mi_row + src4, mi_col - 1).copied(), interp_fixed.is_some(),
21270 );
21271 let (h_kind, v_kind) = neighbour_filter(interp_fixed, left_syms)?;
21272 ec_obmc_trace("left", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind);
21273 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
21274 let nb_scale = mc::scale_factor(ny.width, frame_width);
21275 if mi_row + off4 + span4 > mi_rows {
21276 OBMC_EDGE_SPAN_HITS.with(|c| c.set(c.get() + 1));
21277 }
21278 let (bw, bh, oy) = (overlap_left, span4 * 4, off4 * 4);
21279 let tmp_y = obmc_neighbour_pred(ny, px, py + oy, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale);
21280 obmc_blend_h(pred_y, side, 0, oy, bw, bh.min(write_h - oy), &tmp_y);
21281 let (cbw, cbh, coy) = (overlap_left / 2, bh / 2, oy / 2);
21282 let tmp_u = obmc_neighbour_pred(nu, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
21283 if let Some((_, _, idx)) = ec_mcb {
21284 eprintln!(
21285 "OUR_MCB left f={idx} off4={off4} span4={span4} cbw={cbw} cbh={cbh} coy={coy} mv=({},{}) ref0={}",
21286 nb.mv.0, nb.mv.1, nb.ref_frame
21287 );
21288 for r in 0..cbh {
21289 let row: Vec<u16> = (0..cbw).map(|c| tmp_u[r * cbw + c]).collect();
21290 eprintln!("OUR_MCB lrow{r}: {row:?}");
21291 }
21292 }
21293 let ch = cbh.min(write_h / 2 - coy);
21294 obmc_blend_h(pred_u, chroma_side, 0, coy, cbw, ch, &tmp_u);
21295 let tmp_v = obmc_neighbour_pred(nv, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
21296 obmc_blend_h(pred_v, chroma_side, 0, coy, cbw, ch, &tmp_v);
21297 }
21298 if let Some((_, _, idx)) = ec_mcb {
21299 for r in 0..write_h / 2 {
21300 let row: Vec<u16> = (0..write_w / 2).map(|c| pred_u[r * chroma_side + c]).collect();
21301 eprintln!("OUR_MCB post f={idx} row{r}: {row:?}");
21302 }
21303 }
21304 Ok(())
21305}
21306
21307/// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to
21308/// the square block sizes this decoder ever decodes (32/16/8, all
21309/// `min(w,h) >= 8`, `is_comp_ref_allowed` true): `COMPOUND_DIFFWTD` is then
21310/// always `is_interinter_compound_used`, so the function is always `true`
21311/// for `side` -- kept as a named call (rather than inlined `true`) so a
21312/// future sub-8 block size does not silently misdecode a real stream.
21313fn is_any_masked_compound_used_here(bw: usize, bh: usize) -> bool {
21314 // lane-inter16ab r4 (class sweep of the r3 CDF-row defect):
21315 // `is_comp_ref_allowed(bsize)` is `AOMMIN(block_size_wide, block_size_high)
21316 // >= 8` on the block's TRUE footprint -- a 16x4/4x16 strip is NOT allowed,
21317 // so libaom writes no `comp_group_idx` symbol there at all. Keyed off the
21318 // square `side` we read one the reference never wrote.
21319 bw.min(bh) >= 8
21320}
21321
21322/// The `BLOCK_SIZES_ALL` index of a `bw x bh` block (libaom `enum BLOCK_SIZE`,
21323/// `blockd.h`) -- the row every size-indexed inter CDF table
21324/// (`compound_type_cdf`, `wedge_idx_cdf`) is keyed by. Our `decode_inter_block`
21325/// carries the enclosing SQUARE `side` for context purposes (the accepted
21326/// strip corner-cut), so a 16x8 / 8x16 PARTITION_HORZ/VERT strip that reads
21327/// one of those symbols off `side` alone takes BLOCK_16X16's row and desyncs
21328/// (lane-inter16ab r3: a real 16x8 compound strip with `comp_group_idx == 1`,
21329/// decode-order frame 5, our range 64901 vs the oracle's 47271 at the very
21330/// next block's mode read).
21331fn bsize_all_index(bw: usize, bh: usize) -> Option<usize> {
21332 Some(match (bw, bh) {
21333 (4, 4) => 0,
21334 (4, 8) => 1,
21335 (8, 4) => 2,
21336 (8, 8) => 3,
21337 (8, 16) => 4,
21338 (16, 8) => 5,
21339 (16, 16) => 6,
21340 (16, 32) => 7,
21341 (32, 16) => 8,
21342 (32, 32) => 9,
21343 (32, 64) => 10,
21344 (64, 32) => 11,
21345 (64, 64) => 12,
21346 (64, 128) => 13,
21347 (128, 64) => 14,
21348 (128, 128) => 15,
21349 (4, 16) => 16,
21350 (16, 4) => 17,
21351 (8, 32) => 18,
21352 (32, 8) => 19,
21353 (16, 64) => 20,
21354 (64, 16) => 21,
21355 _ => return None,
21356 })
21357}
21358
21359/// `av1_wedge_params_lookup[bsize].wedge_types > 0` (libaom `reconinter.c`):
21360/// the block sizes that carry a wedge codebook at all. A `compound_type`
21361/// symbol is written only for these; every other size infers
21362/// `COMPOUND_DIFFWTD`.
21363fn wedge_used_bsize(bw: usize, bh: usize) -> bool {
21364 matches!(
21365 (bw, bh),
21366 (8, 8) | (8, 16) | (16, 8) | (16, 16) | (16, 32) | (32, 16) | (32, 32) | (8, 32) | (32, 8)
21367 )
21368}
21369
21370
21371
21372
21373/// Whether a compound reference pair is unidirectional (both references on
21374/// the same temporal side of the current frame) -- `has_uni_comp_refs`
21375/// (libaom `av1_reference_frame_utils.h`/`pred_common.c`'s own definition:
21376/// a pair is `UNIDIR_COMP_REFERENCE` exactly when neither reference is
21377/// backward-while-the-other-is-forward, i.e. `is_backward(ref0) ==
21378/// is_backward(ref1)`). Used to build a real
21379/// [`crate::mvstack::NeighbourRef::uni`] once `ref1` is known, matching
21380/// [`crate::mvstack::comp_reference_type_ctx`]'s own `is_backward` calls.
21381fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool {
21382 let backward = |r: i8| (BWDREF_FRAME..=ALTREF_FRAME).contains(&r);
21383 backward(ref0) == backward(ref1)
21384}
21385
21386/// `get_comp_group_idx_context` (libaom `pred_common.h`): sums the
21387/// above/left neighbour contributions [`Neighbours::record_inter`]/
21388/// [`Neighbours::record_compound_ctx`] already precomputed, clamped to 5.
21389/// lane-inter8 r2: `at_mi` is the block's own top-left in 4x4 mi units --
21390/// an 8x8 leaf used to pass its enclosing 16x16's corner here, so all four
21391/// leaves read the same neighbour cell (class context-read-from-one-cell).
21392fn get_comp_group_idx_context(
21393 neighbours: &Neighbours,
21394 at_mi: (usize, usize),
21395 side: usize,
21396) -> usize {
21397 let _ = side;
21398 let (rmi, cmi) = at_mi;
21399 (neighbours.above_comp_group_idx[cmi] as usize + neighbours.left_comp_group_idx[rmi] as usize)
21400 .min(5)
21401}
21402
21403/// `get_comp_index_context` (libaom `pred_common.h`): the above/left
21404/// neighbour bits plus `3 * (fwd == bck)`, where `fwd`/`bck` are this
21405/// block's own two references' distances from the current frame (spec
21406/// 7.11.3.15's `get_relative_dist`, same convention
21407/// [`crate::compound::dist_wtd_comp_weight_assign`] uses).
21408#[allow(clippy::too_many_arguments)]
21409fn get_comp_index_context(
21410 neighbours: &Neighbours,
21411 at_mi: (usize, usize),
21412 side: usize,
21413 order_hint_bits: u32,
21414 cur_order_hint: u32,
21415 ref0_order_hint: u32,
21416 ref1_order_hint: u32,
21417) -> usize {
21418 let _ = side;
21419 let (rmi, cmi) = at_mi;
21420 let fwd =
21421 crate::motion_field::get_relative_dist(order_hint_bits, ref1_order_hint, cur_order_hint)
21422 .abs();
21423 let bck =
21424 crate::motion_field::get_relative_dist(order_hint_bits, cur_order_hint, ref0_order_hint)
21425 .abs();
21426 let offset = usize::from(fwd == bck);
21427 neighbours.above_compound_idx[cmi] as usize
21428 + neighbours.left_compound_idx[rmi] as usize
21429 + 3 * offset
21430}
21431
21432fn read_comp_mode(
21433 dec: &mut SymbolDecoder,
21434 cdfs: &mut Cdfs,
21435 above: Option<NeighbourRef>,
21436 left: Option<NeighbourRef>,
21437) -> bool {
21438 let ctx = reference_mode_ctx(above, left);
21439 let compound = dec.symbol(&mut cdfs.comp_mode[ctx]) == 1;
21440 if compound {
21441 COMP_MODE_HITS.with(|c| c.set(c.get() + 1));
21442 }
21443 compound
21444}
21445
21446/// Spec 5.11.25's `comp_reference_type` + the `uni_comp_ref`/`comp_ref`/
21447/// `comp_bwdref` trees (libaom `decodemv.c`'s `read_ref_frames` compound
21448/// arm), reached once [`read_comp_mode`] has already returned
21449/// `COMPOUND_REFERENCE`. Returns `(RefFrame[0], RefFrame[1])`.
21450/// `above`/`left` are [`comp_reference_type_ctx`]'s own `NeighbourRef`
21451/// convention; `above_ref`/`left_ref` are the scalar `1..=7`/`-1`
21452/// convention [`read_single_ref`] already uses, for every downstream binary
21453/// decision. libaom `pred_common.c`'s own compound context functions
21454/// (`av1_get_pred_context_uni_comp_ref_p[1|2]`, `comp_ref_p[1|2]`,
21455/// `comp_bwdref_p[1]`) turned out to be exactly [`single_ref_p1_ctx`]..
21456/// [`single_ref_p6_ctx`]/[`uni_comp_ref_p1_ctx`] under a different name
21457/// (same vote-the-neighbours-above-left shape, same forward/backward and
21458/// LAST/LAST2/LAST3/GOLDEN groupings) -- lane-av1comp audited each one
21459/// against the C source rather than porting six near-duplicate functions.
21460/// Its caller today only needs the symbols consumed, correctly, to keep the
21461/// arithmetic decoder's own state in sync before refusing the block by name
21462/// -- the returned pair is not yet threaded into any motion-compensation
21463/// path.
21464fn read_compound_ref_frames(
21465 dec: &mut SymbolDecoder,
21466 cdfs: &mut Cdfs,
21467 above: Option<NeighbourRef>,
21468 left: Option<NeighbourRef>,
21469 above_ref: i8,
21470 left_ref: i8,
21471) -> (i8, i8) {
21472 let a = (above_ref > 0).then_some(above_ref);
21473 let l = (left_ref > 0).then_some(left_ref);
21474 // libaom `av1_collect_neighbors_ref_counts` counts BOTH of a compound
21475 // neighbour's references, not just its first -- `a1`/`l1` carry that
21476 // second reference through to every vote below (lane-av1blend r6: a
21477 // missing `a1`/`l1` here was decoding `compound_idx` off the wrong CDF
21478 // row for a block sitting under a skip_mode-forced compound neighbour).
21479 let a1 = above.and_then(|n| n.ref1);
21480 let l1 = left.and_then(|n| n.ref1);
21481 let type_ctx = comp_reference_type_ctx(above, left);
21482 let unidir = dec.symbol(&mut cdfs.comp_ref_type[type_ctx]) == 0;
21483 if unidir {
21484 UNI_COMP_HITS.with(|c| c.set(c.get() + 1));
21485 // uni_comp_ref (p0): forward vs. backward -- av1_get_pred_context_-
21486 // uni_comp_ref_p is single_ref_p1's own forward/backward vote.
21487 let bit = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0]);
21488 if bit == 1 {
21489 (BWDREF_FRAME, ALTREF_FRAME)
21490 } else {
21491 let p1 = dec.symbol(&mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1]);
21492 if p1 == 1 {
21493 // uni_comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
21494 let p2 = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
21495 if p2 == 1 {
21496 (LAST_FRAME, GOLDEN_FRAME)
21497 } else {
21498 (LAST_FRAME, LAST3_FRAME)
21499 }
21500 } else {
21501 (LAST_FRAME, LAST2_FRAME)
21502 }
21503 }
21504 } else {
21505 // comp_ref (p0): LAST/LAST2 vs. LAST3/GOLDEN, same vote as single_ref_p3.
21506 let bit0 = dec.symbol(&mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0]);
21507 let ref0 = if bit0 == 0 {
21508 // comp_ref_p1: LAST vs. LAST2, same vote as single_ref_p4.
21509 let p1 = dec.symbol(&mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1]);
21510 if p1 == 1 { LAST2_FRAME } else { LAST_FRAME }
21511 } else {
21512 // comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
21513 let p2 = dec.symbol(&mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
21514 if p2 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
21515 };
21516 // comp_bwdref (p0): BWDREF/ALTREF2 vs. ALTREF, same vote as single_ref_p2.
21517 let bit1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0]);
21518 let ref1 = if bit1 == 0 {
21519 // comp_bwdref_p1: BWDREF vs. ALTREF2, same vote as single_ref_p6.
21520 let p1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1]);
21521 if p1 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
21522 } else {
21523 ALTREF_FRAME
21524 };
21525 (ref0, ref1)
21526 }
21527}
21528
21529/// Spec 5.11.24's `compound_mode` (lane-av1comp): which of the eight
21530/// `INTER_COMPOUND_MODES` (`NEAREST_NEARESTMV`..`NEW_NEWMV`, returned as
21531/// `0..=7`) a `COMPOUND_REFERENCE` block takes, reached once
21532/// [`read_comp_mode`] has already returned `COMPOUND_REFERENCE`. `ctx` is
21533/// libaom's `av1_mode_context_analyzer`'s compound branch --
21534/// `compound_mode_ctx_map[ref_mv_ctx >> 1][min(new_mv_ctx, COMP_NEWMV_CTXS
21535/// - 1)]` (`mvref_common.h`) -- folded from [`crate::mvstack::
21536/// find_mv_stack_compound`]'s own `new_mv_ctx`/`ref_mv_ctx`. The read symbol
21537/// is not yet turned into an assigned MV pair or motion-compensated --
21538/// lane-av1comp.
21539fn read_inter_compound_mode(
21540 dec: &mut SymbolDecoder,
21541 cdfs: &mut Cdfs,
21542 new_mv_ctx: usize,
21543 ref_mv_ctx: usize,
21544) -> u8 {
21545 let ctx = cdf::COMPOUND_MODE_CTX_MAP[ref_mv_ctx >> 1][new_mv_ctx.min(4)];
21546 COMPOUND_MODE_HITS.with(|c| c.set(c.get() + 1));
21547 dec.symbol(&mut cdfs.inter_compound_mode[ctx]) as u8
21548}
21549
21550/// spec 7.10.2.10 `assign_mv`'s compound branch, plus the compound half of
21551/// `read_drl_idx` (spec 5.11.24) it depends on -- `mode` is
21552/// [`read_inter_compound_mode`]'s own `0..=7` (`NEAREST_NEARESTMV`..
21553/// `NEW_NEWMV`, libaom `enums.h` order). Every `GLOBAL_GLOBALMV` side reads
21554/// as `(0, 0)` since [`crate::stream::decode_stream`] already refuses any
21555/// non-`IDENTITY` global motion model before a tile is ever decoded.
21556///
21557/// Ported straight from libaom `decodemv.c`'s `read_drl_idx` (the
21558/// `NEW_NEWMV`/`have_nearmv_in_inter_mode` branches) and `assign_mv`/its
21559/// caller's `ref_mv[]`/`nearmv[]` setup: the `NEAR_NEWMV`/`NEW_NEARMV`
21560/// `1 + ref_mv_idx` special case is folded into `new_idx` below, matching
21561/// `read_drl_idx`'s own comment about "offsetting the NEARESTMV mode".
21562fn assign_compound_mv(
21563 dec: &mut SymbolDecoder,
21564 cdfs: &mut Cdfs,
21565 comp_stack: &crate::mvstack::CompoundMvStack,
21566 mode: u8,
21567 allow_high_precision_mv: bool,
21568 force_integer_mv: bool,
21569 // lane-gm r2: `gm_get_motion_vector(ref0)`/`(ref1)` at this block's own
21570 // position, spec 7.10.2.10's `GLOBAL_GLOBALMV` assignment.
21571 global_mv: ((i32, i32), (i32, i32)),
21572) -> ((i32, i32), (i32, i32)) {
21573 const NEAREST_NEARESTMV: u8 = 0;
21574 const NEAR_NEARMV: u8 = 1;
21575 const NEAREST_NEWMV: u8 = 2;
21576 const NEW_NEARESTMV: u8 = 3;
21577 const NEAR_NEWMV: u8 = 4;
21578 const NEW_NEARMV: u8 = 5;
21579 const GLOBAL_GLOBALMV: u8 = 6;
21580 const NEW_NEWMV: u8 = 7;
21581
21582 let mut ref_mv_idx = 0usize;
21583 if mode == NEW_NEWMV {
21584 let mut idx = 0usize;
21585 while idx < 2 && comp_stack.entries.len() > idx + 1 {
21586 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
21587 break;
21588 }
21589 idx += 1;
21590 }
21591 ref_mv_idx = idx;
21592 } else if matches!(mode, NEAR_NEARMV | NEAR_NEWMV | NEW_NEARMV) {
21593 let mut idx = 1usize;
21594 while idx < 3 && comp_stack.entries.len() > idx + 1 {
21595 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
21596 break;
21597 }
21598 idx += 1;
21599 }
21600 ref_mv_idx = idx - 1;
21601 }
21602
21603 let near = comp_stack
21604 .entries
21605 .get(ref_mv_idx + 1)
21606 .map_or(comp_stack.near_mv, |e| (e.mv0, e.mv1));
21607 let new_idx = if matches!(mode, NEAR_NEWMV | NEW_NEARMV) {
21608 ref_mv_idx + 1
21609 } else {
21610 ref_mv_idx
21611 };
21612 let new_pred = comp_stack
21613 .entries
21614 .get(new_idx)
21615 .map_or(comp_stack.nearest_mv, |e| (e.mv0, e.mv1));
21616
21617 let read_new = |dec: &mut SymbolDecoder, cdfs: &mut Cdfs, base: (i32, i32)| {
21618 read_mv(
21619 dec,
21620 &mut cdfs.mv_comp,
21621 &mut cdfs.mv_joint,
21622 base,
21623 allow_high_precision_mv,
21624 force_integer_mv,
21625 )
21626 };
21627
21628 match mode {
21629 NEAREST_NEARESTMV => comp_stack.nearest_mv,
21630 NEAR_NEARMV => near,
21631 NEAREST_NEWMV => (comp_stack.nearest_mv.0, read_new(dec, cdfs, new_pred.1)),
21632 NEW_NEARESTMV => (read_new(dec, cdfs, new_pred.0), comp_stack.nearest_mv.1),
21633 NEAR_NEWMV => (near.0, read_new(dec, cdfs, new_pred.1)),
21634 NEW_NEARMV => (read_new(dec, cdfs, new_pred.0), near.1),
21635 GLOBAL_GLOBALMV => global_mv,
21636 _ => (
21637 read_new(dec, cdfs, new_pred.0),
21638 read_new(dec, cdfs, new_pred.1),
21639 ),
21640 }
21641}
21642
21643/// Derives this query block's own [`crate::mvstack::GmMvTable`] -- one
21644/// `gm_get_motion_vector` (spec 7.10.2.1) result per reference frame, at
21645/// THIS block's own `(mi_row, mi_col, bw4, bh4)` (mvstack.rs's own doc: the
21646/// table is always computed at the *querying* block's position, never a
21647/// donating neighbour's).
21648fn build_gm_mv_table(
21649 global_motion: &[ec_av1_syntax::WarpParams; 7],
21650 mi_row: usize,
21651 mi_col: usize,
21652 bw4: usize,
21653 bh4: usize,
21654 allow_high_precision_mv: bool,
21655 force_integer_mv: bool,
21656) -> crate::mvstack::GmMvTable {
21657 std::array::from_fn(|i| {
21658 let gm = &global_motion[i];
21659 crate::warp::gm_get_motion_vector(
21660 gm.model,
21661 &gm.params,
21662 mi_row,
21663 mi_col,
21664 bw4,
21665 bh4,
21666 allow_high_precision_mv,
21667 force_integer_mv,
21668 )
21669 })
21670}
21671
21672/// Decodes one square inter-frame block (32x32 whole or 16x16 leaf): skip,
21673/// `is_inter`, then either the single-reference/MV-stack/motion-vector chain
21674/// and motion-compensated reconstruction, or the inter frame's own intra
21675/// path (`Y_MODE` by size group, not `KF_Y_MODE` by neighbour), mirroring
21676/// [`crate::tile`]'s `sb_coeff_inter_frame_tile`'s whole-block branch and its
21677/// private `write_inter_frame_leaf` -- both share this one function here,
21678/// parameterised by `side`/the transform sets/scan tables/size group they
21679/// each use.
21680///
21681/// # Errors
21682/// Returns an error when a symbol names anything this decoder does not
21683/// reconstruct: a reference other than `LAST_FRAME`, `GLOBALMV` (round 3;
21684/// `NEARESTMV`/`NEARMV`/`NEWMV` are all reconstructed), or an intra
21685/// mode/tx-type outside what [`read_intra_mode`]/[`read_coeffs`] already
21686/// refuse.
21687#[allow(clippy::too_many_arguments)]
21688/// lane-inter4 r1: 16-px-cell coordinates -> MI (4-px) coordinates, the unit
21689/// [`decode_inter_block`]'s `at` now takes.
21690const fn sub16_to_mi(t: (usize, usize)) -> (usize, usize) {
21691 (t.0 * (SUB / MI), t.1 * (SUB / MI))
21692}
21693
21694fn decode_inter_block(
21695 dec: &mut SymbolDecoder,
21696 cdfs: &mut Cdfs,
21697 neighbours: &mut Neighbours,
21698 grid: &mut MiGrid,
21699 at: (usize, usize),
21700 side: usize,
21701 mi_cols: u32,
21702 mi_rows: u32,
21703 y: &mut PlaneBuf,
21704 u: &mut PlaneBuf,
21705 v: &mut PlaneBuf,
21706 ref_y: &PlaneBuf,
21707 ref_u: &PlaneBuf,
21708 ref_v: &PlaneBuf,
21709 // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own
21710 // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]`
21711 // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME`
21712 // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the
21713 // slot's still empty (an error-resilient stream, or too early in the
21714 // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below.
21715 other_refs: &RefSlots,
21716 sign_bias_table: &SignBiasTable,
21717 // lane-gm r2: this frame header's own `global_motion` table (spec
21718 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` same as `sign_bias_table`
21719 // -- feeds `warp::gm_get_motion_vector` for `GLOBALMV`/`GLOBAL_GLOBALMV`
21720 // assignment and the mv-stack's neighbour substitution.
21721 global_motion: &[ec_av1_syntax::WarpParams; 7],
21722 base_q_idx: u8,
21723 luma_set_intra: TxbSet,
21724 luma_set_inter: TxbSet,
21725 chroma_set: TxbSet,
21726 luma_tx: usize,
21727 chroma_tx: usize,
21728 scan_luma: &[u16],
21729 scan_chroma: &[u16],
21730 // lane-inter4 r3: superseded by `size_group_wh(write_w, write_h)` at the
21731 // one site that read it (`y_mode`) -- a rect strip's group comes from its
21732 // true footprint, not the caller's square `side`. Kept in the signature
21733 // rather than editing twenty call sites.
21734 _size_group: usize,
21735 allow_high_precision_mv: bool,
21736 force_integer_mv: bool,
21737 interp_fixed: Option<mc::InterpFilterKind>,
21738 enable_dual_filter: bool,
21739 tpl_frame: Option<&TplFrameArgs>,
21740 // lane-av1comp: this frame header's own `reference_select` bit -- `false`
21741 // means every block is `SINGLE_REFERENCE` by construction and `comp_mode`
21742 // is never read (spec 5.11.25); `true` reads `comp_mode` per block and
21743 // refuses (rather than silently misdecoding) the ones that pick
21744 // `COMPOUND_REFERENCE`, since two-reference motion compensation is not
21745 // wired yet.
21746 reference_select: bool,
21747 // lane-av1comp: `seq_params`' own masked-compound/distance-weighted-
21748 // compound enable bits, gating `comp_group_idx`/`compound_idx`
21749 // (spec 5.11.25) -- always present (unlike `tpl_frame`), since the
21750 // compound blend weights need this frame's own order hint regardless
21751 // of `use_ref_frame_mvs`.
21752 enable_masked_compound: bool,
21753 // lane-sb128 r4: this sequence header's own `enable_interintra_compound`
21754 // bit (spec 5.11.24's `interintra` read, libaom `decodemv.c`
21755 // read_inter_block_mode_info ~1490-1510) -- read right after `assign_mv`
21756 // and before `read_motion_mode` on the single-ref path below, gated by
21757 // `is_interintra_allowed` (single-ref, `BLOCK_8X8..=BLOCK_32X32`, and
21758 // every mode this single-ref branch can produce is already in
21759 // `SINGLE_INTER_MODE_START..END`); `interintra == 1` is a named refusal
21760 // (inter+intra blended prediction unimplemented) rather than a
21761 // mis-decode.
21762 enable_interintra_compound: bool,
21763 enable_jnt_comp: bool,
21764 order_hint_bits: u32,
21765 order_hint: u32,
21766 ref_order_hints: [u32; 7],
21767 // lane-av1comp round 14: this frame header's own `skip_mode_present` bit
21768 // and `skip_mode_frame` reference pair (spec 5.9.22, `frame.rs`'s
21769 // `read_skip_mode_params`, already 1-based `MV_REFERENCE_FRAME`) --
21770 // `skip_mode` (spec 5.11.23 `read_skip_mode`) is read *before* `skip`
21771 // when this is `true` (every block this decoder reaches is >= 8x8, so
21772 // `is_comp_ref_allowed` never gates it further); a `true` result forces
21773 // `skip_txfm`, `is_inter`, `NEAREST_NEARESTMV` of this pair with no mode/
21774 // DRL symbol read, and a plain average blend with no `comp_group_idx`/
21775 // `compound_idx` read (libaom `decodemv.c` 1604-1619, 1382-1384, 1509).
21776 skip_mode_present: bool,
21777 skip_mode_frame: [u8; 2],
21778 // lane-motionmode round 1: this frame header's own `is_motion_mode_switchable`/
21779 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`).
21780 switchable_motion_mode: bool,
21781 allow_warped_motion: bool,
21782 // lane-warp r5: set by the HORZ_B arm -- the 32x16 top strip is decoded
21783 // as a square 32x32 block, which over-reads a residual unless coded
21784 // `skip`; a non-skip strip must refuse cleanly instead of desyncing.
21785 reject_residual: bool,
21786 // lane-partitions r1: the strip's own true width/height in pixels --
21787 // `side` keeps governing every syntax/CDF/prediction-buffer decision
21788 // (matching `HORZ_B`'s already-accepted square-context corner-cut), but
21789 // the final pixel write and this block's own neighbour-context stamp
21790 // (`record*`/`fill_*_grid`) use `write_w`/`write_h` instead, so a
21791 // PARTITION_HORZ/VERT strip only claims its own true footprint. `side`
21792 // for every existing (square) caller.
21793 write_w: usize,
21794 write_h: usize,
21795 // lane-screen r2: this frame header's own `allow_screen_content_tools`
21796 // bit, threaded to the intra-sub-block branch below -- libaom's
21797 // `read_intra_block_mode_info` (decodemv.c:1065-1107, the inter-frame
21798 // counterpart of `read_intra_frame_mode_info`) reads `y_mode_cdf`
21799 // (never `kf_y_mode_cdf`) and has NO `use_intrabc` call at all (that
21800 // symbol is intra-frame-only, spec `av1_read_mode_info` dispatches on
21801 // `frame_is_intra_only`), but it still calls `read_palette_mode_info`
21802 // under the same `av1_allow_palette` gate as the key-frame path.
21803 allow_screen_content_tools: bool,
21804 // lane-superres r9: this frame's own coded luma width (spec 7.11.3.3) --
21805 // compared against each reference's stored picture width to decide
21806 // whether a scaled-MC path (`mc::predict_scaled`) or the ordinary
21807 // stride-1 one (`mc::predict_with_filters`) applies per reference, and to
21808 // refuse (rather than mis-decode) the warp/OBMC/interintra/compound
21809 // combinations that don't implement scaled MC yet.
21810 frame_width: usize,
21811) -> Result<()> {
21812 // lane-inter4 r1: `at` is in MI units (4 px) so a 32-level 1:4 strip can
21813 // name an 8-px offset; `(r, c)` stays the enclosing 16-px cell for the
21814 // few 16-px-granular uses below.
21815 let (r, c) = (at.0 / (SUB / MI), at.1 / (SUB / MI));
21816 // lane-inter8 r2: the inter side bands are mi-granular; this block's own
21817 // above/left neighbour is the mi cell at its top-left corner (libaom
21818 // `above_mbmi` = mi(mi_row - 1, mi_col)), so a SUB-aligned block reads
21819 // exactly what it read before.
21820 let (rmi, cmi) = at;
21821 let (px, py) = (at.1 * MI, at.0 * MI);
21822 census_inter_block_shape(side, write_w, write_h);
21823 // lane-inter16ab r2: a 16x4 / 4x16 inter strip's chroma is the PAIR's
21824 // (8x4 / 4x8 at the even strip's origin) and is coded only by the odd
21825 // strip (`is_chroma_reference`); every other block keeps its own.
21826 let strip_chroma = INTER_STRIP_CHROMA.with(std::cell::Cell::take);
21827 INTER_LAST_MC.with(|c| c.set(None));
21828 let has_chroma = strip_chroma.is_none_or(|s| s.has_chroma);
21829 let (cpx, cpy) = match strip_chroma {
21830 Some(s) if s.has_chroma => (s.pair_mi.1 * MI / 2, s.pair_mi.0 * MI / 2),
21831 _ => (px / 2, py / 2),
21832 };
21833 let chroma_side = side / 2;
21834 let (write_chroma_w, write_chroma_h) = match strip_chroma {
21835 Some(s) if s.has_chroma => {
21836 if s.horz {
21837 (8, 4)
21838 } else {
21839 (4, 8)
21840 }
21841 }
21842 _ => (write_w / 2, write_h / 2),
21843 };
21844 // lane-midcut r3 (same rule as lane-t900 r5's `warp_plane_allowed`, one
21845 // copy kept at the merge): `av1_init_warp_params` (libaom reconinter.c)
21846 // bails per PLANE at `block_width < 8 || block_height < 8` -- on the
21847 // block's own dims, never on the square prediction buffer this reader
21848 // allocates.
21849 if crate::envflags::env_flag!("EC_MC_TRACE") {
21850 eprintln!("EC_IB px={px} py={py} side={side} w={write_w} h={write_h}");
21851 }
21852
21853 if crate::envflags::env_flag!("EC_AV1_TELL") {
21854 eprintln!(
21855 "TELL mi_row={} mi_col={} label=block_entry side={side} tell={} range={}",
21856 rmi, cmi, dec.debug_bitpos(), dec.debug_state().0
21857 );
21858 }
21859 let skip_mode_ctx =
21860 usize::from(neighbours.above_skip_mode[cmi]) + usize::from(neighbours.left_skip_mode[rmi]);
21861 // lane-comppin r3: skip_mode desync isolation -- dump ctx + the pre-read
21862 // MSAC tell so it can be diffed against an equivalent hook in libaom's
21863 // own `read_skip_mode`/`av1_get_skip_mode_context`.
21864 if crate::envflags::env_flag!("EC_AV1_SKIPMODE_DUMP") {
21865 eprintln!(
21866 "EC_SKIPMODE r={r} c={c} ctx={skip_mode_ctx} skip_mode_present={skip_mode_present} tell_before={}",
21867 dec.debug_bitpos()
21868 );
21869 }
21870 // spec 5.11.5 `inter_frame_mode_info`: `inter_segment_id(1)` before
21871 // `skip_mode`/`skip`, `inter_segment_id(0)` after them.
21872 let (seg_mi_r, seg_mi_c) = (rmi, cmi);
21873 let (seg_w_mi, seg_h_mi) = (write_w / 4, write_h / 4);
21874 inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, false, true);
21875 // libaom `read_skip_mode` (decodemv.c): `if (!is_comp_ref_allowed(bsize))
21876 // return 0` -- a 16x4 / 4x16 strip (min(bw, bh) == 4, blockd.h:65) reads
21877 // no `skip_mode` symbol at all.
21878 let comp_allowed = write_w.min(write_h) >= 8;
21879 let skip_mode =
21880 skip_mode_present && comp_allowed && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
21881 if crate::envflags::env_flag!("EC_AV1_SKIPMODE_DUMP") {
21882 eprintln!(
21883 "EC_SKIPMODE r={r} c={c} result={skip_mode} tell_after={}",
21884 dec.debug_bitpos()
21885 );
21886 }
21887 if skip_mode {
21888 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
21889 }
21890
21891 let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]);
21892 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
21893 inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, skip, false);
21894 maybe_read_cdef_idx(dec, rmi, cmi, skip);
21895 // lane-inter4 r1: spec 5.11.6's `bSize == sbSize` -- a 64x32/64x16 strip
21896 // is NOT the whole superblock, so its `skip` never suppresses the read.
21897 // lane-sb128c r7: `sbSize` is 128 under `--sb-size=128`, so the whole-block
21898 // test is against the sequence's own superblock side, not a hardcoded 64.
21899 let sb_px = sb_mi_cur() as usize * 4;
21900 let whole_sb = side == sb_px && write_w == sb_px && write_h == sb_px;
21901 maybe_read_delta_q(dec, cdfs, rmi, cmi, whole_sb, skip);
21902 maybe_read_delta_lf(dec, cdfs, rmi, cmi, whole_sb, skip);
21903 let (has_above, has_left) = (
21904 rmi > neighbours.tile_row0_mi,
21905 cmi > neighbours.tile_col0_mi,
21906 );
21907 let (above_inter, left_inter) = (neighbours.above_inter[cmi], neighbours.left_inter[rmi]);
21908 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
21909 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
21910 // lane-sb128c r1: this round wires the INTER half of a 128x128 block (four
21911 // TX_64X64 luma units and four TX_32X32 chroma units interleaved per mu
21912 // chunk). An INTRA block at that size inside an inter frame takes the
21913 // intra tail below, which still codes one whole-block chroma unit and one
21914 // `read_tx_size` at 128 -- refuse by name instead of mis-decoding it.
21915 if crate::envflags::env_flag!("EC_TRACE_MODE") {
21916 eprintln!(
21917 "EC_MODE mi_row={} mi_col={} rng={} is_inter={} skip={} side={side}",
21918 rmi,
21919 cmi,
21920 dec.debug_state().0,
21921 u8::from(is_inter),
21922 u8::from(skip)
21923 );
21924 }
21925 // lane-warp r5: see `reject_residual` -- a square-block decode of a
21926 // HORZ_B strip is symbol-exact only for `skip` (no residual, no
21927 // motion_mode/warp symbol). lane-intrarect r1 MOVED this gate from just
21928 // after the `skip` read to here, past `is_inter` (class
21929 // [[refusal-short-circuits-its-own-code]]: at the old place it refused
21930 // 24/24 attempts of this lane's own gate before the intra arm below
21931 // could run). An INTRA strip with its true `write_w`x`write_h` footprint
21932 // now codes its residual rectangularly ([`decode_intra_rect_in_inter`]);
21933 // an INTER one, and a strip decoded with square dimensions anyway, still
21934 // cannot.
21935 // merge b51719f+lane-intrarect: main's `rect_inter_residual_supported`
21936 // term stays -- lane-inter4's 16x8/8x16 inter leaves DO code a
21937 // rectangular residual, and the lane's condition (written before that
21938 // landed) refused every one of them.
21939 if reject_residual
21940 && !skip
21941 && !rect_inter_residual_supported(write_w, write_h)
21942 && (is_inter || (write_w == side && write_h == side))
21943 {
21944 if crate::envflags::env_flag!("EC_RECTRES") {
21945 eprintln!(
21946 "EC_RECTRES w={write_w} h={write_h} side={side} skip={} is_inter={} mi_row={rmi} mi_col={cmi}",
21947 u8::from(skip),
21948 u8::from(is_inter)
21949 );
21950 }
21951 return Err(unsupported(
21952 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
21953 ));
21954 }
21955 if crate::envflags::env_flag!("EC_AV1_TELL") {
21956 eprintln!(
21957 "TELL mi_row={} mi_col={} label=post_is_inter skip_mode={skip_mode} skip={skip} is_inter={is_inter} tell={} range={}",
21958 rmi, cmi, dec.debug_bitpos(), dec.debug_state().0
21959 );
21960 }
21961
21962 let mode_for_tx;
21963 let uv_predict_mode;
21964 let (luma_grid, u_grid, v_grid);
21965 let block_filter;
21966 let ref_frame_for_lf;
21967 let globalmv_for_lf;
21968 // lane-av1comp: `Some((comp_group_idx, compound_idx))` only for a real
21969 // `COMPOUND_REFERENCE` block -- applied to `neighbours` *after* the
21970 // common `record_inter` call below (which would otherwise stamp the
21971 // single-ref ALTREF-special-case default over it).
21972 let mut compound_ctx: Option<(i8, u8, u8)> = None;
21973 // lane-txselect: `read_block_tx_size`'s leaf transform units (spec
21974 // 5.11.17), `Some` only when this block's var-tx tree resolved to more
21975 // than one luma transform -- read back by the residual loop, the
21976 // coefficient-context write-back and the loop-filter grid fill below.
21977 let mut vartx_leaves: Option<Vec<(usize, usize, usize, usize)>> = None;
21978 // lane-t900 r22: this block's own palette state, stamped into the
21979 // mi-granular neighbour bands at the tail below for EVERY block --
21980 // libaom's `MB_MODE_INFO.palette_size` is 0 on an inter block, and
21981 // `av1_get_palette_cache`/`av1_get_palette_mode_ctx` read those cells, so
21982 // leaving a previous palette block's colours standing here would feed the
21983 // next intra block a cache libaom never builds.
21984 let mut palette_record: (usize, [u16; 8], usize, [u16; 8]) = (0, [0u16; 8], 0, [0u16; 8]);
21985 let at_mi = at;
21986 // lane-vert46 r1: set when this block's chroma was coded as one 32x32 unit
21987 // per 64x64 "mu" chunk (any side above 64), so the end-of-block record
21988 // below must NOT re-stamp the chroma neighbour context from the assembled
21989 // whole-block grid.
21990 let mut mu_chroma = false;
21991 if is_inter {
21992 let above_nbr = has_above.then(|| NeighbourRef {
21993 is_inter: above_inter,
21994 ref0: if above_inter {
21995 neighbours.above_ref[cmi]
21996 } else {
21997 0
21998 },
21999 ref1: neighbours.above_ref1[cmi],
22000 uni: neighbours.above_ref1[cmi]
22001 .is_some_and(|r1| is_uni_comp_ref(neighbours.above_ref[cmi], r1)),
22002 });
22003 let left_nbr = has_left.then(|| NeighbourRef {
22004 is_inter: left_inter,
22005 ref0: if left_inter {
22006 neighbours.left_ref[rmi]
22007 } else {
22008 0
22009 },
22010 ref1: neighbours.left_ref1[rmi],
22011 uni: neighbours.left_ref1[rmi]
22012 .is_some_and(|r1| is_uni_comp_ref(neighbours.left_ref[rmi], r1)),
22013 });
22014 if crate::envflags::env_flag!("EC_AV1_COMPIDX_DUMP") {
22015 eprintln!(
22016 "EC_PRECOMP r={r} c={c} skip_mode={skip_mode} skip={skip} reference_select={reference_select} tell={}",
22017 dec.debug_bitpos()
22018 );
22019 }
22020 let is_compound =
22021 skip_mode
22022 || (reference_select
22023 // `is_comp_ref_allowed` (blockd.h:65) gates the
22024 // `comp_mode` read exactly as it gates `skip_mode`.
22025 && comp_allowed
22026 && read_comp_mode(dec, cdfs, above_nbr, left_nbr));
22027 if is_compound {
22028 let (ref0, ref1) = if skip_mode {
22029 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
22030 } else {
22031 read_compound_ref_frames(
22032 dec,
22033 cdfs,
22034 above_nbr,
22035 left_nbr,
22036 neighbours.above_ref[cmi],
22037 neighbours.left_ref[rmi],
22038 )
22039 };
22040 let (mi_row, mi_col) = (rmi, cmi);
22041 // lane-rect r2: true footprint, mirroring the single-ref path below.
22042 let bw4 = write_w / 4;
22043 let bh4 = write_h / 4;
22044 // spec 7.10.2.8, doubled per side (`CompoundTplArgs`): same
22045 // `use_ref_frame_mvs` gating as the single-ref `tpl` build
22046 // below, just one `get_relative_dist` per reference.
22047 let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs {
22048 field: t.field,
22049 cur_offset_0: crate::motion_field::get_relative_dist(
22050 t.order_hint_bits,
22051 t.order_hint,
22052 t.ref_order_hints[(ref0 - LAST_FRAME) as usize],
22053 ),
22054 cur_offset_1: crate::motion_field::get_relative_dist(
22055 t.order_hint_bits,
22056 t.order_hint,
22057 t.ref_order_hints[(ref1 - LAST_FRAME) as usize],
22058 ),
22059 allow_high_precision_mv,
22060 });
22061 let gm_table = build_gm_mv_table(
22062 global_motion,
22063 mi_row,
22064 mi_col,
22065 bw4,
22066 bh4,
22067 allow_high_precision_mv,
22068 force_integer_mv,
22069 );
22070 let comp_stack = crate::mvstack::find_mv_stack_compound(
22071 grid,
22072 mi_row,
22073 mi_col,
22074 bw4,
22075 bh4,
22076 (ref0, ref1),
22077 mi_cols as usize,
22078 mi_rows as usize,
22079 sign_bias_table,
22080 &gm_table,
22081 comp_tpl,
22082 );
22083 let compound_mode = if skip_mode {
22084 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
22085 } else {
22086 read_inter_compound_mode(dec, cdfs, comp_stack.new_mv_ctx, comp_stack.ref_mv_ctx)
22087 };
22088 let (mv0, mv1) = assign_compound_mv(
22089 dec,
22090 cdfs,
22091 &comp_stack,
22092 compound_mode,
22093 allow_high_precision_mv,
22094 force_integer_mv,
22095 (gm_table[(ref0 - LAST_FRAME) as usize], gm_table[(ref1 - LAST_FRAME) as usize]),
22096 );
22097 if crate::envflags::env_flag!("EC_TRACE_MODE") {
22098 eprintln!(
22099 "EC_MODE_VAL mi_row={mi_row} mi_col={mi_col} mode={} ref0={ref0} ref1={ref1} mv0=({},{}) stack={} rng={}",
22100 compound_mode + 17,
22101 mv0.0,
22102 mv0.1,
22103 comp_stack.entries.len(),
22104 dec.debug_state().0
22105 );
22106 for (i, e) in comp_stack.entries.iter().enumerate() {
22107 eprintln!(
22108 "EC_STACK mi_row={mi_row} mi_col={mi_col} i={i} this=({},{}) comp=({},{}) w={}",
22109 e.mv0.0, e.mv0.1, e.mv1.0, e.mv1.1, e.weight
22110 );
22111 }
22112 }
22113 let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV
22114 // spec `is_nontrans_global_motion`: ALL active refs' models must
22115 // be non-TRANSLATION (IDENTITY counts) for the compound block's
22116 // interp-filter read to be suppressed.
22117 let gm_nontrans_models = is_globalmv
22118 && global_motion[(ref0 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation
22119 && global_motion[(ref1 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation;
22120 // lane-t900 r9: `is_nontrans_global_motion` bails at
22121 // `AOMMIN(mi_size_wide, mi_size_high) < 2` before it looks at any
22122 // model, so a 4-px-sided block still reads its interp filter.
22123 let gm_nontrans = gm_nontrans_models && bw4.min(bh4) >= 2;
22124 if gm_nontrans_models && !gm_nontrans {
22125 GM_NONTRANS_SMALL_SIDE_HITS.with(|c| c.set(c.get() + 1));
22126 }
22127 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
22128 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
22129 // lane-cwarp r1: `is_global_mv_block` (blockd.h:421-429) is
22130 // PER REFERENCE SLOT -- mode GLOBAL_GLOBALMV, block >= 8x8, and
22131 // THAT slot's own gm model > TRANSLATION. `bw4`/`bh4` come from
22132 // the write extent below, so recompute the size bound from
22133 // `side` here (the block's own size, what libaom's `bsize`
22134 // is).
22135 let is_global_mv0 = is_globalmv
22136 && side >= 8
22137 && global_motion[(ref0 - LAST_FRAME) as usize].model as u8 > 1;
22138 let is_global_mv1 = is_globalmv
22139 && side >= 8
22140 && global_motion[(ref1 - LAST_FRAME) as usize].model as u8 > 1;
22141 // libaom `av1_init_warp_params` + `allow_warp`'s
22142 // `global_warp_allowed` branch, run once per reference for a
22143 // compound block exactly as for a single-ref one (reconinter.c
22144 // `build_inter_predictors_8x8_and_bigger` loops over `ref` and
22145 // calls `av1_init_warp_params` inside the loop) -- WARPED_CAUSAL
22146 // never reaches here (spec 5.11.27 / libaom `read_motion_mode`:
22147 // `has_second_ref` returns SIMPLE_TRANSLATION), so the local-warp
22148 // arm of `allow_warp` is dead on this path and only the global
22149 // one applies. `force_integer_mv` short-circuits
22150 // `av1_init_warp_params` before `allow_warp`.
22151 let compound_warp = |ref_frame: i8, eligible: bool| {
22152 if eligible
22153 && !force_integer_mv
22154 && !global_motion[(ref_frame - LAST_FRAME) as usize].invalid
22155 {
22156 crate::warp::global_warp_params(
22157 global_motion[(ref_frame - LAST_FRAME) as usize].params,
22158 )
22159 } else {
22160 None
22161 }
22162 };
22163 // lane-t900 r28 (class branch-dropped-as-unreachable, swept out
22164 // of the scaled-ref lift): libaom `allow_warp`
22165 // (av1/common/reconinter.c:41) opens with `if (av1_is_scaled(sf))
22166 // return 0;` PER SLOT, so a compound tap whose own reference is
22167 // scaled (superres) is predicted translationally while its
22168 // sibling may still warp.
22169 let ref_unscaled = |rf: i8| {
22170 ref_planes(rf, ref_y, ref_u, ref_v, other_refs)
22171 .is_ok_and(|(py, _, _)| {
22172 mc::scale_factor(py.width, frame_width) == mc::REF_NO_SCALE
22173 })
22174 };
22175 let warp0 = compound_warp(ref0, is_global_mv0).filter(|_| ref_unscaled(ref0));
22176 let warp1 = compound_warp(ref1, is_global_mv1).filter(|_| ref_unscaled(ref1));
22177 if warp0.is_some() || warp1.is_some() {
22178 COMPOUND_WARP_HITS.with(|c| c.set(c.get() + 1));
22179 }
22180 // spec `get_ref_filter_type`: matches when EITHER of the
22181 // neighbour's two references equals this block's own ref0 --
22182 // `above_ref1`/`left_ref1` is the neighbour's real second
22183 // reference (`record_compound_ctx`) when it was itself a
22184 // compound block; checking `above_ref`/`left_ref` alone drops a
22185 // real filter match down to the "no neighbour" sentinel
22186 // whenever the shared reference sits in the neighbour's SECOND
22187 // slot (lane-av1idx r2).
22188 let above_filter_ctx = if neighbours.above_ref[cmi] == ref0
22189 || neighbours.above_ref1[cmi] == Some(ref0)
22190 {
22191 neighbours.above_filter[cmi]
22192 } else {
22193 [3, 3]
22194 };
22195 let left_filter_ctx = if neighbours.left_ref[rmi] == ref0
22196 || neighbours.left_ref1[rmi] == Some(ref0)
22197 {
22198 neighbours.left_filter[rmi]
22199 } else {
22200 [3, 3]
22201 };
22202 globalmv_for_lf = is_globalmv;
22203 ref_frame_for_lf = ref0;
22204 mode_for_tx = 0;
22205 uv_predict_mode = DC_PRED;
22206 // lane-rect r2: `grid` (mvstack.rs's own MiGrid, distinct from
22207 // `neighbours`) must be stamped with the block's true footprint
22208 // too -- a square `bw4`x`bw4` stamp here claims a rect strip's
22209 // NEXT strip's own rows/cols before it decodes, corrupting
22210 // every later mvstack scan that reads this cell back.
22211 for dr in 0..bh4 {
22212 for dc in 0..bw4 {
22213 grid.set(
22214 mi_row + dr,
22215 mi_col + dc,
22216 MiInfo {
22217 is_inter: true,
22218 ref_frame: ref0,
22219 ref_frame1: Some(ref1),
22220 mv1: Some(mv1),
22221 mv: mv0,
22222 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
22223 size: bw4,
22224 size_h: bh4,
22225 // libaom `is_global_mv_block`: per-ref-slot, mode
22226 // GLOBAL_GLOBALMV, block >= 8x8, and THAT slot's
22227 // own gm model > TRANSLATION (IDENTITY excluded
22228 // too -- the two-predicate trap, distinct from
22229 // `gm_nontrans` above which allows IDENTITY).
22230 is_global_mv0,
22231 is_global_mv1,
22232 },
22233 );
22234 }
22235 }
22236 // spec 5.11.25's `comp_group_idx`/`compound_idx`: only read when
22237 // masked compound / distance-weighted compound are actually
22238 // enabled for this stream -- `is_any_masked_compound_used_here`
22239 // is `true` for every block size this decoder ever reaches
22240 // (`min(side,side) >= 8`, `COMPOUND_DIFFWTD` always eligible
22241 // there), so the gate reduces to the sequence header bit; kept
22242 // as an explicit call so a future smaller block size is not
22243 // silently wrong (libaom `reconinter.h::is_any_masked_compound_used`).
22244 let group_ctx = get_comp_group_idx_context(neighbours, (rmi, cmi), side);
22245 let comp_group_idx = if !skip_mode
22246 && enable_masked_compound
22247 && is_any_masked_compound_used_here(write_w, write_h)
22248 {
22249 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
22250 } else {
22251 0
22252 };
22253 if crate::envflags::env_flag!("EC_TRACE_MODE") {
22254 eprintln!(
22255 "EC_CGI mi_row={rmi} mi_col={cmi} ctx={group_ctx} val={comp_group_idx} rng={}",
22256 dec.debug_state().0
22257 );
22258 }
22259 // lane-maskcomp r2 / lane-wedge r3: `Some(mask_type)` for a
22260 // `COMPOUND_DIFFWTD` block, `Some(mask)` (wedge codebook lookup)
22261 // for a `COMPOUND_WEDGE` block -- exactly one of the two is set
22262 // when `comp_group_idx == 1`.
22263 let mut diffwtd_mask_type: Option<u8> = None;
22264 let mut wedge_mask: Option<&'static [u8]> = None;
22265 if comp_group_idx == 1 {
22266 // lane-maskcomp r1: `read_compound_type` (spec 5.11.25,
22267 // libaom `decodemv.c` 1634-1656). `is_interinter_compound_used
22268 // (COMPOUND_WEDGE, bsize)` (`av1_is_wedge_used`,
22269 // `av1_wedge_params_lookup`) is true for every square bsize
22270 // this leaf reaches (8x8/16x16/32x32 all have
22271 // `wedge_types > 0`), so `compound_type` always reads a real
22272 // symbol here -- no alphabet collapse to worry about at this
22273 // block-size family.
22274 // lane-mcomp64 r1: `av1_is_wedge_used` is false at 64x64
22275 // (`av1_wedge_params_lookup[BLOCK_64X64].wedge_types == 0`),
22276 // so libaom's `read_compound_type` (decodemv.c 1634-1656)
22277 // writes NO `compound_type` symbol there and INFERS
22278 // `COMPOUND_DIFFWTD` -- only the 1-bit `mask_type` literal
22279 // follows. `None` here is exactly that inferred arm.
22280 // lane-inter16ab r3: the row is this block's TRUE
22281 // `BLOCK_SIZES_ALL` index, not the enclosing square `side`'s
22282 // -- a 16x8 strip reads `compound_type_cdf[BLOCK_16X8]`.
22283 let wedge_bsize =
22284 bsize_all_index(write_w, write_h).filter(|_| wedge_used_bsize(write_w, write_h));
22285 let compound_type = match wedge_bsize {
22286 Some(b) => dec.symbol(&mut cdfs.compound_type[b]),
22287 None => 1,
22288 };
22289 if let Some(wedge_bsize) = wedge_bsize.filter(|_| compound_type == 0) {
22290 // COMPOUND_WEDGE: lane-wedge r3, codebook checksum-
22291 // verified vs independent C dump (wedge.rs).
22292 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
22293 let wedge_sign = dec.literal(1);
22294 WEDGE_HITS.with(|c| c.set(c.get() + 1));
22295 if let Some(k) = rect_wedge_slot(write_w, write_h) {
22296 RECT_WEDGE_HITS.with(|c| {
22297 let mut a = c.get();
22298 a[k] += 1;
22299 c.set(a);
22300 });
22301 }
22302 // lane-inter16ab r5: the codebook row is this block's TRUE
22303 // footprint (`av1_wedge_params_lookup[bsize]`: hgtw for
22304 // h>w, hltw for h<w, plus that bsize's own signflip row).
22305 // Masks are padded to stride `max(bw,bh) == side`, so the
22306 // square blend below indexes them unchanged and the
22307 // padding never reaches the frame (only `write_w x
22308 // write_h` is written out).
22309 wedge_mask = Some(
22310 crate::wedge::wedge_masks()
22311 .codebook(write_w, write_h)
22312 .mask(wedge_sign as usize, wedge_index as usize),
22313 );
22314 } else {
22315 // COMPOUND_DIFFWTD: `mask_type`, MAX_DIFFWTD_MASK_BITS==1.
22316 let mask_type = dec.literal(1);
22317 diffwtd_mask_type = Some(mask_type as u8);
22318 if wedge_bsize.is_none() {
22319 DIFFWTD_INFERRED_HITS.with(|c| c.set(c.get() + 1));
22320 }
22321 }
22322 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
22323 if write_w != write_h {
22324 RECT_MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
22325 }
22326 }
22327 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): r16/r17
22328 // called this a `predict_compound_intermediate`/`combine_compound`
22329 // reconstruction defect. r1 FALSIFIED that hypothesis outright:
22330 // unmasking and running the real gates
22331 // (a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly,
22332 // a_real_aomenc_stream_with_compound_references_decodes_pixel_exact)
22333 // shows the plain-average blend is bit-exact *most of the time*
22334 // -- `combine_compound`'s two-shift-in-one round2 was proven
22335 // algebraically identical to libaom's separate
22336 // `>>DIST_PRECISION_BITS`-then-`ROUND_POWER_OF_TWO` sequence
22337 // (av1_dist_wtd_convolve_2d_c, convolve.c:402-415) for every
22338 // input, and a whole-pel zero-MV compound block (mv0=mv1=(0,0),
22339 // the common case a lag-in-frames GOP's hidden altref frames
22340 // hit) reproduces aomdec's own pre-deblock dump byte-for-byte
22341 // for several consecutive frames.
22342 //
22343 // The real defect a live gate run isolated (seed 49,
22344 // `fixtures/av1blend-r1-mismatch.obu`): decode-order frame 0
22345 // (keyframe) and frame 1 (first hidden altref, `ref1 ==
22346 // ALTREF_FRAME`) match aomdec's own pre-deblock dump byte for
22347 // byte; decode-order frame 2 -- same shape, same zero MV, only
22348 // difference `ref1 == BWDREF_FRAME` instead of `ALTREF_FRAME` --
22349 // is the *first* frame to diverge (881/6144 luma+chroma bytes).
22350 // Every later frame up through decode-order 9 also mismatches,
22351 // *including* frame 8, whose four blocks are back to
22352 // `ref1 == ALTREF_FRAME` only -- ruling out "BWDREF_FRAME's MC
22353 // math is wrong" (that block's own math is proven exact) in
22354 // favour of "the picture sitting in some DPB slot is already
22355 // wrong by the time frame 2 reads it, and the corruption
22356 // propagates through refresh_frame_flags into every later
22357 // reference regardless of which named ref a later block picks".
22358 // Frames 10 through 18 (once the GOP's lineage stops tracing
22359 // back through the bad slot) are bit-exact again. This points at
22360 // reference-slot bookkeeping (`ref_slots`/`refresh_frame_flags`
22361 // in `stream.rs`'s `decode_stream`, or `ref_order_hints`/DPB
22362 // indexing feeding `dist_wtd_comp_weight_assign`) around
22363 // BWDREF_FRAME specifically, not at the MC/blend arithmetic in
22364 // mc.rs. Not isolated further within lane-av1blend's budget --
22365 // refuse by name rather than ship a blend that is right only
22366 // sometimes. Ceiling: r13/r14's MC plumbing above this line
22367 // stays -- only the plain-average reconstruct is masked off
22368 // again. Upgrade: instrument `ref_slots`/`refresh_frame_flags`
22369 // per decode-order frame (which slot each `Frame` OBU refreshes,
22370 // and which slot each `ref_frame_idx[BWDREF_FRAME - LAST_FRAME]`
22371 // reads) against aomdec's own `RefCntBuffer` bookkeeping on
22372 // `fixtures/av1blend-r1-mismatch.obu`, starting at decode-order
22373 // frame 2.
22374 //
22375 // r2 (fresh fixture, seed 45, same recipe -- the original r1
22376 // fixture is gitignored and could not be regenerated byte-exact):
22377 // static review of `stream.rs`'s `ref_slots`/`refresh_frame_flags`/
22378 // `cdf_slots` bookkeeping and the `show_existing_frame` refresh
22379 // arm (spec 7.21: only refreshes on a shown KEY frame, which the
22380 // parser already enforces at `frame.rs:791/815` -- `refresh_frame_flags`
22381 // is forced 0 on every non-key `show_existing_frame`) turned up
22382 // nothing wrong; `other_refs`/`ref_planes` slot indexing for
22383 // `BWDREF_FRAME` is spec-correct too. A live unmasked run
22384 // isolated a *different, smaller* shape than r1's: decode-order
22385 // frame 3 (a `ref1 == BWDREF_FRAME`, zero-MV, simple-average
22386 // compound block) is the first to diverge from ffmpeg (worst
22387 // delta 1, luma only, clustered at 32-pixel block edges) even
22388 // though BOTH its compound inputs -- the key frame and
22389 // decode-order frame 2's own picture (`ref1 == ALTREF_FRAME`,
22390 // itself proven bit-exact: it is later re-shown via
22391 // `show_existing_frame` and matches ffmpeg exactly) -- are
22392 // independently pixel-exact, and the blend arithmetic is the
22393 // same proven-exact formula. That rules out "wrong slot"/"stale
22394 // picture" for this fixture: the inputs are right, so the defect
22395 // is in decode-order frame 3's *own* per-block decode (entropy
22396 // desync from compound-CDF adaptation carried across a slot, or
22397 // the compound mode/MV read itself) -- not in `ref_slots`/
22398 // `refresh_frame_flags`. Not isolated further within budget.
22399 // Upgrade: bisect decode-order frame 3's tile decode against a
22400 // synced `EC_TOK`/`EC_PART` trace from the instrumented aomdec
22401 // build (`/tmp/libaom-src/build/decoder-debug/aomdec`) on
22402 // `fixtures/av1blend-r1-mismatch.obu` (seed 45 now, not seed 49)
22403 // -- the pre-deblock dump frame-index alignment between this
22404 // crate and that aomdec build is NOT 1:1 on this fixture (23
22405 // dumps here vs 24 there), so calibrate that first.
22406 // r3 (this round): pre-deblock buffers were bisected byte-for-byte
22407 // against an instrumented aomdec build (frame-index alignment
22408 // recalibrated via content-hash matching rather than the raw
22409 // dump count -- the keyframe never calls a pre-deblock dump at
22410 // all, since only `decode_inter_frame_tile` does, which is the
22411 // whole "23 vs 24" gap, not a real bug).
22412 // Decode-order frame 3 (`fixtures/av1blend-r1-mismatch.obu`,
22413 // seed 45) is still the first divergence: PRE-deblock differs
22414 // from aomdec's own pre-deblock dump by up to 1, on ~20% of
22415 // luma pixels, clustered where its two compound inputs' pixel
22416 // values disagree by more than a couple of levels -- both
22417 // inputs (the keyframe and decode-order frame 2's own picture)
22418 // are independently proven bit-exact (pre- and post-deblock)
22419 // against aomdec, and `decodemv`'s own EC_TRACE (mode/mv/skip)
22420 // matches this decoder's block loop exactly for every block in
22421 // this frame. Solving `aomval = (key*w0 + bwd*w1 + 8) >> 4` for
22422 // every mismatching pixel against `key`/`bwd` (both known-exact)
22423 // picks out `w0=9, w1=7` for the majority (525/846) with zero
22424 // matches for the plain average this decoder actually emits or
22425 // the reversed `w0=7, w1=9` -- i.e. `compound_idx` is being
22426 // decoded as `1` (simple average, spec `COMPOUND_AVERAGE`) when
22427 // the real bitstream encoded `0` (`COMPOUND_DISTWTD`,
22428 // `dist_wtd_comp_weight_assign`'s own weights for this frame's
22429 // order-hint distances 2/3 land on exactly `(9, 7)` -- this
22430 // decoder's own `dist_wtd_comp_weight_assign` was independently
22431 // re-verified against `QUANT_DIST_WEIGHT`/`QUANT_DIST_LOOKUP_TABLE`
22432 // by hand for these distances and gives the same `(9, 7)`).
22433 // `get_comp_index_context` was checked line-for-line against
22434 // libaom's `pred_common.h` (the `fwd`/`bck` distance halves, the
22435 // `above_mi`/`left_mi` `has_second_ref`/`ALTREF_FRAME` fallback,
22436 // the `3 * offset` term) and matches; `Default_Compound_Idx_Cdf`
22437 // (`cdf.rs`'s `COMPOUND_IDX`) matches `entropymode.c`'s
22438 // `default_compound_idx_cdfs` value-for-value; the read is
22439 // gated on `!skip_mode && enable_jnt_comp`, matching libaom's
22440 // `has_second_ref(mbmi) && !mbmi->skip_mode` outer guard plus
22441 // `order_hint_info.enable_dist_wtd_comp` inner guard. The
22442 // remaining 321/846 mismatched pixels do NOT fit `(9, 7)`
22443 // either -- some blocks in this frame plausibly decode a
22444 // genuinely different (correct, context-dependent) compound_idx
22445 // than block (0,0)'s own -- so this is not simply "always wrong
22446 // the same way": table/context/gate are all individually
22447 // verified correct, yet the decoded VALUE at this specific
22448 // symbol is wrong at least once in this frame. Not isolated
22449 // further within budget. Upgrade: instrument `dec.symbol`'s own
22450 // range/bit state (`rng`/`tell`, matching aomdec's own EC_PART
22451 // trace fields) immediately before and after the `compound_idx`
22452 // read specifically, not just the surrounding mode/mv/skip
22453 // trace which does match -- the desync (if any) is local to
22454 // this one read, not a wider stream desync.
22455 //
22456 // r5 (this round): the `resolve_interp_filter` call used to sit
22457 // right here, ahead of `comp_group_idx`/`compound_idx` -- spec
22458 // 5.11.19/libaom `decodemv.c:1575` reads `interp_filter` AFTER
22459 // `read_compound_type`, not before, so that was a genuine
22460 // ordering bug for a Switchable-filter frame (moved below, past
22461 // the `compound_ctx = Some(...)` line). It does NOT explain this
22462 // fixture's own mismatch, though: `av1blend-r1-mismatch.obu`'s
22463 // header carries a *fixed* interpolation filter
22464 // (`interp_fixed = Some(Regular)`, confirmed live via a
22465 // one-off dump), so `resolve_interp_filter` never read a symbol
22466 // in either position -- zero bits moved, decoded values
22467 // unchanged before and after the reorder. Kept anyway: it is a
22468 // real spec-order fix for the next Switchable-filter compound
22469 // stream, independently correct regardless of this fixture.
22470 //
22471 // Also ruled out this round: comparing this crate's own
22472 // `SymbolDecoder::debug_bitpos()` against aomdec's
22473 // `aom_reader_tell()` at the block boundary is NOT a valid
22474 // desync probe -- they are different quantities (raw consumed
22475 // input bits vs. an entropy-cost estimate that advances without
22476 // a literal byte fetch), so equal/unequal bitpos proves nothing
22477 // either way. Do not repeat that comparison; instead trace
22478 // `range`/`value` (this crate) against libaom's own internal
22479 // `dif`/`rng` (needs new instrumentation in both) immediately
22480 // after each read *upstream* of this one in the same block:
22481 // `read_comp_mode`, `read_compound_ref_frames` (comp_ref_type/
22482 // uni_comp_ref/comp_ref/comp_bwdref), `read_inter_compound_mode`,
22483 // and the DRL loop. All of those independently decoded the SAME
22484 // values this crate and aomdec both show (ref0=1, ref1=5, mode
22485 // NEAREST_NEARESTMV, mv=(0,0)) -- but an upstream *context*
22486 // miscomputation can still decode the identical symbol value off
22487 // a slightly different CDF, narrowing `range` by a different
22488 // amount than aomdec without changing the decoded value itself,
22489 // and only surface as a wrong decode a few reads later exactly
22490 // like this. `get_comp_index_context` and the `COMPOUND_IDX`
22491 // table were independently re-verified again this round and are
22492 // still correct; the four candidates above were not re-audited
22493 // this round. Refusing here (rather than shipping a value-exact-
22494 // most-of-the-time blend) until one of them is found wrong.
22495 // r6/r7: found and fixed one real bug (mvstack.rs ref_ctx family
22496 // undercounted compound neighbours in the single_ref_p*/comp_ref*/
22497 // comp_bwdref* context reads -- kept, real fix). Unmasking on
22498 // that fix alone and running the wide gate sweep (many seeds,
22499 // `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`/
22500 // `a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly`,
22501 // cq-level=45) still mismatches roughly half the time, at
22502 // different frames each run for the SAME seed -- aomenc's own
22503 // cpu-used=0 RD search is run-to-run nondeterministic (noted
22504 // above), so this is a second, still-unfound compound_idx defect,
22505 // not the one r6/r7 fixed. r6's own residual-mismatch note (321/
22506 // 846 pixels not fitting the (9,7)-vs-plain-average hypothesis
22507 // either) already flagged more than one bug here. Re-masking:
22508 // do not ship a blend that is right only sometimes.
22509 // lane-av1idx r1: fixed one real bug this round
22510 // (`switchable_interp_ctx` never folded in libaom's
22511 // `INTER_FILTER_COMP_OFFSET` for a compound block's own
22512 // interp_filter context -- kept). Pinned
22513 // `fixtures/av1idx-refsel-pin.obu` (seed 61, reference_select
22514 // gate) still mismatches after that fix (decode-order frame 8
22515 // first, small deltas, worst 1-2, propagating through later
22516 // frames via DPB reference) -- a second, still-unfound bug.
22517 // Re-masking: see that fixture + `scratch_isolate_pinned_mismatch`
22518 // (`EC_AV1_PIN=fixtures/av1idx-refsel-pin.obu EC_AV1_PIN_N=20`)
22519 // for the next round's starting point.
22520 // lane-maskcomp r2: `compound_idx` is only read when
22521 // `comp_group_idx == 0` (libaom `decodemv.c:1606`) -- a masked
22522 // (wedge/diffwtd) block never also carries a distance-weighted
22523 // split. This gate was missing before r2 (dead code: the masked
22524 // path always refused earlier, so it never executed with
22525 // `comp_group_idx == 1` in practice).
22526 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
22527 && !skip_mode
22528 && enable_jnt_comp
22529 {
22530 let idx_ctx = get_comp_index_context(
22531 neighbours,
22532 (rmi, cmi),
22533 side,
22534 order_hint_bits,
22535 order_hint,
22536 ref_order_hints[(ref0 - LAST_FRAME) as usize],
22537 ref_order_hints[(ref1 - LAST_FRAME) as usize],
22538 );
22539 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
22540 if crate::envflags::env_flag!("EC_TRACE_MODE") {
22541 eprintln!(
22542 "EC_CIDX mi_row={rmi} mi_col={cmi} ctx={idx_ctx} val={idx} rng={}",
22543 dec.debug_state().0
22544 );
22545 }
22546 if idx == 1 {
22547 (8, 8, 1u8)
22548 } else {
22549 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
22550 order_hint_bits,
22551 order_hint,
22552 ref_order_hints[(ref0 - LAST_FRAME) as usize],
22553 ref_order_hints[(ref1 - LAST_FRAME) as usize],
22554 );
22555 (fwd, bck, 0u8)
22556 }
22557 } else {
22558 (8, 8, 1u8)
22559 };
22560 compound_ctx = Some((ref1, comp_group_idx as u8, compound_idx));
22561 if crate::envflags::env_flag!("EC_AV1_COMPIDX_DUMP") {
22562 eprintln!(
22563 "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={}",
22564 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
22565 );
22566 }
22567
22568 // spec 5.11.19/libaom `decodemv.c` 1575: `read_mb_interp_filter`
22569 // comes AFTER `read_compound_type` (the `comp_group_idx`/
22570 // `compound_idx` reads just above), not before -- moved here
22571 // (lane-av1blend r5) from its old position ahead of those reads,
22572 // which stole their bits for a Switchable-filter compound block
22573 // and desynced every symbol read after it in the tile.
22574 // `av1_is_interp_needed` is also 0 for `skip_mode` blocks: the
22575 // filter is derived (Regular), never read -- same
22576 // conditional-read contract as the WARPED_CAUSAL suppression on
22577 // the single-ref path below.
22578 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
22579 dec,
22580 cdfs,
22581 interp_fixed,
22582 enable_dual_filter,
22583 gm_nontrans || skip_mode,
22584 above_filter_ctx,
22585 left_filter_ctx,
22586 true,
22587 );
22588 block_filter = resolved_filter;
22589
22590 // lane-scaledref r1: each compound tap scales INDEPENDENTLY off
22591 // its own stored reference's luma width (spec 7.11.3.3 derives
22592 // x_scale_fp per reference; libaom `av1_setup_pre_planes` builds
22593 // one `scale_factors` per `ref_frame`), so the two taps can carry
22594 // different ratios in the same block. `REF_NO_SCALE` reduces
22595 // `predict_compound_intermediate`'s walk to the ordinary
22596 // stride-1 one, so the unscaled case is unchanged.
22597 let scale0 = mc::scale_factor(py0.width, frame_width);
22598 let scale1 = mc::scale_factor(py1.width, frame_width);
22599 if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE {
22600 SCALED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
22601 }
22602 // lane-scaledref r2: the MIXED case -- one tap scaled, the other
22603 // not -- is the one an all-frames-scaled recipe never produces,
22604 // and the one a single shared scale factor would get wrong.
22605 if (scale0 == mc::REF_NO_SCALE) != (scale1 == mc::REF_NO_SCALE) {
22606 MIXED_SCALE_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
22607 }
22608
22609 let mut inter0_y = vec![0i32; side * side];
22610 mc::predict_compound_intermediate_kern(
22611 &py0.data,
22612 py0.width,
22613 py0.true_width,
22614 py0.true_height,
22615 mv_to_q4(px, mv0.1, true),
22616 mv_to_q4(py, mv0.0, true),
22617 scale0,
22618 side,
22619 side,
22620 write_w,
22621 write_h,
22622 h_filter,
22623 v_filter,
22624 &mut inter0_y,
22625 );
22626 // lane-cwarp r1: this reference's own GLOBAL warp replaces the
22627 // translational tap (libaom `av1_warp_plane` with
22628 // `conv_params->is_compound`); the blend below is unchanged.
22629 if let Some(wp) = warp0.as_ref().filter(|_| warp_plane_allowed(write_w, write_h)) {
22630 crate::warp::warp_affine_compound(
22631 wp, &py0.data, py0.true_width as i32, py0.true_height as i32,
22632 py0.width as i32, &mut inter0_y, px as i32, py as i32, side as i32,
22633 side as i32, side as i32, 0, 0,
22634 );
22635 }
22636 let mut inter1_y = vec![0i32; side * side];
22637 mc::predict_compound_intermediate_kern(
22638 &py1.data,
22639 py1.width,
22640 py1.true_width,
22641 py1.true_height,
22642 mv_to_q4(px, mv1.1, true),
22643 mv_to_q4(py, mv1.0, true),
22644 scale1,
22645 side,
22646 side,
22647 write_w,
22648 write_h,
22649 h_filter,
22650 v_filter,
22651 &mut inter1_y,
22652 );
22653 // lane-cwarp r1: this reference's own GLOBAL warp replaces the
22654 // translational tap (libaom `av1_warp_plane` with
22655 // `conv_params->is_compound`); the blend below is unchanged.
22656 if let Some(wp) = warp1.as_ref().filter(|_| warp_plane_allowed(write_w, write_h)) {
22657 crate::warp::warp_affine_compound(
22658 wp, &py1.data, py1.true_width as i32, py1.true_height as i32,
22659 py1.width as i32, &mut inter1_y, px as i32, py as i32, side as i32,
22660 side as i32, side as i32, 0, 0,
22661 );
22662 }
22663 let mut pred_y = vec![0u16; side * side];
22664 let mut diffwtd_mask_y = Vec::new();
22665 // lane-wedge r3: `mask_y` is the DIFFWTD buffer just computed OR
22666 // the wedge codebook lookup (comp_group_idx==1's two mutually
22667 // exclusive branches) -- same [`mc::blend_masked_compound`] call
22668 // either way, only the mask source differs.
22669 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
22670 diffwtd_mask_y = vec![0u8; side * side];
22671 DIFFWTD_HITS.with(|c| c.set(c.get() + 1));
22672 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
22673 Some(diffwtd_mask_y.as_slice())
22674 } else {
22675 wedge_mask
22676 };
22677 if let Some(mask_y) = mask_y {
22678 mc::blend_masked_compound(
22679 &inter0_y, &inter1_y, mask_y, side, side, side, false, &mut pred_y,
22680 );
22681 } else {
22682 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
22683 }
22684
22685 let mut inter0_u = vec![0i32; chroma_side * chroma_side];
22686 mc::predict_compound_intermediate_kern(
22687 &pu0.data,
22688 pu0.width,
22689 pu0.true_width,
22690 pu0.true_height,
22691 mv_to_q4(cpx, mv0.1, false),
22692 mv_to_q4(cpy, mv0.0, false),
22693 scale0,
22694 chroma_side,
22695 chroma_side,
22696 write_chroma_w,
22697 write_chroma_h,
22698 h_filter,
22699 v_filter,
22700 &mut inter0_u,
22701 );
22702 // `av1_init_warp_params` bails when the PLANE's block is
22703 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
22704 // block of an 8x8 luma block stays translational.
22705 if let Some(wp) = &warp0 {
22706 if warp_plane_allowed(write_chroma_w, write_chroma_h) {
22707 crate::warp::warp_affine_compound(
22708 wp, &pu0.data, pu0.true_width as i32, pu0.true_height as i32,
22709 pu0.width as i32, &mut inter0_u, cpx as i32, cpy as i32,
22710 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
22711 );
22712 }
22713 }
22714 let mut inter1_u = vec![0i32; chroma_side * chroma_side];
22715 mc::predict_compound_intermediate_kern(
22716 &pu1.data,
22717 pu1.width,
22718 pu1.true_width,
22719 pu1.true_height,
22720 mv_to_q4(cpx, mv1.1, false),
22721 mv_to_q4(cpy, mv1.0, false),
22722 scale1,
22723 chroma_side,
22724 chroma_side,
22725 write_chroma_w,
22726 write_chroma_h,
22727 h_filter,
22728 v_filter,
22729 &mut inter1_u,
22730 );
22731 // `av1_init_warp_params` bails when the PLANE's block is
22732 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
22733 // block of an 8x8 luma block stays translational.
22734 if let Some(wp) = &warp1 {
22735 if warp_plane_allowed(write_chroma_w, write_chroma_h) {
22736 crate::warp::warp_affine_compound(
22737 wp, &pu1.data, pu1.true_width as i32, pu1.true_height as i32,
22738 pu1.width as i32, &mut inter1_u, cpx as i32, cpy as i32,
22739 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
22740 );
22741 }
22742 }
22743 let mut pred_u = vec![0u16; chroma_side * chroma_side];
22744 if let Some(mask_y) = mask_y {
22745 mc::blend_masked_compound(
22746 &inter0_u,
22747 &inter1_u,
22748 mask_y,
22749 side,
22750 chroma_side,
22751 chroma_side,
22752 true,
22753 &mut pred_u,
22754 );
22755 } else {
22756 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
22757 }
22758
22759 let mut inter0_v = vec![0i32; chroma_side * chroma_side];
22760 mc::predict_compound_intermediate_kern(
22761 &pv0.data,
22762 pv0.width,
22763 pv0.true_width,
22764 pv0.true_height,
22765 mv_to_q4(cpx, mv0.1, false),
22766 mv_to_q4(cpy, mv0.0, false),
22767 scale0,
22768 chroma_side,
22769 chroma_side,
22770 write_chroma_w,
22771 write_chroma_h,
22772 h_filter,
22773 v_filter,
22774 &mut inter0_v,
22775 );
22776 // `av1_init_warp_params` bails when the PLANE's block is
22777 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
22778 // block of an 8x8 luma block stays translational.
22779 if let Some(wp) = &warp0 {
22780 if warp_plane_allowed(write_chroma_w, write_chroma_h) {
22781 crate::warp::warp_affine_compound(
22782 wp, &pv0.data, pv0.true_width as i32, pv0.true_height as i32,
22783 pv0.width as i32, &mut inter0_v, cpx as i32, cpy as i32,
22784 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
22785 );
22786 }
22787 }
22788 let mut inter1_v = vec![0i32; chroma_side * chroma_side];
22789 mc::predict_compound_intermediate_kern(
22790 &pv1.data,
22791 pv1.width,
22792 pv1.true_width,
22793 pv1.true_height,
22794 mv_to_q4(cpx, mv1.1, false),
22795 mv_to_q4(cpy, mv1.0, false),
22796 scale1,
22797 chroma_side,
22798 chroma_side,
22799 write_chroma_w,
22800 write_chroma_h,
22801 h_filter,
22802 v_filter,
22803 &mut inter1_v,
22804 );
22805 // `av1_init_warp_params` bails when the PLANE's block is
22806 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
22807 // block of an 8x8 luma block stays translational.
22808 if let Some(wp) = &warp1 {
22809 if warp_plane_allowed(write_chroma_w, write_chroma_h) {
22810 crate::warp::warp_affine_compound(
22811 wp, &pv1.data, pv1.true_width as i32, pv1.true_height as i32,
22812 pv1.width as i32, &mut inter1_v, cpx as i32, cpy as i32,
22813 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
22814 );
22815 }
22816 }
22817 let mut pred_v = vec![0u16; chroma_side * chroma_side];
22818 if let Some(mask_y) = mask_y {
22819 mc::blend_masked_compound(
22820 &inter0_v,
22821 &inter1_v,
22822 mask_y,
22823 side,
22824 chroma_side,
22825 chroma_side,
22826 true,
22827 &mut pred_v,
22828 );
22829 } else {
22830 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
22831 }
22832
22833 // lane-inter4 r2: a rectangular strip's transform tree starts from
22834 // its own rect `max_txsize_rect_lookup` entry, not a square one.
22835 let rect_tu = (write_w, write_h) != (side, side);
22836 vartx_leaves = if rect_tu {
22837 read_block_tx_size_rect(
22838 dec,
22839 cdfs,
22840 neighbours,
22841 at_mi,
22842 (write_w, write_h),
22843 (mi_cols as usize, mi_rows as usize),
22844 skip,
22845 )?
22846 } else {
22847 read_block_tx_size(
22848 dec,
22849 cdfs,
22850 neighbours,
22851 at_mi,
22852 side,
22853 (mi_cols as usize, mi_rows as usize),
22854 true,
22855 skip,
22856 )?
22857 .1
22858 };
22859 if skip {
22860 y.reconstruct_mc_rect(
22861 px,
22862 py,
22863 side,
22864 write_w,
22865 write_h,
22866 &pred_y,
22867 &vec![0i32; side * side],
22868 );
22869 u.reconstruct_mc_rect(
22870 cpx,
22871 cpy,
22872 chroma_side,
22873 write_chroma_w,
22874 write_chroma_h,
22875 &pred_u,
22876 &vec![0i32; chroma_side * chroma_side],
22877 );
22878 v.reconstruct_mc_rect(
22879 cpx,
22880 cpy,
22881 chroma_side,
22882 write_chroma_w,
22883 write_chroma_h,
22884 &pred_v,
22885 &vec![0i32; chroma_side * chroma_side],
22886 );
22887 luma_grid = vec![0i32; side * side];
22888 u_grid = vec![0i32; chroma_side * chroma_side];
22889 v_grid = vec![0i32; chroma_side * chroma_side];
22890 } else {
22891 // lane-inter4 r2: a rect strip's coefficient context spans its
22892 // OWN width above and height left -- reading `side` cells both
22893 // ways indexes past the tile's last mi row for a bottom strip.
22894 let around = if rect_tu {
22895 neighbours.around_mi_rect(at_mi, write_w, write_h)
22896 } else {
22897 neighbours.around_mi(at, side)
22898 };
22899 let luma_tx_type;
22900 // lane-sb128c r1: a 128x128 inter block's four chroma units
22901 // are read INSIDE the luma leaf loop (one per 64x64 mu chunk);
22902 // these collect them for the block-level neighbour write-back.
22903 let mut u_units = vec![0i32; chroma_side * chroma_side];
22904 let mut v_units = vec![0i32; chroma_side * chroma_side];
22905 if let Some(leaves) = vartx_leaves.clone() {
22906 // spec 5.11.17's transform tree, leaf by leaf in the order
22907 // `read_var_tx_size` coded it: each unit reads its own
22908 // coefficients against the neighbour magnitudes the
22909 // earlier units already wrote, and reconstructs over its
22910 // own slice of the block's motion-compensated predictor.
22911 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
22912 let mut first_tx_type = TxType::DctDct;
22913 for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() {
22914 let tu_mi = (at_mi.0 + row, at_mi.1 + col);
22915 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
22916 let (tu_grid, tu_tx_type) = if tw == th {
22917 let tx_px = tw;
22918 let mut tu_pred = Vec::with_capacity(tx_px * tx_px);
22919 for rr in 0..tx_px {
22920 let start = (row * MI + rr) * side + col * MI;
22921 tu_pred.extend_from_slice(&pred_y[start..start + tx_px]);
22922 }
22923 let scan = default_scan(tx_px.min(32));
22924 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI);
22925 read_inter_plane(
22926 dec,
22927 cdfs,
22928 inter_txbset_for(tx_px, reduced),
22929 &scan,
22930 0,
22931 neighbours.around_mi(tu_mi, tx_px)[0],
22932 mode_for_tx,
22933 y,
22934 tu_px,
22935 tu_py,
22936 tx_px,
22937 base_q_idx,
22938 &tu_pred,
22939 None,
22940 Some(tu_skip_ctx),
22941 )?
22942 } else {
22943 // lane-r14 r3: a 1:4 strip's `sub_tx_size_map`
22944 // sub-transform is RECTANGULAR (TX_64X16 ->
22945 // TX_32X16, TX_16X64 -> TX_16X32), so this leaf is
22946 // read with the rect coefficient machinery, at its
22947 // own `txb_skip_ctx`/neighbour spans -- the unit is
22948 // smaller than its block, so `get_txb_ctx_general`'s
22949 // neighbour table applies, not the lone-TU 0.
22950 vartx_rect_leaf_hit(tw, th);
22951 let tu_skip_ctx =
22952 neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI);
22953 let start = row * MI * side + col * MI;
22954 read_inter_plane_rect(
22955 dec,
22956 cdfs,
22957 rect_inter_luma_set(tw, th)?,
22958 (tw, th),
22959 side,
22960 0,
22961 neighbours.around_mi_rect(tu_mi, tw, th)[0],
22962 mode_for_tx,
22963 y,
22964 tu_px,
22965 tu_py,
22966 &pred_y[start..],
22967 None,
22968 Some(tu_skip_ctx),
22969 )?
22970 };
22971 if idx == 0 {
22972 first_tx_type = tu_tx_type;
22973 }
22974 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
22975 // lane-sb128c r1: libaom's `decode_token_recon_block`
22976 // walks 64x64 "mu" chunks (`mu_blocks_wide/high =
22977 // mi_size_wide[BLOCK_64X64]`) and codes EVERY PLANE of
22978 // a chunk before the next one, so a 128x128 block
22979 // interleaves Y,U,V per quadrant -- the same order the
22980 // intra 128 path reads (lane-sb128b r3, measured
22981 // against aomdec's `EC_TRACE_COEFF`). Below 128 a block
22982 // is a single chunk and this never fires.
22983 if side > 64 {
22984 let chunk = (row / 16, col / 16);
22985 let done = idx + 1 == leaves.len()
22986 || (leaves[idx + 1].0 / 16, leaves[idx + 1].1 / 16) != chunk;
22987 if done {
22988 let (cr, cc) = chunk;
22989 // `av1_get_max_uv_txsize(BLOCK_128X128)` =
22990 // `av1_get_adjusted_tx_size(TX_64X64)` =
22991 // TX_32X32: one 32x32 chroma unit per chunk.
22992 let cu_tx = 32usize;
22993 let luma_span = cu_tx * 2;
22994 let cu_mi = (at_mi.0 + cr * 16, at_mi.1 + cc * 16);
22995 let cu_around = neighbours.around_mi(cu_mi, luma_span);
22996 let (cu_x, cu_y) = (cpx + cc * cu_tx, cpy + cr * cu_tx);
22997 let cu_scan = default_scan(cu_tx);
22998 for plane_idx in 1..3 {
22999 let (src, buf) = if plane_idx == 1 {
23000 (&pred_u, &mut *u)
23001 } else {
23002 (&pred_v, &mut *v)
23003 };
23004 let mut cu_pred = Vec::with_capacity(cu_tx * cu_tx);
23005 for rr in 0..cu_tx {
23006 let start =
23007 (cr * cu_tx + rr) * chroma_side + cc * cu_tx;
23008 cu_pred.extend_from_slice(&src[start..start + cu_tx]);
23009 }
23010 let cu_grid = read_inter_plane(
23011 dec,
23012 cdfs,
23013 chroma_set,
23014 &cu_scan,
23015 plane_idx,
23016 cu_around[plane_idx],
23017 mode_for_tx,
23018 buf,
23019 cu_x,
23020 cu_y,
23021 cu_tx,
23022 base_q_idx,
23023 &cu_pred,
23024 Some(first_tx_type),
23025 Some(3),
23026 )?
23027 .0;
23028 // Immediately, so the NEXT chunk's unit
23029 // reads this one's coefficient context.
23030 neighbours.record_mi_chroma(
23031 cu_mi, luma_span, luma_span, plane_idx, &cu_grid,
23032 );
23033 CHROMA_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
23034 mu_chroma = true;
23035 let dst = if plane_idx == 1 {
23036 &mut u_units
23037 } else {
23038 &mut v_units
23039 };
23040 for rr in 0..cu_tx {
23041 let start =
23042 (cr * cu_tx + rr) * chroma_side + cc * cu_tx;
23043 dst[start..start + cu_tx]
23044 .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]);
23045 }
23046 }
23047 }
23048 }
23049 }
23050 // `av1_get_tx_type`'s chroma lookup scales the chroma
23051 // position back to luma, so an inter block's chroma
23052 // inherits the *first* (top-left) luma unit's coded type.
23053 luma_tx_type = first_tx_type;
23054 luma_grid = vec![0i32; side * side];
23055 } else if rect_tu {
23056 // The whole-block rectangular transform unit
23057 // (`txfm_partition` said 0 at depth 0).
23058 let (grid, tx_type) = read_inter_plane_rect(
23059 dec,
23060 cdfs,
23061 rect_inter_luma_set(write_w, write_h)?,
23062 (write_w, write_h),
23063 side,
23064 0,
23065 around[0],
23066 mode_for_tx,
23067 y,
23068 px,
23069 py,
23070 &pred_y,
23071 None,
23072 None,
23073 )?;
23074 luma_tx_type = tx_type;
23075 luma_grid = embed_rect_grid(&grid, write_w, write_h, side);
23076 } else {
23077 (luma_grid, luma_tx_type) = read_inter_plane(
23078 dec,
23079 cdfs,
23080 luma_set_inter,
23081 scan_luma,
23082 0,
23083 around[0],
23084 mode_for_tx,
23085 y,
23086 px,
23087 py,
23088 side,
23089 base_q_idx,
23090 &pred_y,
23091 None,
23092 None,
23093 )?;
23094 }
23095 if side > 64 {
23096 // Already read inside the mu-chunk loop above -- at the 128
23097 // root a rect (128x64/64x128) block's chroma is per mu
23098 // chunk too, so this test comes BEFORE the `rect_tu` one.
23099 u_grid = std::mem::take(&mut u_units);
23100 v_grid = std::mem::take(&mut v_units);
23101 } else if rect_tu {
23102 // `av1_get_max_uv_txsize(bsize)`: the chroma transform of a
23103 // 2:1 strip is the strip's own rect chroma size (16x8 /
23104 // 8x16), one unit for the whole block, and it codes no
23105 // `tx_type` symbol -- it inherits the luma unit's.
23106 let (uw, uh) = (write_chroma_w, write_chroma_h);
23107 u_grid = embed_rect_grid(
23108 &read_inter_plane_rect(
23109 dec,
23110 cdfs,
23111 rect_inter_chroma_set(write_chroma_w, write_chroma_h)?,
23112 (uw, uh),
23113 chroma_side,
23114 1,
23115 around[1],
23116 mode_for_tx,
23117 u,
23118 cpx,
23119 cpy,
23120 &pred_u,
23121 Some(luma_tx_type),
23122 None,
23123 )?
23124 .0,
23125 uw,
23126 uh,
23127 chroma_side,
23128 );
23129 v_grid = embed_rect_grid(
23130 &read_inter_plane_rect(
23131 dec,
23132 cdfs,
23133 rect_inter_chroma_set(write_chroma_w, write_chroma_h)?,
23134 (uw, uh),
23135 chroma_side,
23136 2,
23137 around[2],
23138 mode_for_tx,
23139 v,
23140 cpx,
23141 cpy,
23142 &pred_v,
23143 Some(luma_tx_type),
23144 None,
23145 )?
23146 .0,
23147 uw,
23148 uh,
23149 chroma_side,
23150 );
23151 } else {
23152 u_grid = read_inter_plane(
23153 dec,
23154 cdfs,
23155 chroma_set,
23156 scan_chroma,
23157 1,
23158 around[1],
23159 mode_for_tx,
23160 u,
23161 cpx,
23162 cpy,
23163 chroma_side,
23164 base_q_idx,
23165 &pred_u,
23166 Some(luma_tx_type),
23167 None,
23168 )?
23169 .0;
23170 v_grid = read_inter_plane(
23171 dec,
23172 cdfs,
23173 chroma_set,
23174 scan_chroma,
23175 2,
23176 around[2],
23177 mode_for_tx,
23178 v,
23179 cpx,
23180 cpy,
23181 chroma_side,
23182 base_q_idx,
23183 &pred_v,
23184 Some(luma_tx_type),
23185 None,
23186 )?
23187 .0;
23188 }
23189 }
23190 } else {
23191 let ref_frame =
23192 read_single_ref(
23193 dec,
23194 cdfs,
23195 neighbours.above_ref[cmi],
23196 neighbours.above_ref1[cmi],
23197 neighbours.left_ref[rmi],
23198 neighbours.left_ref1[rmi],
23199 );
23200 ref_frame_for_lf = ref_frame;
23201 if crate::envflags::env_flag!("EC_AV1_TELL") {
23202 let (mi_row, mi_col) = (rmi, cmi);
23203 eprintln!(
23204 "TELL mi_row={mi_row} mi_col={mi_col} label=post_ref_frame ref={ref_frame} tell={} range={}",
23205 dec.debug_bitpos(), dec.debug_state().0
23206 );
23207 }
23208 // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own
23209 // stacked defects (lf_level ref/mode-delta forwarding, the
23210 // switchable_interp ref-frame ctx gate, and a film-grain synthesis
23211 // gap that looked like a GOLDEN MC bug by survivor bias -- see the
23212 // ledger) are all closed; GOLDEN_FRAME decodes live via `other_refs`
23213 // below same as every other non-`LAST_FRAME` reference. lane-av1refs
23214 // widens this from GOLDEN alone to every reference `read_single_ref`
23215 // can name.
23216 let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME {
23217 (ref_y, ref_u, ref_v)
23218 } else {
23219 match other_refs[ref_frame as usize] {
23220 Some((ry, ru, rv)) => (ry, ru, rv),
23221 None => {
23222 return Err(unsupported(
23223 "a reference frame selected with no picture at this frame's own \
23224 ref_frame_idx slot for it",
23225 ));
23226 }
23227 }
23228 };
23229
23230 let (mi_row, mi_col) = (rmi, cmi);
23231 // lane-rect r2: the mv stack must be queried with the block's
23232 // REAL extent (libaom `av1_get_mv_refs` gets bw4/bh4 from
23233 // xd->width/xd->height, not a square guess) -- `write_w`/
23234 // `write_h` already name the true HORZ/VERT/HORZ_B strip
23235 // footprint (r1's plumbing), so derive bw4/bh4 from those
23236 // instead of the old `side`-square (HORZ_B-only) heuristic.
23237 let bw4 = write_w / 4;
23238 let bh4 = write_h / 4;
23239 // spec 7.10.2.8: only reached when the frame header set
23240 // `use_ref_frame_mvs` (`tpl_frame` is `Some` then, `None`
23241 // otherwise) -- `cur_offset_0` is this query block's own resolved
23242 // `ref_frame`'s distance from the current frame (spec 7.9.3),
23243 // recomputed per block since different blocks pick different refs.
23244 let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
23245 field: t.field,
23246 cur_offset_0: crate::motion_field::get_relative_dist(
23247 t.order_hint_bits,
23248 t.order_hint,
23249 t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
23250 ),
23251 allow_high_precision_mv,
23252 });
23253 let gm_table = build_gm_mv_table(
23254 global_motion,
23255 mi_row,
23256 mi_col,
23257 bw4,
23258 bh4,
23259 allow_high_precision_mv,
23260 force_integer_mv,
23261 );
23262 let stack = find_mv_stack_with_sign_bias(
23263 grid,
23264 mi_row,
23265 mi_col,
23266 bw4,
23267 bh4,
23268 ref_frame,
23269 mi_cols as usize,
23270 mi_rows as usize,
23271 sign_bias_table,
23272 &gm_table,
23273 tpl,
23274 );
23275 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
23276 let mut is_globalmv = false;
23277 // lane-interbis r1: which single-ref mode this block resolved to,
23278 // in the oracle's own numbering (NEARESTMV=13 .. NEWMV=16), for
23279 // the `EC_MODE_VAL` value ladder below.
23280 let mut dbg_mode = 16u32;
23281 let (mv, is_new_mv) = if !not_new {
23282 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
23283 // read at most two `drl_mode` bits, one per stack entry past the
23284 // first, stopping at the first `0`. The chosen index selects
23285 // which stack entry `read_mv`'s base predictor comes from
23286 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
23287 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
23288 let mut idx = 0usize;
23289 while idx < 2 && stack.entries.len() > idx + 1 {
23290 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
23291 break;
23292 }
23293 idx += 1;
23294 }
23295 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
23296 (
23297 read_mv(
23298 dec,
23299 &mut cdfs.mv_comp,
23300 &mut cdfs.mv_joint,
23301 base_mv,
23302 allow_high_precision_mv,
23303 force_integer_mv,
23304 ),
23305 true,
23306 )
23307 } else {
23308 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
23309 is_globalmv = !not_zero;
23310 let mv = if !not_zero {
23311 // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already
23312 // computed at this block's own position in `gm_table`.
23313 dbg_mode = 15;
23314 gm_table[(ref_frame - LAST_FRAME) as usize]
23315 } else {
23316 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
23317 dbg_mode = if nearest { 13 } else { 14 };
23318 if nearest {
23319 stack.nearest_mv
23320 } else {
23321 // NEARMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting
23322 // at 1): read at most two more `drl_mode` bits, one per stack
23323 // entry past the second, stopping at the first `0`.
23324 // `drl_ctx[idx]` is the context between `entries[idx]` and
23325 // `entries[idx + 1]` (`MvStack::drl_ctx`'s own doc), which is
23326 // exactly the pair this index is choosing between.
23327 let mut idx = 1usize;
23328 while idx < 3 && stack.entries.len() > idx + 1 {
23329 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
23330 break;
23331 }
23332 idx += 1;
23333 }
23334 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
23335 }
23336 };
23337 (mv, false)
23338 };
23339 if crate::envflags::env_flag!("EC_TRACE_MODE") {
23340 for (i, e) in stack.entries.iter().enumerate() {
23341 eprintln!(
23342 "EC_STACK mi_row={mi_row} mi_col={mi_col} ref={ref_frame} i={i} this=({},{}) comp=(0,0) w={}",
23343

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