forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB34789daTahinli3 months ago1757 commits

decode.rs23402 lines, 1.2 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 static SB128: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
68}
69
70/// Sets [`SB128`] for this thread (called once per frame from `stream.rs`).
71pub(crate) fn set_sb128(v: bool) {
72 SB128.with(|c| c.set(v));
73 crate::encode::set_reach_superblock_px(if v { 128 } else { 64 });
74}
75
76fn sb128() -> bool {
77 SB128.with(|c| c.get())
78}
79
80/// This sequence's superblock size in mi units (16 = 64x64, 32 = 128x128).
81pub(crate) fn sb_mi_cur() -> u32 {
82 if sb128() { SB_MI * 2 } else { SB_MI }
83}
84
85/// How many real 128-level partition symbols this decoder has read, and how
86/// many superblocks resolved to `PARTITION_SPLIT` (coded or forced) -- the
87/// gate's proof a `--sb-size=128` stream exercised the 128 partition root.
88thread_local! {
89 static PART128_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
90 static PART128_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
91 static PART128_GATHERED_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
92}
93
94/// Current value of `PART128_GATHERED_SYMBOLS`: 128 roots that read the
95/// half-out-of-frame gathered split_or_horz/split_or_vert symbol (spec
96/// 5.11.4), which this decoder used to read and throw away.
97pub(crate) fn part128_gathered_symbols() -> usize {
98 PART128_GATHERED_SYMBOLS.with(|c| c.get())
99}
100
101/// Current value of [`PART128_SYMBOLS`].
102pub(crate) fn part128_symbols() -> usize {
103 PART128_SYMBOLS.with(|c| c.get())
104}
105
106/// Current value of [`PART128_SPLIT_HITS`].
107pub(crate) fn part128_split_hits() -> usize {
108 PART128_SPLIT_HITS.with(|c| c.get())
109}
110
111/// [`gather`] over an alphabet of any length -- the 128-level partition CDF
112/// has 8 symbols (no `PARTITION_HORZ_4`/`_VERT_4` at `BLOCK_128X128`, spec
113/// `partition_cdf_length`), so its forced-split gather sums 5 elements where
114/// the 64/32 levels sum 6.
115fn gather_of(cdf: &[u16], elements: &[usize]) -> [u16; 3] {
116 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
117 [32768 - split, 32768, 0]
118}
119
120/// [`VERT_ALIKE`]/[`HORZ_ALIKE`] without the 1:4 arms, for the 128 root.
121const VERT_ALIKE128: [usize; 5] = [2, PARTITION_SPLIT, 4, 6, 7];
122const HORZ_ALIKE128: [usize; 5] = [1, PARTITION_SPLIT, 4, 5, 6];
123
124// How many `use_filter_intra` symbols this decoder has read as `1`, across
125// every call on the current thread -- the cheap counter [`filter_intra_hits`] gate
126// tests read (before/after, not the absolute value) to prove a stream
127// actually exercised the filter-intra predictor rather than silently
128// skipping it.
129thread_local! {
130 static FILTER_INTRA_HITS: std::cell::Cell<usize> =
131 const { std::cell::Cell::new(0) };
132}
133
134/// Current value of [`FILTER_INTRA_HITS`].
135pub(crate) fn filter_intra_hits() -> usize {
136 FILTER_INTRA_HITS.with(|c| c.get())
137}
138
139// lane-fiinter r1: how many of those `use_filter_intra == 1` symbols belonged
140// to an INTRA block inside an INTER frame (`read_intra_block_mode_info`'s own
141// `read_filter_intra_mode_info` call), which no gate exercised before this
142// round -- every inter gate recipe passed `--enable-filter-intra=0`.
143thread_local! {
144 static INTRA_IN_INTER_FILTER_INTRA_HITS: std::cell::Cell<usize> =
145 const { std::cell::Cell::new(0) };
146}
147
148/// Current value of [`INTRA_IN_INTER_FILTER_INTRA_HITS`].
149pub(crate) fn intra_in_inter_filter_intra_hits() -> usize {
150 INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.get())
151}
152
153// lane-angleinter r1: how many INTRA blocks inside an INTER frame carried a
154// nonzero `angle_delta_y` / `angle_delta_uv` (`read_intra_angle_info`). Both
155// arms refused a nonzero luma delta before this round, and no inter gate
156// enabled `--enable-angle-delta` (aomenc's own default is 1).
157thread_local! {
158 static INTRA_IN_INTER_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> =
159 const { std::cell::Cell::new(0) };
160 static INTRA_IN_INTER_ANGLE_DELTA_UV_HITS: std::cell::Cell<usize> =
161 const { std::cell::Cell::new(0) };
162}
163
164/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_Y_HITS`].
165pub(crate) fn intra_in_inter_angle_delta_y_hits() -> usize {
166 INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.get())
167}
168
169/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_UV_HITS`].
170pub(crate) fn intra_in_inter_angle_delta_uv_hits() -> usize {
171 INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|c| c.get())
172}
173
174// lane-uv8 r1: the three non-DC chroma mode classes an INTRA 8x8 leaf inside
175// an INTER frame ([`decode_inter_block8`]'s intra arm) can carry -- the arm
176// read `uv_mode` and then refused everything but `DC_PRED`. Counted here and
177// nowhere else so the gate's assert cannot be satisfied by a >=16x16 block.
178thread_local! {
179 static INTRA_IN_INTER8_UV_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
180 static INTRA_IN_INTER8_UV_SMOOTH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
181 static INTRA_IN_INTER8_UV_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
182}
183
184/// `(directional, smooth/paeth, CfL)` chroma modes coded by an intra 8x8 leaf
185/// inside an inter frame -- see [`INTRA_IN_INTER8_UV_DIR_HITS`].
186pub(crate) fn intra_in_inter8_uv_hits() -> (usize, usize, usize) {
187 (
188 INTRA_IN_INTER8_UV_DIR_HITS.with(|c| c.get()),
189 INTRA_IN_INTER8_UV_SMOOTH_HITS.with(|c| c.get()),
190 INTRA_IN_INTER8_UV_CFL_HITS.with(|c| c.get()),
191 )
192}
193
194// lane-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into
195// [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a
196// frame-level flag through the recursive block decode -- `0` (the default)
197// makes every call a true no-op, matching every existing gate stream's
198// `cdef_bits == 0` behaviour exactly.
199thread_local! {
200 static CDEF_BITS: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
201}
202// lane-realworld r8: the sequence header's `color_config.bit_depth`, set
203// once per `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs`
204// call the same way `CDEF_BITS` is above. `stream.rs`'s own refusal still
205// blocks every non-8-bit stream from reaching a decode call, so this is `8`
206// on every path that runs today -- threading it now (rather than the literal
207// `8`) is stage 1 of widening past that refusal without re-deriving every
208// clamp bound later. `PlaneBuf`'s sample storage stays `u16` regardless of
209// depth (this decoder's own internal choice, matches dav1d/libaom).
210thread_local! {
211 static BIT_DEPTH: std::cell::Cell<u8> = const { std::cell::Cell::new(8) };
212}
213/// `(1 << bit_depth) - 1` — the reconstruction clamp bound for the current
214/// stream's [`BIT_DEPTH`], replacing the crate-wide literal `255`.
215pub(crate) fn sample_max() -> i32 {
216 (1i32 << BIT_DEPTH.with(std::cell::Cell::get)) - 1
217}
218/// The current stream's bit depth, for callers (e.g. dequant) that need the
219/// raw value rather than the derived clamp bound.
220pub(crate) fn bit_depth() -> u8 {
221 BIT_DEPTH.with(std::cell::Cell::get)
222}
223/// Sets [`BIT_DEPTH`] for the current thread, called once per frame from
224/// [`crate::stream`]'s decode loop.
225pub(crate) fn set_bit_depth(bit_depth: u8) {
226 BIT_DEPTH.with(|c| c.set(bit_depth));
227}
228// Whether this superblock's single CDEF unit (this decoder has no 128x128
229// SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal
230// read -- reset to `false` at the top of each superblock in the two tile
231// loops, spec `read_cdef`'s `cdef_transmitted[index]`.
232thread_local! {
233 static CDEF_TRANSMITTED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
234}
235// Number of superblock columns in the current tile's grid, so
236// [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into
237// [`CDEF_IDX_GRID`].
238thread_local! {
239 static CDEF_SB_COLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
240}
241// One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select
242// which of the header's `1 << cdef.bits` strength pairs applies to that
243// superblock's samples.
244thread_local! {
245 static CDEF_IDX_GRID: std::cell::RefCell<Vec<u8>> = std::cell::RefCell::new(Vec::new());
246}
247// How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`]
248// has read, across every call on the current thread -- the gate's proof that a
249// `cdef_bits > 0` stream actually reached the new reader rather than every
250// superblock coincidentally being all-skip.
251thread_local! {
252 static CDEF_IDX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
253}
254
255/// Current value of [`CDEF_IDX_HITS`].
256pub(crate) fn cdef_idx_hits() -> usize {
257 CDEF_IDX_HITS.with(|c| c.get())
258}
259
260// lane-realworld r4: this frame's `delta.q_present` (spec 5.9.17) and its
261// actual step (`1 << delta.q_res`, already the real multiplier, not the raw
262// 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a
263// true no-op, matching every existing gate stream's `delta_q_present == 0`
264// behaviour exactly, the same corner-cut [`CDEF_BITS`] takes above.
265thread_local! {
266 static DELTA_Q_PRESENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
267 static DELTA_Q_RES: std::cell::Cell<i32> = const { std::cell::Cell::new(1) };
268}
269// The running quantizer index (spec `CurrentQIndex`, libaom
270// `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the
271// top of every tile (spec `decode_tile`), carried across superblocks within
272// that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the
273// dequantization call sites instead of the frame-constant `base_q_idx`.
274thread_local! {
275 static CURRENT_Q_IDX: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };
276}
277// This frame's own per-plane DC/AC quantizer-index deltas (lane-sbpart r11,
278// spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- frame-constant (not
279// per-superblock like [`CURRENT_Q_IDX`]), set once per frame decode and read
280// back at every dequantization call site keyed on which plane it is doing.
281thread_local! {
282 static QUANT_DELTAS: std::cell::Cell<crate::quant::QuantDeltas> = const {
283 std::cell::Cell::new(crate::quant::QuantDeltas {
284 y_dc: 0,
285 u_dc: 0,
286 u_ac: 0,
287 v_dc: 0,
288 v_ac: 0,
289 })
290 };
291}
292// How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has
293// read, across every call on the current thread -- the gate's proof that a
294// `delta_q_present` stream actually reached the new reader.
295thread_local! {
296 static DELTA_Q_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
297}
298
299/// Current value of [`DELTA_Q_HITS`].
300pub(crate) fn delta_q_hits() -> usize {
301 DELTA_Q_HITS.with(|c| c.get())
302}
303
304/// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 =
305/// Y, 1 = U, 2 = V) -- luma has no coded `ac` delta (spec 5.9.12 never reads
306/// one), so it is always `0` here.
307fn plane_q_delta(plane_idx: usize) -> (i32, i32) {
308 let d = QUANT_DELTAS.with(|c| c.get());
309 match plane_idx {
310 0 => (d.y_dc, 0),
311 1 => (d.u_dc, d.u_ac),
312 _ => (d.v_dc, d.v_ac),
313 }
314}
315
316/// `read_delta_qindex`/`read_delta_q_params` (spec 5.11.10, libaom
317/// `decodemv.c:85-146,735-770`), called right after [`maybe_read_cdef_idx`]
318/// at every block-decode call site (spec order `skip -> cdef -> delta_q`).
319/// A no-op when `delta_q_present` is unset, or when this block is not at the
320/// superblock's own top-left MI position (`b_row == 0 && b_col == 0` in
321/// libaom, collapsed here to a position check since a partition tree's
322/// top-left leaf is the only block that can ever land there), or when that
323/// leaf both *is* the whole superblock and is `skip` (the one case libaom
324/// itself skips the read, state carrying over unchanged).
325fn maybe_read_delta_q(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool) {
326 if !DELTA_Q_PRESENT.with(|c| c.get()) {
327 return;
328 }
329 let sb_mi = sb_mi_cur() as usize;
330 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
331 return;
332 }
333 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
334 // computed against the sequence's own superblock size (lane-sb128b r1:
335 // it used to be hardcoded against 64 and disabled under `sb128`, which a
336 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
337 // wrong).
338 if is_whole_sb && skip {
339 return;
340 }
341 let mut abs = dec.symbol(&mut cdfs.delta_q) as i32;
342 const DELTA_Q_SMALL: i32 = 3;
343 if abs >= DELTA_Q_SMALL {
344 let rem_bits = dec.literal(3) + 1;
345 let thr = (1i32 << rem_bits) + 1;
346 abs = dec.literal(rem_bits) as i32 + thr;
347 }
348 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
349 let reduced = if sign_negative { -abs } else { abs };
350 DELTA_Q_HITS.with(|c| c.set(c.get() + 1));
351 let res = DELTA_Q_RES.with(|c| c.get());
352 CURRENT_Q_IDX.with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));
353}
354
355// lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi`
356// (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`.
357thread_local! {
358 static DELTA_LF_PRESENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
359 static DELTA_LF_RES: std::cell::Cell<i32> = const { std::cell::Cell::new(1) };
360 static DELTA_LF_MULTI: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
361}
362// The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`,
363// `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile,
364// mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever
365// updates index 0 and every reader treats that as the value for all 4
366// indices (spec `read_delta_lf_params`'s own single-cdf branch).
367thread_local! {
368 static CURRENT_DELTA_LF: std::cell::Cell<[i32; 4]> = const { std::cell::Cell::new([0; 4]) };
369}
370// How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has
371// read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`].
372thread_local! {
373 static DELTA_LF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
374}
375
376/// Current value of [`DELTA_LF_HITS`].
377pub(crate) fn delta_lf_hits() -> usize {
378 DELTA_LF_HITS.with(|c| c.get())
379}
380
381/// `read_delta_lflevel`/`read_delta_lf_params` (spec 5.11.11, libaom
382/// `decodemv.c:99-146,735-770`) -- same shape and same call-site gating as
383/// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over
384/// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or
385/// read once into index 0 otherwise.
386fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool) {
387 if !DELTA_LF_PRESENT.with(|c| c.get()) {
388 return;
389 }
390 let sb_mi = sb_mi_cur() as usize;
391 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
392 return;
393 }
394 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
395 // computed against the sequence's own superblock size (lane-sb128b r1:
396 // it used to be hardcoded against 64 and disabled under `sb128`, which a
397 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
398 // wrong).
399 if is_whole_sb && skip {
400 return;
401 }
402 let multi = DELTA_LF_MULTI.with(|c| c.get());
403 let res = DELTA_LF_RES.with(|c| c.get());
404 let count = if multi { 4 } else { 1 };
405 let mut cur = CURRENT_DELTA_LF.with(|c| c.get());
406 for i in 0..count {
407 let mut abs = if multi {
408 dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32
409 } else {
410 dec.symbol(&mut cdfs.delta_lf) as i32
411 };
412 const DELTA_LF_SMALL: i32 = 3;
413 if abs >= DELTA_LF_SMALL {
414 let rem_bits = dec.literal(3) + 1;
415 let thr = (1i32 << rem_bits) + 1;
416 abs = dec.literal(rem_bits) as i32 + thr;
417 }
418 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
419 let reduced = if sign_negative { -abs } else { abs };
420 cur[i] = (cur[i] + reduced * res).clamp(-63, 63);
421 DELTA_LF_HITS.with(|c| c.set(c.get() + 1));
422 }
423 CURRENT_DELTA_LF.with(|c| c.set(cur));
424}
425
426/// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
427/// after `skip` is known at every block-decode call site. A no-op at
428/// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and
429/// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
430/// `allow_intrabc`, so neither needs a separate check here. Reads once per
431/// superblock, at the first non-skip block.
432fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: bool) {
433 let bits = CDEF_BITS.with(|c| c.get());
434 if bits == 0 || skip || CDEF_TRANSMITTED.with(|c| c.get()) {
435 return;
436 }
437 let idx = dec.literal(u32::from(bits)) as u8;
438 CDEF_TRANSMITTED.with(|c| c.set(true));
439 CDEF_IDX_HITS.with(|c| c.set(c.get() + 1));
440 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
441 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
442 if sb_cols > 0 {
443 CDEF_IDX_GRID.with(|g| {
444 let mut g = g.borrow_mut();
445 let i = sb_r * sb_cols + sb_c;
446 if i < g.len() {
447 g[i] = idx;
448 }
449 });
450 }
451}
452
453// ---------------------------------------------------------------------------
454// lane-seg: segmentation. Header (spec 5.9.14) is parsed by `ec-av1-syntax`;
455// this block is the per-block `segment_id` reader (spec 5.11.7-5.11.9) plus
456// the two consumers a real stream exercises: the per-segment quantizer index
457// (spec 7.12.2 `get_qindex`) and the per-segment loop-filter level
458// (spec 7.14.4). Shapes follow libaom `decodemv.c:read_segment_id`/
459// `read_intra_segment_id`/`read_inter_segment_id` and
460// `pred_common.h:av1_get_spatial_seg_pred` -- note libaom returns the SPATIAL
461// PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which
462// is what the oracle every gate here compares against actually does.
463thread_local! {
464 static SEG: std::cell::RefCell<SegmentationParams> =
465 std::cell::RefCell::new(SegmentationParams::default());
466 /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries
467 /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride).
468 static SEG_IDS: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
469 /// `PrevSegmentIds`: the primary reference frame's saved map, empty when
470 /// this frame has no primary reference (spec `load_previous_segment_ids`).
471 static PREV_SEG_IDS: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
472 /// `(mi_rows, mi_cols)` for both maps above.
473 static SEG_MI_DIMS: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
474 /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi
475 /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which
476 /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead.
477 static ABOVE_SEG_PRED: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
478 static LEFT_SEG_PRED: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
479 /// The block currently being decoded -- read back by [`block_q_idx`].
480 static CUR_SEGMENT_ID: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
481 /// The tile's own top-left mi position, for `AvailU`/`AvailL`.
482 static SEG_TILE_ORIGIN: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
483 /// How many real `segment_id` symbols were read, and the set of segment
484 /// ids any block ended up with -- the gate's proof the feature fired.
485 static SEG_ID_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
486 static SEG_IDS_SEEN: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
487 /// How many `seg_id_predicted` symbols were read (temporal update).
488 static SEG_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
489}
490
491/// Installs this frame's segmentation parameters and allocates its map, with
492/// `prev` the primary reference frame's saved map (spec
493/// `load_previous_segment_ids`; `None` for `PRIMARY_REF_NONE` or an empty
494/// slot). Called once per frame, whether or not segmentation is enabled.
495pub(crate) fn set_segmentation(
496 seg: SegmentationParams,
497 mi_rows: usize,
498 mi_cols: usize,
499 prev: Option<&[u8]>,
500) {
501 SEG.with(|s| *s.borrow_mut() = seg);
502 SEG_MI_DIMS.with(|c| c.set((mi_rows, mi_cols)));
503 SEG_IDS.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]);
504 PREV_SEG_IDS.with(|m| {
505 let mut m = m.borrow_mut();
506 m.clear();
507 if let Some(p) = prev {
508 if p.len() == mi_rows * mi_cols {
509 m.extend_from_slice(p);
510 }
511 }
512 });
513 ABOVE_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_cols]);
514 LEFT_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_rows]);
515 CUR_SEGMENT_ID.with(|c| c.set(0));
516}
517
518/// This frame's decoded segment map, to be stored into whichever reference
519/// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`).
520pub(crate) fn take_segment_ids() -> Vec<u8> {
521 SEG_IDS.with(|m| m.borrow().clone())
522}
523
524/// How many `segment_id` symbols have been read (never reset per frame).
525pub(crate) fn segment_id_hits() -> usize {
526 SEG_ID_HITS.with(|c| c.get())
527}
528
529/// How many distinct segment ids any decoded block has carried.
530pub(crate) fn segment_ids_seen() -> usize {
531 SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize)
532}
533
534/// How many `seg_id_predicted` symbols have been read (temporal update).
535pub(crate) fn segment_pred_hits() -> usize {
536 SEG_PRED_HITS.with(|c| c.get())
537}
538
539/// Resets the segmentation hit counters (gate setup).
540pub(crate) fn reset_segment_hits() {
541 SEG_ID_HITS.with(|c| c.set(0));
542 SEG_IDS_SEEN.with(|c| c.set(0));
543 SEG_PRED_HITS.with(|c| c.set(0));
544}
545
546/// `seg_feature_active_idx(segment_id, feature)` for the frame currently
547/// being decoded, with its `FeatureData` value.
548fn seg_feature(segment_id: usize, feature: usize) -> Option<i32> {
549 SEG.with(|s| {
550 let s = s.borrow();
551 s.feature_active(segment_id, feature)
552 .then(|| i32::from(s.feature_data[segment_id][feature]))
553 })
554}
555
556/// `get_qindex(ignoreDeltaQ = 0, segment_id)` (spec 7.12.2, libaom
557/// `av1_get_qindex`) for the block currently being decoded: the running
558/// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data.
559/// Every dequant call site reads the block's quantizer through here.
560fn block_q_idx() -> i32 {
561 let base = CURRENT_Q_IDX.with(|c| c.get());
562 let seg_id = CUR_SEGMENT_ID.with(|c| c.get()) as usize;
563 match seg_feature(seg_id, SEG_LVL_ALT_Q) {
564 Some(data) => (base + data).clamp(0, 255),
565 None => base,
566 }
567}
568
569/// The segment id recorded for one mi cell of the current frame's map.
570fn segment_id_at(mi_r: usize, mi_c: usize) -> u8 {
571 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
572 if mi_r >= mi_rows || mi_c >= mi_cols {
573 return 0;
574 }
575 SEG_IDS.with(|m| m.borrow()[mi_r * mi_cols + mi_c])
576}
577
578/// `set_segment_id`: stamps `id` over every mi cell this block covers.
579fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8) {
580 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
581 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
582 SEG_IDS.with(|m| {
583 let mut m = m.borrow_mut();
584 for y in 0..y_mis {
585 for x in 0..x_mis {
586 m[(mi_r + y) * mi_cols + mi_c + x] = id;
587 }
588 }
589 });
590 CUR_SEGMENT_ID.with(|c| c.set(id));
591 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
592}
593
594/// `get_predicted_segment_id` (libaom `dec_get_segment_id` over
595/// `last_frame_seg_map`): the minimum previous-frame segment id over the
596/// block's own mi footprint. `0` when there is no previous map.
597fn predicted_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize) -> u8 {
598 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
599 PREV_SEG_IDS.with(|m| {
600 let m = m.borrow();
601 if m.is_empty() {
602 return 0;
603 }
604 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
605 let mut id = u8::MAX;
606 for y in 0..y_mis {
607 for x in 0..x_mis {
608 id = id.min(m[(mi_r + y) * mi_cols + mi_c + x]);
609 }
610 }
611 if id == u8::MAX { 0 } else { id }
612 })
613}
614
615/// `av1_neg_deinterleave` (libaom `decodemv.c:258`).
616fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 {
617 if reference == 0 {
618 return diff;
619 }
620 if reference >= max - 1 {
621 return max - diff - 1;
622 }
623 let half = if 2 * reference < max {
624 diff <= 2 * reference
625 } else {
626 diff <= 2 * (max - reference - 1)
627 };
628 if half {
629 return if diff & 1 != 0 {
630 reference + ((diff + 1) >> 1)
631 } else {
632 reference - (diff >> 1)
633 };
634 }
635 if 2 * reference < max { diff } else { max - (diff + 1) }
636}
637
638/// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current
639/// frame's already-decoded above/left/above-left neighbours.
640fn spatial_seg_pred(mi_r: usize, mi_c: usize) -> (i32, usize) {
641 let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());
642 let (avail_u, avail_l) = (mi_r > row0, mi_c > col0);
643 let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1)));
644 let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c)));
645 let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1)));
646 let ctx = match prev_ul {
647 None => 0,
648 Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2,
649 Some(ul) if Some(ul) == prev_u || Some(ul) == prev_l || prev_u == prev_l => 1,
650 Some(_) => 0,
651 };
652 let pred = match (prev_u, prev_l) {
653 (None, l) => l.unwrap_or(0),
654 (Some(u), None) => u,
655 (Some(u), Some(l)) => {
656 if prev_ul == Some(u) {
657 u
658 } else {
659 l
660 }
661 }
662 };
663 (pred, ctx)
664}
665
666/// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id
667/// when `skip`, otherwise one `segment_id` symbol de-interleaved against
668/// that prediction. Does NOT write the map -- callers do.
669fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, skip: bool) -> u8 {
670 let (pred, ctx) = spatial_seg_pred(mi_r, mi_c);
671 if skip {
672 return pred as u8;
673 }
674 let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32;
675 SEG_ID_HITS.with(|c| c.set(c.get() + 1));
676 let last_active = SEG.with(|s| i32::from(s.borrow().last_active_seg_id));
677 neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active) as u8
678}
679
680/// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block
681/// -- once before `skip` when `SegIdPreSkip`, once after it otherwise (the
682/// caller decides which by passing `pre_skip`).
683fn intra_segment_id(
684 dec: &mut SymbolDecoder,
685 cdfs: &mut Cdfs,
686 mi_r: usize,
687 mi_c: usize,
688 w_mi: usize,
689 h_mi: usize,
690 skip: bool,
691) {
692 if !SEG.with(|s| s.borrow().enabled) {
693 return;
694 }
695 let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip);
696 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
697}
698
699/// Whether this frame's intra blocks read their `segment_id` before `skip`
700/// (`SegIdPreSkip`); `false` also when segmentation is off.
701fn seg_id_pre_skip() -> bool {
702 SEG.with(|s| {
703 let s = s.borrow();
704 s.enabled && s.seg_id_pre_skip
705 })
706}
707
708/// `read_inter_segment_id(preskip)` (spec 5.11.9, libaom `decodemv.c:352`).
709/// Called at both spec positions of an inter frame's block: `pre_skip = true`
710/// before `skip_mode`/`skip`, and `pre_skip = false` after them.
711fn inter_segment_id(
712 dec: &mut SymbolDecoder,
713 cdfs: &mut Cdfs,
714 mi_r: usize,
715 mi_c: usize,
716 w_mi: usize,
717 h_mi: usize,
718 skip: bool,
719 pre_skip: bool,
720) {
721 let (enabled, update_map, temporal_update, pre_skip_frame) = SEG.with(|s| {
722 let s = s.borrow();
723 (s.enabled, s.update_map, s.temporal_update, s.seg_id_pre_skip)
724 });
725 if !enabled {
726 return;
727 }
728 if !update_map {
729 // The map is inherited wholesale from the previous frame.
730 let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi);
731 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
732 return;
733 }
734 if pre_skip && !pre_skip_frame {
735 return;
736 }
737 if !pre_skip && skip {
738 // libaom: a skipped block never codes `seg_id_predicted`, and its
739 // segment id is the spatial prediction.
740 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0);
741 let id = read_segment_id(dec, cdfs, mi_r, mi_c, true);
742 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
743 return;
744 }
745 let id = if temporal_update {
746 let ctx = seg_pred_ctx(mi_r, mi_c);
747 let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0;
748 SEG_PRED_HITS.with(|c| c.set(c.get() + 1));
749 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted));
750 if predicted {
751 predicted_segment_id(mi_r, mi_c, w_mi, h_mi)
752 } else {
753 read_segment_id(dec, cdfs, mi_r, mi_c, false)
754 }
755 } else {
756 read_segment_id(dec, cdfs, mi_r, mi_c, false)
757 };
758 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
759}
760
761/// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags.
762fn seg_pred_ctx(mi_r: usize, mi_c: usize) -> usize {
763 // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and
764 // so contribute 0) outside the tile -- the availability check here is
765 // what keeps a previous tile's stamps out of this tile's context.
766 let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());
767 let above = if mi_r > row0 {
768 ABOVE_SEG_PRED.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))
769 } else {
770 0
771 };
772 let left = if mi_c > col0 {
773 LEFT_SEG_PRED.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))
774 } else {
775 0
776 };
777 usize::from(above + left)
778}
779
780/// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update.
781fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8) {
782 ABOVE_SEG_PRED.with(|m| {
783 let mut m = m.borrow_mut();
784 for i in 0..w_mi {
785 if let Some(cell) = m.get_mut(mi_c + i) {
786 *cell = value;
787 }
788 }
789 });
790 LEFT_SEG_PRED.with(|m| {
791 let mut m = m.borrow_mut();
792 for i in 0..h_mi {
793 if let Some(cell) = m.get_mut(mi_r + i) {
794 *cell = value;
795 }
796 }
797 });
798}
799
800// How many key-frame luma blocks resolved `smooth_neighbor` (spec
801// `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after
802// counter, proving a stream actually put a directional block next to a
803// smooth-predicted neighbour rather than every block reading the (previously
804// hardcoded `false`) edge-filter strength bucket unchanged.
805thread_local! {
806 static SMOOTH_LUMA_HITS: std::cell::Cell<usize> =
807 const { std::cell::Cell::new(0) };
808}
809
810/// Current value of [`SMOOTH_LUMA_HITS`].
811pub(crate) fn smooth_luma_hits() -> usize {
812 SMOOTH_LUMA_HITS.with(|c| c.get())
813}
814
815thread_local! {
816 /// lane-band46 r1: how many split-transform units answered their intra
817 /// reach DIFFERENTLY under libaom's per-unit rules ([`Reach::of_tu`], the
818 /// palette2 r12 fix) than the standalone-block lookup this decoder used to
819 /// apply to them (class reach-is-per-transform-unit). Every hit is a
820 /// transform unit whose above-right / below-left reference samples would
821 /// be wrong without that fix.
822 static SPLIT_TU_REACH_FIX_HITS: std::cell::Cell<usize> =
823 const { std::cell::Cell::new(0) };
824}
825
826/// Current value of [`SPLIT_TU_REACH_FIX_HITS`].
827pub(crate) fn split_tu_reach_fix_hits() -> usize {
828 SPLIT_TU_REACH_FIX_HITS.with(|c| c.get())
829}
830
831/// [`Reach::of_tu`] for one transform unit, counting how often that per-unit
832/// answer differs from the standalone-block answer the call sites used before
833/// lane-palette2 r12 -- the counter a gate asserts on to prove a stream really
834/// exercised the fix. `col_off`/`row_off` are in SAMPLES from the parent
835/// block's top-left `(px, py)`.
836#[allow(clippy::too_many_arguments)]
837fn tu_reach(
838 bw: usize,
839 bh: usize,
840 col_off: usize,
841 row_off: usize,
842 tx: usize,
843 block: Reach,
844 px: usize,
845 py: usize,
846 width: usize,
847 height: usize,
848) -> Reach {
849 let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block);
850 let standalone = Reach::of(tx, px + col_off, py + row_off, width, height);
851 if fixed != standalone {
852 SPLIT_TU_REACH_FIX_HITS.with(|c| c.set(c.get() + 1));
853 }
854 fixed
855}
856
857// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12),
858// across every call on the current thread -- lane-chroma r3's own before/after
859// counter, proving a stream actually exercised chroma's smooth/paeth
860// predictor (the previously-refused round-2 gap) rather than every block
861// landing on DC/CFL/directional.
862thread_local! {
863 static SMOOTH_UV_HITS: std::cell::Cell<usize> =
864 const { std::cell::Cell::new(0) };
865}
866
867/// Current value of [`SMOOTH_UV_HITS`].
868pub(crate) fn smooth_uv_hits() -> usize {
869 SMOOTH_UV_HITS.with(|c| c.get())
870}
871
872// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a
873// full superblock walk over, across every call on the current thread --
874// lane-tiles r2's own gate-blind-to-feature guard: a gate over a
875// multi-tile stream must prove more than one tile actually fired, not just
876// that the stream carried tile_info.cols > 1.
877thread_local! {
878 static TILE_HITS: std::cell::Cell<usize> =
879 const { std::cell::Cell::new(0) };
880}
881/// Current value of [`TILE_HITS`].
882pub(crate) fn tile_hits() -> usize {
883 TILE_HITS.with(|c| c.get())
884}
885
886// How many 4-pixel deblocking edge groups [`edge_params`] has actually
887// selected for filtering, across every call on the current thread -- the same
888// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
889// exercised `apply_deblock` rather than every edge landing on level 0.
890thread_local! {
891 static DEBLOCK_HITS: std::cell::Cell<usize> =
892 const { std::cell::Cell::new(0) };
893}
894/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
895/// mirroring stream.rs's `pictures_decoded` so the two dumps index
896/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
897static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize =
898 std::sync::atomic::AtomicUsize::new(0);
899
900/// Current value of [`DEBLOCK_HITS`].
901pub(crate) fn deblock_hits() -> usize {
902 DEBLOCK_HITS.with(|c| c.get())
903}
904
905// lane-defon r1: how many COMPOUND_REFERENCE blocks read a
906// `UNIDIR_COMP_REFERENCE` pair (both references on the same temporal side,
907// spec 5.11.25 `comp_reference_type == 0`) -- the gate's proof that a
908// stream built with `--enable-onesided-comp=1` really exercised the
909// `uni_comp_ref` alphabet rather than only bidirectional pairs.
910thread_local! {
911 static UNI_COMP_HITS: std::cell::Cell<usize> =
912 const { std::cell::Cell::new(0) };
913}
914
915/// Current value of [`UNI_COMP_HITS`].
916pub(crate) fn uni_comp_hits() -> usize {
917 UNI_COMP_HITS.with(|c| c.get())
918}
919
920// lane-defon r1: how many blocks blended through a `COMPOUND_DIFFWTD` mask
921// (`mc::diffwtd_mask`) -- the narrower half of `MASKED_COMPOUND_HITS`, the
922// gate's proof that `--enable-diff-wtd-comp=1` reached the difference-weighted
923// blend and not only the wedge arm.
924thread_local! {
925 static DIFFWTD_HITS: std::cell::Cell<usize> =
926 const { std::cell::Cell::new(0) };
927}
928
929/// Current value of [`DIFFWTD_HITS`].
930pub(crate) fn diffwtd_hits() -> usize {
931 DIFFWTD_HITS.with(|c| c.get())
932}
933
934// lane-mcomp64 r1: how many blocks took the INFERRED `COMPOUND_DIFFWTD` arm --
935// a block size where `av1_is_wedge_used` is false (64x64 is the only such size
936// this decoder's square inter path reaches), so no `compound_type` symbol is
937// coded at all. Strictly narrower than `DIFFWTD_HITS`, which also counts the
938// coded-symbol DIFFWTD blocks at 8x8/16x16/32x32.
939thread_local! {
940 static DIFFWTD_INFERRED_HITS: std::cell::Cell<usize> =
941 const { std::cell::Cell::new(0) };
942}
943
944/// Current value of [`DIFFWTD_INFERRED_HITS`].
945pub(crate) fn diffwtd_inferred_hits() -> usize {
946 DIFFWTD_INFERRED_HITS.with(|c| c.get())
947}
948
949// lane-defon r1: how many FORWARD KEYFRAMES were decoded -- a KEY frame coded
950// with `show_frame == 0`, output later by a `show_existing_frame` header
951// (aomenc `--enable-fwd-kf=1 --fwd-kf-dist=N`). Counted from
952// `stream::decode_stream`, which is where the frame header is consumed; the
953// gate's proof that the on-value really reached the bitstream rather than
954// being dropped by the rate control.
955thread_local! {
956 static FWD_KF_HITS: std::cell::Cell<usize> =
957 const { std::cell::Cell::new(0) };
958}
959
960/// Current value of [`FWD_KF_HITS`].
961pub(crate) fn fwd_kf_hits() -> usize {
962 FWD_KF_HITS.with(|c| c.get())
963}
964
965/// Records one decoded forward keyframe (see [`FWD_KF_HITS`]).
966pub(crate) fn note_fwd_kf() {
967 FWD_KF_HITS.with(|c| c.set(c.get() + 1));
968}
969
970// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
971// the block's own side, across every call on the current thread -- the same
972// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
973// actually exercised a *split* transform under `TxMode::Select` rather than
974// every block coincidentally resolving `depth=0` (indistinguishable from
975// `TxMode::Largest` pixel-wise).
976thread_local! {
977 static TX_DEPTH_HITS: std::cell::Cell<usize> =
978 const { std::cell::Cell::new(0) };
979}
980
981// How many plain SQUARE intra blocks (lane-sqchroma r1) resolved a luma
982// transform smaller than their own side (`tx_depth != 0`) while coding a
983// chroma prediction other than `DC_PRED` -- the pair the square path's chroma
984// only exercises with aomenc's tx-size search left ON (its default), which
985// every older recipe in this file pins off. Counted at the block, so a stream
986// where RD happened to give every split-transform block a DC chroma mode
987// reads as zero rather than silently passing for free.
988thread_local! {
989 static SQ_CHROMA_TX_HITS: std::cell::Cell<usize> =
990 const { std::cell::Cell::new(0) };
991}
992
993/// Current value of [`SQ_CHROMA_TX_HITS`].
994pub(crate) fn sq_chroma_tx_hits() -> usize {
995 SQ_CHROMA_TX_HITS.with(|c| c.get())
996}
997
998/// Current value of [`TX_DEPTH_HITS`].
999pub(crate) fn tx_depth_hits() -> usize {
1000 TX_DEPTH_HITS.with(|c| c.get())
1001}
1002
1003// lane-txselect: how many `txfm_split` symbols an inter frame's var-tx tree
1004// read, and how many of those actually took the split, on the current thread
1005// -- the same before/after counter pattern as [`TX_DEPTH_HITS`], proving a
1006// stream exercised spec 5.11.17's `read_var_tx_size` rather than every block
1007// coincidentally coding one whole-block transform.
1008thread_local! {
1009 static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1010 static TXFM_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1011 // lane-inter4 r2: rectangular INTER residual coding -- how many rect
1012 // strips coded one whole-block rect transform unit, and how many split
1013 // their rect max transform into square sub-transforms.
1014 static RECT_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1015 static RECT_INTER_TXSPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1016 // lane-r14 r2: luma transform units of an inter strip with a 64-px axis
1017 // (64x32/32x64/64x16/16x64), whose coefficients are coded as the
1018 // truncated low-32 corner.
1019 static RECT64_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1020 // lane-r14 r3: rectangular var-tx LEAVES, [32x16, 16x32].
1021 static VARTX_RECT_LEAF_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1022 // lane-inter16ab r4: rectangular var-tx leaves with a 4-px axis, [8x4, 4x8]
1023 // -- the `sub_tx_size_map[TX_16X4]` split leaves of a 16x16-level 1:4 strip.
1024 static VARTX_RECT_LEAF4_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1025 // lane-inter4 r3: 16x16-level PARTITION_HORZ / PARTITION_VERT on an inter
1026 // frame -- 16x8 and 8x16 inter leaves.
1027 static INTER_LEAF16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1028 static INTER_LEAF16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1029 // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits,
1030 // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] --
1031 // `decode_inter_block` already carries forty parameters and both are
1032 // frame-constant.
1033 static TX_SELECT_INTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1034 static REDUCED_TX_SET_INTER: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
1035 // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit,
1036 // frame-constant like the two above and stashed the same way -- an intra
1037 // block inside an inter frame reads `use_filter_intra` under it.
1038 static ENABLE_FILTER_INTRA_INTER: std::cell::Cell<bool> =
1039 const { std::cell::Cell::new(false) };
1040}
1041
1042/// Current value of [`TXFM_SPLIT_READS`].
1043pub(crate) fn txfm_split_reads() -> usize {
1044 TXFM_SPLIT_READS.with(|c| c.get())
1045}
1046
1047/// Current value of [`TXFM_SPLIT_HITS`].
1048pub(crate) fn txfm_split_hits() -> usize {
1049 TXFM_SPLIT_HITS.with(|c| c.get())
1050}
1051
1052/// Current value of [`INTER_LEAF16_HORZ_HITS`] (lane-inter4 r3).
1053pub(crate) fn inter_leaf16_horz_hits() -> usize {
1054 INTER_LEAF16_HORZ_HITS.with(|c| c.get())
1055}
1056
1057/// Current value of [`INTER_LEAF16_VERT_HITS`] (lane-inter4 r3).
1058pub(crate) fn inter_leaf16_vert_hits() -> usize {
1059 INTER_LEAF16_VERT_HITS.with(|c| c.get())
1060}
1061
1062/// Current value of [`RECT_INTER_TU_HITS`] (lane-inter4 r2).
1063pub(crate) fn rect_inter_tu_hits() -> usize {
1064 RECT_INTER_TU_HITS.with(|c| c.get())
1065}
1066
1067/// Current value of [`RECT_INTER_TXSPLIT_HITS`] (lane-inter4 r2).
1068pub(crate) fn rect_inter_txsplit_hits() -> usize {
1069 RECT_INTER_TXSPLIT_HITS.with(|c| c.get())
1070}
1071
1072/// Current value of [`RECT64_INTER_TU_HITS`] (lane-r14 r2).
1073pub(crate) fn rect64_inter_tu_hits() -> usize {
1074 RECT64_INTER_TU_HITS.with(|c| c.get())
1075}
1076
1077/// Current value of [`VARTX_RECT_LEAF_HITS`] (lane-r14 r3): how many
1078/// rectangular var-tx leaf transform units were coded, `[32x16, 16x32]`.
1079pub(crate) fn vartx_rect_leaf_hits() -> [usize; 2] {
1080 VARTX_RECT_LEAF_HITS.with(|c| c.get())
1081}
1082
1083/// Current value of [`VARTX_RECT_LEAF4_HITS`] (lane-inter16ab r4): 8x4/4x8
1084/// split leaves of a 16x4/4x16 strip, `[8x4, 4x8]`.
1085pub(crate) fn vartx_rect_leaf4_hits() -> [usize; 2] {
1086 VARTX_RECT_LEAF4_HITS.with(|c| c.get())
1087}
1088
1089/// Records one rectangular var-tx leaf.
1090fn vartx_rect_leaf_hit(tw: usize, th: usize) {
1091 let cell = if tw.min(th) == 4 { &VARTX_RECT_LEAF4_HITS } else { &VARTX_RECT_LEAF_HITS };
1092 cell.with(|c| {
1093 let mut h = c.get();
1094 h[usize::from(th > tw)] += 1;
1095 c.set(h);
1096 });
1097}
1098
1099/// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/
1100/// [`ENABLE_FILTER_INTRA_INTER`].
1101pub(crate) fn set_inter_tx_mode(
1102 tx_select: bool,
1103 reduced_tx_set: bool,
1104 enable_filter_intra: bool,
1105) {
1106 TX_SELECT_INTER.with(|c| c.set(tx_select));
1107 REDUCED_TX_SET_INTER.with(|c| c.set(reduced_tx_set));
1108 ENABLE_FILTER_INTRA_INTER.with(|c| c.set(enable_filter_intra));
1109}
1110
1111// How many `partition_w16` reads (a 16x16 block's own partition symbol, key
1112// intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a
1113// plain default-settings aomenc run over lavfi mandelbrot hits this arm on
1114// frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not
1115// the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real
1116// `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`,
1117// chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8
1118// path above).
1119thread_local! {
1120 static VERT_B_INTRA_HITS: std::cell::Cell<usize> =
1121 const { std::cell::Cell::new(0) };
1122}
1123
1124/// Current value of [`VERT_B_INTRA_HITS`].
1125pub(crate) fn vert_b_intra_hits() -> usize {
1126 VERT_B_INTRA_HITS.with(|c| c.get())
1127}
1128
1129// lane-ab16 r1: how many 16x16-level AB partitions fired, per arm, in
1130// `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order. Each arm is two
1131// 8x8 squares (`decode_leaf8`) plus one 16x8/8x16 strip (`decode_leaf_rect`,
1132// the non-skip coefficient path lane-rectx proved); the gate hard-asserts
1133// every arm separately so a run where aomenc's RD only picked one cannot
1134// pass as proof of four.
1135thread_local! {
1136 static AB16_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
1137}
1138
1139/// [`AB16_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16).
1140thread_local! {
1141 /// 4x4 transform units decoded inside an 8x8 square of a
1142 /// `PARTITION_VERT_A`/`_B` -- the exact call that panicked before
1143 /// [`crate::encode::Reach::of_tu`] (lane-ab16 r2), so the gate can prove
1144 /// a real `--enable-tx-size-search=1` stream reaches it.
1145 static VERT_AB_TX4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1146}
1147
1148pub(crate) fn vert_ab_tx4_hits() -> usize {
1149 VERT_AB_TX4_HITS.with(std::cell::Cell::get)
1150}
1151
1152pub(crate) fn ab16_hits_by_arm() -> [usize; 4] {
1153 AB16_HITS.with(std::cell::Cell::get)
1154}
1155
1156fn bump_ab16(arm: usize) {
1157 AB16_HITS.with(|c| {
1158 let mut v = c.get();
1159 v[arm] += 1;
1160 c.set(v);
1161 });
1162}
1163
1164// How many `partition_w16` reads resolved to a plain `PARTITION_HORZ`/
1165// `PARTITION_VERT` (lane-rect16 r2): re-measuring after the VERT_B fix above
1166// showed mandelbrot's real first-hit blocker is this plain arm at mi=(0,7),
1167// not VERT_B (`refusal-names-a-correlate`; the VERT_B write-up's "frame 0's
1168// very first non-NONE/SPLIT symbol" claim was about decode ORDER within one
1169// superblock's z-order recursion, not raster mi position).
1170thread_local! {
1171 static HORZ_VERT_INTRA_HITS: std::cell::Cell<usize> =
1172 const { std::cell::Cell::new(0) };
1173}
1174
1175/// Current value of [`HORZ_VERT_INTRA_HITS`].
1176pub(crate) fn horz_vert_intra_hits() -> usize {
1177 HORZ_VERT_INTRA_HITS.with(|c| c.get())
1178}
1179
1180// How many blocks were decoded as a frame-edge rect strip -- the single
1181// coded half of a `PARTITION_HORZ`/`PARTITION_VERT` at the true frame edge
1182// (lane-oddh r1), i.e. a block living inside the 8px band of a frame whose
1183// height or width is 8 mod 16 (the user's 3840x1608 film). Intra and inter
1184// paths share the counter.
1185thread_local! {
1186 static EDGE_RECT_STRIP_HITS: std::cell::Cell<usize> =
1187 const { std::cell::Cell::new(0) };
1188}
1189
1190/// Current value of [`EDGE_RECT_STRIP_HITS`].
1191pub(crate) fn edge_rect_strip_hits() -> usize {
1192 EDGE_RECT_STRIP_HITS.with(|c| c.get())
1193}
1194
1195// How many HORZ/VERT intra strips resolved a SPLIT luma transform
1196// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) --
1197// the case every rect path here refused by name before, and the first
1198// refusal the user's ReelB extract (600s in) stops at.
1199thread_local! {
1200 static RECT_SPLIT_TX_HITS: std::cell::Cell<usize> =
1201 const { std::cell::Cell::new(0) };
1202}
1203
1204/// Current value of [`RECT_SPLIT_TX_HITS`].
1205pub(crate) fn rect_split_tx_hits() -> usize {
1206 RECT_SPLIT_TX_HITS.with(|c| c.get())
1207}
1208
1209// The subset of [`RECT_SPLIT_TX_HITS`] that is BOTH superblock-level (one
1210// side 64) AND split past the first depth, i.e. tiled more than one unit in
1211// each axis -- the only shape with a transform unit that has neighbours on
1212// two sides inside its own strip (`row_off > 0 && col_off > 0`), and the one
1213// no gate fired before lane-rectsplit r2 (the shared counter above also
1214// counts 32x32-level and depth-1 strips, so it cannot prove this case).
1215thread_local! {
1216 static RECT_SPLIT_SB_INTERIOR_TU_HITS: std::cell::Cell<usize> =
1217 const { std::cell::Cell::new(0) };
1218}
1219
1220/// Current value of [`RECT_SPLIT_SB_INTERIOR_TU_HITS`].
1221pub(crate) fn rect_split_sb_interior_tu_hits() -> usize {
1222 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.get())
1223}
1224
1225// Per-shape hit counts for the rect chroma transforms lane-rectchroma r1
1226// wired into [`decode_rect_split`] -- the shapes a split-transform strip's
1227// chroma half takes that had no coefficient tables before (index order:
1228// 32x8, 8x32, 8x4, 4x8). One counter per shape because a gate that only
1229// proves the pair it happens to hit cannot catch a transposed scan/context
1230// table (class scan-weights-cross-axis).
1231thread_local! {
1232 static RECT_SPLIT_CHROMA_SHAPE_HITS: std::cell::Cell<[usize; 4]> =
1233 const { std::cell::Cell::new([0; 4]) };
1234}
1235
1236/// Current value of [`RECT_SPLIT_CHROMA_SHAPE_HITS`] (32x8, 8x32, 8x4, 4x8).
1237pub(crate) fn rect_split_chroma_shape_hits() -> [usize; 4] {
1238 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| c.get())
1239}
1240
1241// How many HORZ/VERT intra strips actually predicted with filter intra
1242// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name
1243// ("this decoder predicts square-only") until `predict_filter_intra` took
1244// `bw`x`bh`.
1245thread_local! {
1246 static FILTER_INTRA_RECT_HITS: std::cell::Cell<usize> =
1247 const { std::cell::Cell::new(0) };
1248}
1249
1250/// Current value of [`FILTER_INTRA_RECT_HITS`].
1251pub(crate) fn filter_intra_rect_hits() -> usize {
1252 FILTER_INTRA_RECT_HITS.with(|c| c.get())
1253}
1254
1255// As [`FILTER_INTRA_RECT_HITS`], counting only the 32x32-level 1:4 strips
1256// (32x8/8x32, lane-fi32x8 r1) -- the shapes whose `use_filter_intra` symbol
1257// was never read at all before that round, so a gate needs to prove the flag
1258// fired at THAT shape and not at a 16x8 one somewhere else in the frame.
1259// Split by ORIENTATION: rows 8 (32x8) and 9 (8x32) of `cdf::FILTER_INTRA`
1260// carry different probabilities (18101 vs 20229), so a transposed pair is
1261// only caught by a gate that sees the flag fire on BOTH shapes (class
1262// scan-weights-cross-axis).
1263thread_local! {
1264 static FILTER_INTRA_RECT4_HORZ_HITS: std::cell::Cell<usize> =
1265 const { std::cell::Cell::new(0) };
1266 static FILTER_INTRA_RECT4_VERT_HITS: std::cell::Cell<usize> =
1267 const { std::cell::Cell::new(0) };
1268}
1269
1270/// Current value of [`FILTER_INTRA_RECT4_HORZ_HITS`] (32x8 strips).
1271pub(crate) fn filter_intra_rect4_horz_hits() -> usize {
1272 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.get())
1273}
1274
1275/// Current value of [`FILTER_INTRA_RECT4_VERT_HITS`] (8x32 strips).
1276pub(crate) fn filter_intra_rect4_vert_hits() -> usize {
1277 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.get())
1278}
1279
1280// How many rectangular transform units actually coded coefficients through
1281// [`read_coeffs_rect`] (`all_zero == 0`) -- lane-rect1d's measure that a gate
1282// exercised the rect coefficient reader at all rather than passing on
1283// all-skip blocks.
1284thread_local! {
1285 static RECT_COEFF_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1286 static RECT_CLASS1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1287}
1288
1289/// Current value of [`RECT_COEFF_TU_HITS`].
1290pub(crate) fn rect_coeff_tu_hits() -> usize {
1291 RECT_COEFF_TU_HITS.with(|c| c.get())
1292}
1293
1294/// Rectangular transform units whose resolved `tx_type` is a 1D class
1295/// (`V_DCT`/`H_DCT`) -- [`TX_CLASS1_HITS`]'s rect-only half, so a gate can
1296/// pin that the 1D-class-on-a-RECT-transform path fired rather than settling
1297/// for the square reader's own 1D types.
1298pub(crate) fn rect_class1_hits() -> usize {
1299 RECT_CLASS1_HITS.with(|c| c.get())
1300}
1301
1302// As [`FILTER_INTRA_RECT_HITS`], counting only the strips BELOW 16x16
1303// (8x16/16x8 leaves of a 16x16 HORZ/VERT partition, lane-fistrip r1) -- the
1304// shapes whose `use_filter_intra` symbol had no CDF class before this round.
1305// A gate asserting the wider counter would be satisfied by a 32x16 strip and
1306// prove nothing about the new shapes.
1307thread_local! {
1308 static FILTER_INTRA_RECT_SUB16_HITS: std::cell::Cell<usize> =
1309 const { std::cell::Cell::new(0) };
1310}
1311
1312/// Current value of [`FILTER_INTRA_RECT_SUB16_HITS`].
1313pub(crate) fn filter_intra_rect_sub16_hits() -> usize {
1314 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.get())
1315}
1316
1317// As [`FILTER_INTRA_RECT_SUB16_HITS`], one partition level further down:
1318// 4x8/8x4 leaves of an 8x8 HORZ/VERT (lane-fi8 r1). A gate on the sub16
1319// counter would be satisfied by a 16x8 strip and prove nothing here.
1320thread_local! {
1321 static FILTER_INTRA_RECT_SUB8_HITS: std::cell::Cell<usize> =
1322 const { std::cell::Cell::new(0) };
1323}
1324
1325/// Current value of [`FILTER_INTRA_RECT_SUB8_HITS`].
1326pub(crate) fn filter_intra_rect_sub8_hits() -> usize {
1327 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.get())
1328}
1329
1330// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
1331// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
1332// call on the current thread -- the same before/after counter pattern as
1333// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
1334// `eob_pt`/1D-neighbour context path rather than every block coincidentally
1335// landing on `DCT_DCT`.
1336thread_local! {
1337 static TX_CLASS1_HITS: std::cell::Cell<usize> =
1338 const { std::cell::Cell::new(0) };
1339}
1340
1341// How many `uv_mode` reads resolved to a directional chroma mode (neither
1342// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
1343// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1344// actually exercised chroma's own directional predictor.
1345thread_local! {
1346 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
1347 const { std::cell::Cell::new(0) };
1348}
1349
1350/// Current value of [`DIRECTIONAL_UV_HITS`].
1351pub(crate) fn directional_uv_hits() -> usize {
1352 DIRECTIONAL_UV_HITS.with(|c| c.get())
1353}
1354
1355// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
1356// something other than [`ANGLE_DELTA_ZERO`], across every call in the
1357// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
1358// proving a stream actually exercised a nonzero angle delta.
1359thread_local! {
1360 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
1361 const { std::cell::Cell::new(0) };
1362}
1363
1364// How many [`read_single_ref`] reads resolved to a reference other than
1365// `LAST_FRAME`, across every call on the current thread -- the same before/after
1366// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1367// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
1368// only other supported one so far) rather than every block coincidentally
1369// resolving `LAST_FRAME`.
1370thread_local! {
1371 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
1372 const { std::cell::Cell::new(0) };
1373}
1374
1375/// Current value of [`NON_LAST_REF_HITS`].
1376pub(crate) fn non_last_ref_hits() -> usize {
1377 NON_LAST_REF_HITS.with(|c| c.get())
1378}
1379
1380// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
1381// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
1382// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
1383// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
1384// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
1385// `GOLDEN_FRAME` draw it did not ask for.
1386thread_local! {
1387 static LAST2_HITS: std::cell::Cell<usize> =
1388 const { std::cell::Cell::new(0) };
1389}
1390thread_local! {
1391 static LAST3_HITS: std::cell::Cell<usize> =
1392 const { std::cell::Cell::new(0) };
1393}
1394thread_local! {
1395 static GOLDEN_HITS: std::cell::Cell<usize> =
1396 const { std::cell::Cell::new(0) };
1397}
1398thread_local! {
1399 static BWDREF_HITS: std::cell::Cell<usize> =
1400 const { std::cell::Cell::new(0) };
1401}
1402thread_local! {
1403 static ALTREF2_HITS: std::cell::Cell<usize> =
1404 const { std::cell::Cell::new(0) };
1405}
1406thread_local! {
1407 static ALTREF_HITS: std::cell::Cell<usize> =
1408 const { std::cell::Cell::new(0) };
1409}
1410
1411// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
1412// -- proves a `reference_select` stream actually reached a block that picked
1413// compound, not just that the header bit was set. Every such block is
1414// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
1415// so this only ever counts attempted reads, never a completed decode.
1416thread_local! {
1417 static COMP_MODE_HITS: std::cell::Cell<usize> =
1418 const { std::cell::Cell::new(0) };
1419}
1420
1421/// Current value of [`COMP_MODE_HITS`].
1422pub(crate) fn comp_mode_hits() -> usize {
1423 COMP_MODE_HITS.with(|c| c.get())
1424}
1425
1426// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
1427// use for, across every call on the current thread -- the same before/after
1428// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1429// exercised palette reconstruction rather than only reading and refusing the
1430// `palette_y_mode` symbol.
1431thread_local! {
1432 static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1433}
1434
1435/// Current value of [`PALETTE_HITS`].
1436pub(crate) fn palette_hits() -> usize {
1437 PALETTE_HITS.with(|c| c.get())
1438}
1439
1440// lane-tiles r12: of those, how many sat at their own TILE's left column --
1441// exactly the blocks whose palette cache/ctx must NOT see the previous tile's
1442// colours (`av1_get_palette_cache`'s `xd->left_mbmi == NULL`). A multi-tile
1443// palette gate that never hits one proves nothing about the tile guard.
1444thread_local! {
1445 static PALETTE_TILE_LEFT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1446}
1447
1448/// Current value of [`PALETTE_TILE_LEFT_HITS`].
1449pub(crate) fn palette_tile_left_hits() -> usize {
1450 PALETTE_TILE_LEFT_HITS.with(|c| c.get())
1451}
1452
1453// lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma
1454// palette use -- proves a stream actually reconstructed UV palette pixels,
1455// not just read and refused the `palette_uv_mode` symbol.
1456thread_local! {
1457 static PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1458}
1459
1460/// Current value of [`PALETTE_UV_HITS`].
1461pub(crate) fn palette_uv_hits() -> usize {
1462 PALETTE_UV_HITS.with(|c| c.get())
1463}
1464
1465// lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`])
1466// decoded a real palette-Y use -- proves the rect strip's own palette syntax
1467// (not just the square path's) actually fired.
1468thread_local! {
1469 static PALETTE_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1470}
1471
1472/// Current value of [`PALETTE_RECT_HITS`].
1473pub(crate) fn palette_rect_hits() -> usize {
1474 PALETTE_RECT_HITS.with(|c| c.get())
1475}
1476
1477// lane-palette2 r6: how many HORZ/VERT rect intra strips ran the
1478// [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] --
1479// i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in
1480// range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per
1481// RD, almost always refused-on-use because the block doesn't end up USING a
1482// palette -- see r5's report). This is the site the removed refusal
1483// ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it
1484// fired here whether or not the block picked a palette, so this is the
1485// counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost
1486// never observes.
1487thread_local! {
1488 static RECT_SCREEN_CONTENT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1489}
1490
1491/// Current value of [`RECT_SCREEN_CONTENT_HITS`].
1492pub(crate) fn rect_screen_content_hits() -> usize {
1493 RECT_SCREEN_CONTENT_HITS.with(|c| c.get())
1494}
1495
1496// lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a
1497// split luma transform (`logical_tx != side`) -- proves the per-TU index-map
1498// windowing actually ran, not just that the whole-block path stayed exact.
1499// Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16);
1500// first actually incremented in r7, when the refusal it guarded was lifted.
1501thread_local! {
1502 static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1503}
1504
1505thread_local! {
1506 /// lane-kf900 r4: rect intra strips that ACTUALLY use a palette -- the
1507 /// 1:4 shapes (32x8/8x32, 16x4/4x16) and the sub-16x16 2:1 leaves
1508 /// (16x8/8x16), the two shapes the lifted refusals named.
1509 static RECT4_PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1510}
1511
1512/// Current value of [`RECT4_PALETTE_HITS`].
1513pub(crate) fn rect4_palette_hits() -> usize {
1514 RECT4_PALETTE_HITS.with(|c| c.get())
1515}
1516
1517/// Current value of [`PALETTE_SPLIT_TX_HITS`].
1518pub(crate) fn palette_split_tx_hits() -> usize {
1519 PALETTE_SPLIT_TX_HITS.with(|c| c.get())
1520}
1521
1522// lane-hgkf r2: SKIPPED intra blocks whose `tx_depth` split the luma transform
1523// and which are therefore predicted one transform unit at a time (a skipped
1524// block codes no coefficients, so nothing else in the stream witnesses this
1525// path -- only the pixels do).
1526thread_local! {
1527 static SKIP_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1528}
1529
1530/// Current value of [`SKIP_SPLIT_TX_HITS`] (blocks, not units).
1531pub fn skip_split_tx_hits() -> usize {
1532 SKIP_SPLIT_TX_HITS.with(|c| c.get())
1533}
1534
1535/// Zeroes [`SKIP_SPLIT_TX_HITS`] before a gate's own decode attempt.
1536pub fn reset_skip_split_tx_hits() {
1537 SKIP_SPLIT_TX_HITS.with(|c| c.set(0));
1538}
1539
1540// lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth`
1541// symbol split their luma transform, bucketed by block side (8, 16, 32, 64) --
1542// the gate's proof that the lifted path actually ran, per size.
1543thread_local! {
1544 static INTRA_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 4]> =
1545 const { std::cell::Cell::new([0; 4]) };
1546}
1547
1548/// Current value of [`INTRA_IN_INTER_SPLIT_TX_HITS`], indexed 8/16/32/64.
1549pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] {
1550 INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
1551}
1552
1553thread_local! {
1554 /// A just-decoded palette-Y block's own predicted pixels
1555 /// (`side*side`, row-major, `colors[map[i]]`), consumed by
1556 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
1557 /// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
1558 /// per-block override through `read_plane`'s two dozen call sites is the
1559 /// alternative this avoids). Always empty again once that call consumes
1560 /// it (`.take()`), so a non-palette block's own `reconstruct` call never
1561 /// sees stale state.
1562 static PALETTE_PRED: std::cell::RefCell<Option<Vec<u16>>> =
1563 const { std::cell::RefCell::new(None) };
1564}
1565
1566
1567/// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
1568/// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a
1569/// site whose reconstruct never runs would be picked up by the NEXT block's
1570/// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
1571/// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
1572#[track_caller]
1573fn set_palette_pred(buf: Vec<u16>) {
1574 if std::env::var_os("EC_DEBUG_PAL").is_some() {
1575 let stale = PALETTE_PRED.with(|c| c.borrow().is_some());
1576 eprintln!(
1577 "PALSET len={} stale={stale} at {}",
1578 buf.len(),
1579 std::panic::Location::caller()
1580 );
1581 }
1582 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(buf));
1583}
1584
1585#[track_caller]
1586fn take_palette_pred() -> Option<Vec<u16>> {
1587 let got = PALETTE_PRED.with(|c| c.borrow_mut().take());
1588 if std::env::var_os("EC_DEBUG_PAL").is_some() {
1589 eprintln!(
1590 "PALTAKE len={:?} at {}",
1591 got.as_ref().map(Vec::len),
1592 std::panic::Location::caller()
1593 );
1594 }
1595 got
1596}
1597
1598thread_local! {
1599 /// The current frame's `mi` grid, kept only while a frame header set
1600 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
1601 /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
1602 /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
1603 /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
1604 /// does not allow intrabc (so nothing is paid for it).
1605 ///
1606 /// corner-cut: only [`decode_block`] (the square path) records into it,
1607 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
1608 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
1609 /// be wrong there; upgrade = record from the rect/leaf paths too.
1610 static INTRABC_MI_GRID: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>> =
1611 const { std::cell::RefCell::new(None) };
1612 /// The block vector [`read_intra_mode`] just decoded, handed to
1613 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
1614 /// which the alternative -- a tenth tuple member through every caller --
1615 /// already avoids). Always `.take()`n by the block that reads it.
1616 static INTRABC_DV: std::cell::Cell<Option<(i32, i32)>> = const { std::cell::Cell::new(None) };
1617 /// How many blocks decoded `use_intrabc == 1` -- the gate's hit counter.
1618 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1619}
1620
1621/// Whether this frame's header set `allow_intrabc` -- [`INTRABC_MI_GRID`] is
1622/// `Some` exactly then (set once per frame in `decode_frame`), so the flag
1623/// needs no separate plumbing to reach the rect-strip mode reader.
1624fn allow_intrabc_frame() -> bool {
1625 INTRABC_MI_GRID.with(|g| g.borrow().is_some())
1626}
1627
1628thread_local! {
1629 /// How many rect intra strips READ the `use_intrabc` symbol (i.e. how many
1630 /// times the fix below was exercised) -- the rect-strip gate's hit counter,
1631 /// distinct from [`INTRABC_HITS`] which counts blocks that USE intrabc.
1632 static RECT_INTRABC_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1633}
1634
1635/// Current value of [`RECT_INTRABC_READS`].
1636pub(crate) fn rect_intrabc_reads() -> usize {
1637 RECT_INTRABC_READS.with(|c| c.get())
1638}
1639
1640/// Zeroes [`RECT_INTRABC_READS`] (gate tests call this before a decode).
1641pub(crate) fn reset_rect_intrabc_reads() {
1642 RECT_INTRABC_READS.with(|c| c.set(0));
1643}
1644
1645/// Current value of [`INTRABC_HITS`].
1646pub(crate) fn intrabc_hits() -> usize {
1647 INTRABC_HITS.with(|c| c.get())
1648}
1649
1650/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
1651pub(crate) fn reset_intrabc_hits() {
1652 INTRABC_HITS.with(|c| c.set(0));
1653}
1654
1655/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
1656/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
1657/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
1658/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
1659fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>) {
1660 INTRABC_MI_GRID.with(|g| {
1661 let mut g = g.borrow_mut();
1662 let Some((grid, _, _)) = g.as_mut() else {
1663 return;
1664 };
1665 let info = crate::mvstack::MiInfo {
1666 is_inter: dv.is_some(),
1667 ref_frame: 0,
1668 ref_frame1: None,
1669 mv: dv.unwrap_or((0, 0)),
1670 mv1: None,
1671 is_new_mv: dv.is_some(),
1672 is_global_mv0: false,
1673 is_global_mv1: false,
1674 size: n4,
1675 size_h: n4,
1676 };
1677 for r in mi_r..mi_r + n4 {
1678 for c in mi_c..mi_c + n4 {
1679 grid.set(r, c, info);
1680 }
1681 }
1682 });
1683}
1684
1685// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
1686// proves a real `skip_mode_present` stream actually reached a block that
1687// picked it, not just that the frame header bit was set.
1688thread_local! {
1689 static SKIP_MODE_HITS: std::cell::Cell<usize> =
1690 const { std::cell::Cell::new(0) };
1691}
1692
1693/// Current value of [`SKIP_MODE_HITS`].
1694pub(crate) fn skip_mode_hits() -> usize {
1695 SKIP_MODE_HITS.with(|c| c.get())
1696}
1697
1698// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
1699// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
1700// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
1701// reached [`obmc_blend`], not just the header bit.
1702thread_local! {
1703 static OBMC_HITS: std::cell::Cell<usize> =
1704 const { std::cell::Cell::new(0) };
1705}
1706
1707// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the
1708// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled
1709// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while
1710// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have
1711// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this
1712// decoder used to read with the wrong alphabet, so a gate that asserts this
1713// counter advanced proves the fixed path fired (class
1714// `gate-blind-to-feature`).
1715thread_local! {
1716 static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1717}
1718
1719/// Current value of [`FIMV_ALPHABET_HITS`].
1720pub fn fimv_alphabet_hits() -> usize {
1721 FIMV_ALPHABET_HITS.with(|c| c.get())
1722}
1723
1724// lane-fimv r1: how many frame headers this decoder has decoded with
1725/// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate
1726// prove the encoder really produced the header state under test rather than
1727// assume it.
1728thread_local! {
1729 static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1730}
1731
1732/// Current value of [`FIMV_FRAME_HITS`].
1733pub fn fimv_frame_hits() -> usize {
1734 FIMV_FRAME_HITS.with(|c| c.get())
1735}
1736
1737/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
1738/// `force_integer_mv` bit is set.
1739pub fn note_force_integer_mv_frame() {
1740 FIMV_FRAME_HITS.with(|c| c.set(c.get() + 1));
1741}
1742
1743/// Current value of [`OBMC_HITS`].
1744pub(crate) fn obmc_hits() -> usize {
1745 OBMC_HITS.with(|c| c.get())
1746}
1747
1748// lane-scaledref r1: per-case firing counts for the scaled-reference gate
1749// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED
1750// reference would pass just as well and prove nothing, so the gate
1751// hard-asserts each combination this round lifts actually occurred:
1752// a compound block with a scaled tap, a warp block whose warp libaom
1753// suppresses because the reference is scaled, an OBMC block, an interintra
1754// block, and an 8x8 leaf.
1755thread_local! {
1756 static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1757 static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1758 static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1759 static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1760 static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1761 static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1762 static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1763}
1764
1765/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one
1766/// scaled and one unscaled tap.
1767pub(crate) fn mixed_scale_compound_hits() -> usize {
1768 MIXED_SCALE_COMPOUND_HITS.with(|c| c.get())
1769}
1770
1771/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have
1772/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf`
1773/// instead because their reference is scaled (libaom `motion_mode_allowed`,
1774/// `blockd.h:1484`).
1775pub(crate) fn scaled_warp_suppressed_hits() -> usize {
1776 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get())
1777}
1778
1779/// Current value of [`SCALED_COMPOUND_HITS`].
1780pub(crate) fn scaled_compound_hits() -> usize {
1781 SCALED_COMPOUND_HITS.with(|c| c.get())
1782}
1783
1784/// Current value of [`SCALED_WARP_FALLBACK_HITS`].
1785pub(crate) fn scaled_warp_fallback_hits() -> usize {
1786 SCALED_WARP_FALLBACK_HITS.with(|c| c.get())
1787}
1788
1789/// Current value of [`SCALED_OBMC_HITS`].
1790pub(crate) fn scaled_obmc_hits() -> usize {
1791 SCALED_OBMC_HITS.with(|c| c.get())
1792}
1793
1794/// Current value of [`SCALED_INTERINTRA_HITS`].
1795pub(crate) fn scaled_interintra_hits() -> usize {
1796 SCALED_INTERINTRA_HITS.with(|c| c.get())
1797}
1798
1799/// Current value of [`SCALED_BLOCK8_HITS`].
1800pub(crate) fn scaled_block8_hits() -> usize {
1801 SCALED_BLOCK8_HITS.with(|c| c.get())
1802}
1803
1804// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
1805// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
1806// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
1807// 8x8-leaf OBMC block apart from a 16x16+ one.
1808thread_local! {
1809 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1810}
1811
1812// lane-interp3 r1: how many inter blocks read a SWITCHABLE `interp_filter`
1813// pair whose two directions differ (`enable_dual_filter` only -- with dual
1814// filter off both directions take the single symbol, so this can never fire).
1815// A gate asserting it proves the stream really carries dual-filter blocks.
1816thread_local! {
1817 static DUAL_FILTER_DIFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1818}
1819
1820// lane-interp3 r1: how many COMPOUND 8x8 leaves read their own
1821// `read_mb_interp_filter` symbol(s) -- the read this round added (the leaf
1822// used to skip it entirely, losing a symbol and stamping the `[3, 3]`
1823// no-filter sentinel that made a neighbouring OBMC block panic).
1824thread_local! {
1825 static COMPOUND8_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1826}
1827
1828/// Current value of [`DUAL_FILTER_DIFF_HITS`].
1829pub(crate) fn dual_filter_diff_hits() -> usize {
1830 DUAL_FILTER_DIFF_HITS.with(|c| c.get())
1831}
1832
1833/// Current value of [`COMPOUND8_FILTER_HITS`].
1834pub(crate) fn compound8_filter_hits() -> usize {
1835 COMPOUND8_FILTER_HITS.with(|c| c.get())
1836}
1837
1838// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
1839// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
1840// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
1841// -- the gate's proof that a fixture really exercises the alphabet this
1842// round changed, even though the block itself still refuses (warp
1843// estimation/filter not ported).
1844thread_local! {
1845 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
1846 const { std::cell::Cell::new(0) };
1847}
1848
1849/// Current value of [`WARP_SELECTED_HITS`].
1850pub(crate) fn warp_selected_hits() -> usize {
1851 WARP_SELECTED_HITS.with(|c| c.get())
1852}
1853
1854// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one
1855// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane`
1856// into the compound intermediate) rather than translationally -- the
1857// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model
1858// really reached [`crate::warp::warp_affine_compound`].
1859thread_local! {
1860 static COMPOUND_WARP_HITS: std::cell::Cell<usize> =
1861 const { std::cell::Cell::new(0) };
1862}
1863
1864/// Current value of [`COMPOUND_WARP_HITS`].
1865pub(crate) fn compound_warp_hits() -> usize {
1866 COMPOUND_WARP_HITS.with(|c| c.get())
1867}
1868
1869// lane-interp3 r3: the same proof narrowed to the 8x8 LEAF's own compound
1870// arm ([`decode_inter_block8`]) -- that arm predicted both taps
1871// translationally until r3, so a gate needs to tell a warped 8x8 compound
1872// leaf apart from a warped 16x16+ one (both bump [`COMPOUND_WARP_HITS`]).
1873thread_local! {
1874 static COMPOUND_WARP_HITS_8: std::cell::Cell<usize> =
1875 const { std::cell::Cell::new(0) };
1876}
1877
1878/// Current value of [`COMPOUND_WARP_HITS_8`].
1879pub(crate) fn compound_warp_hits_8() -> usize {
1880 COMPOUND_WARP_HITS_8.with(|c| c.get())
1881}
1882
1883// lane-gmaffine r1: how many blocks built their prediction from a
1884// SIX-parameter (`AFFINE`) global-motion model through
1885// `crate::warp::global_warp_params` -- the gate's proof that a stream really
1886// carried an AFFINE `global_motion_params` AND that a block was predicted
1887// with it, not merely that the header parsed one.
1888thread_local! {
1889 static AFFINE_GM_HITS: std::cell::Cell<usize> =
1890 const { std::cell::Cell::new(0) };
1891}
1892
1893/// Current value of [`AFFINE_GM_HITS`].
1894pub(crate) fn affine_gm_hits() -> usize {
1895 AFFINE_GM_HITS.with(|c| c.get())
1896}
1897
1898// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves
1899// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real
1900// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented
1901// only once `find_projection` returned a usable model, unlike
1902// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates'
1903// proof that the leaf path itself fired, not the 16x16+ one.
1904thread_local! {
1905 static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1906 static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1907}
1908
1909/// Current value of [`GLOBALMV_HITS_8`].
1910pub(crate) fn globalmv_hits_8() -> usize {
1911 GLOBALMV_HITS_8.with(|c| c.get())
1912}
1913
1914/// Current value of [`WARP_HITS_8`].
1915pub(crate) fn warp_hits_8() -> usize {
1916 WARP_HITS_8.with(|c| c.get())
1917}
1918
1919// How many blocks decoded `interintra == 1` with the non-wedge blended
1920// prediction applied (lane-interintra r1) -- the gate's proof that a
1921// stream actually exercised interintra.
1922thread_local! {
1923 static INTERINTRA_HITS: std::cell::Cell<usize> =
1924 const { std::cell::Cell::new(0) };
1925}
1926
1927/// Current value of [`INTERINTRA_HITS`].
1928pub(crate) fn interintra_hits() -> usize {
1929 INTERINTRA_HITS.with(|c| c.get())
1930}
1931
1932// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
1933// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
1934// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
1935// gate fixture actually exercises this alphabet, even though the block
1936// still refuses (the mask blend itself is unported).
1937thread_local! {
1938 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
1939 const { std::cell::Cell::new(0) };
1940}
1941
1942/// Current value of [`MASKED_COMPOUND_HITS`].
1943pub(crate) fn masked_compound_hits() -> usize {
1944 MASKED_COMPOUND_HITS.with(|c| c.get())
1945}
1946
1947// lane-intersub8 r4/r5: the NON-SQUARE half of `MASKED_COMPOUND_HITS` -- a
1948// masked-compound block whose true footprint is rectangular, i.e. the case
1949// whose `compound_type`/`wedge_idx` CDF row r4 fixed (it used to read the
1950// square envelope's `BLOCK_SIZES_ALL` index). Square blocks cannot show that
1951// defect, so a gate asserting `masked_compound_hits` alone stays vacuous for it.
1952thread_local! {
1953 static RECT_MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
1954 const { std::cell::Cell::new(0) };
1955}
1956
1957/// Current value of [`RECT_MASKED_COMPOUND_HITS`].
1958pub(crate) fn rect_masked_compound_hits() -> usize {
1959 RECT_MASKED_COMPOUND_HITS.with(|c| c.get())
1960}
1961
1962// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
1963// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
1964// actually exercised the wedge blend, not just the DIFFWTD half of
1965// `MASKED_COMPOUND_HITS`.
1966thread_local! {
1967 static WEDGE_HITS: std::cell::Cell<usize> =
1968 const { std::cell::Cell::new(0) };
1969}
1970
1971/// Current value of [`WEDGE_HITS`].
1972pub(crate) fn wedge_hits() -> usize {
1973 WEDGE_HITS.with(|c| c.get())
1974}
1975
1976// How many blocks decoded a real wedge-INTERINTRA block
1977// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
1978// a gate fixture exercised the wedge blend (fixed sign 0), not just the
1979// smooth arm counted by `INTERINTRA_HITS`.
1980thread_local! {
1981 static WII_HITS: std::cell::Cell<usize> =
1982 const { std::cell::Cell::new(0) };
1983}
1984
1985/// Current value of [`WII_HITS`].
1986pub(crate) fn wii_hits() -> usize {
1987 WII_HITS.with(|c| c.get())
1988}
1989
1990// lane-sbrect10 r1: how many INTRA blocks read `uv_mode` off the 13-symbol
1991// NO-CFL alphabet *because their size excludes CFL* (libaom `is_cfl_allowed`:
1992// wide <= 32 && high <= 32). The witness that a gate stream really carries a
1993// 64-axis intra block -- the shape whose 14-symbol read desynced every inter
1994// frame carrying one.
1995thread_local! {
1996 static NOCFL_UV_MODE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1997}
1998
1999/// Current value of [`NOCFL_UV_MODE_HITS`].
2000pub(crate) fn nocfl_uv_mode_hits() -> usize {
2001 NOCFL_UV_MODE_HITS.with(|c| c.get())
2002}
2003
2004/// lane-inter16ab r5: the six RECTANGULAR wedge shapes, in this order --
2005/// the counter slots of [`RECT_WEDGE_HITS`]/[`RECT_WII_HITS`].
2006pub(crate) const RECT_WEDGE_SHAPES: [(usize, usize); 6] =
2007 [(8, 16), (16, 8), (16, 32), (32, 16), (8, 32), (32, 8)];
2008
2009fn rect_wedge_slot(bw: usize, bh: usize) -> Option<usize> {
2010 RECT_WEDGE_SHAPES.iter().position(|&s| s == (bw, bh))
2011}
2012
2013// lane-inter16ab r5: how many COMPOUND_WEDGE / wedge-INTERINTRA blocks used a
2014// RECTANGULAR codebook row (hgtw/hltw), per shape -- the gate's proof that
2015// the rect wedge masks lifted this round actually fired, not just the square
2016// ones already counted by `WEDGE_HITS`/`WII_HITS`.
2017thread_local! {
2018 static RECT_WEDGE_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
2019 static RECT_WII_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
2020}
2021
2022/// Current value of [`RECT_WEDGE_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
2023pub(crate) fn rect_wedge_hits() -> [usize; 6] {
2024 RECT_WEDGE_HITS.with(|c| c.get())
2025}
2026
2027/// Current value of [`RECT_WII_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
2028pub(crate) fn rect_wii_hits() -> [usize; 6] {
2029 RECT_WII_HITS.with(|c| c.get())
2030}
2031
2032// lane-inter4 r4: how many 16x8/8x16 INTER LEAVES actually ran the OBMC
2033// blend -- the gate's proof that `--enable-obmc=1` reached this shape (the
2034// r3 refusal's replacement: prefilt frames are bit-exact vs an instrumented
2035// aomdec, neighbour list included).
2036thread_local! {
2037 static OBMC_RECT_LEAF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2038}
2039
2040/// Current value of [`OBMC_RECT_LEAF_HITS`].
2041pub(crate) fn obmc_rect_leaf_hits() -> usize {
2042 OBMC_RECT_LEAF_HITS.with(|c| c.get())
2043}
2044
2045/// Current value of [`OBMC_HITS_8`].
2046pub(crate) fn obmc_hits_8() -> usize {
2047 OBMC_HITS_8.with(|c| c.get())
2048}
2049
2050// lane-rectgate r1: how many 32x32 quadrants actually decoded a
2051// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
2052// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
2053// `VERT_B` all still fall into the generic "a partition type this encoder
2054// never writes" refusal below) -- the gate's proof that a free-partition
2055// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
2056// coincidentally never selecting one.
2057thread_local! {
2058 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
2059 const { std::cell::Cell::new(0) };
2060}
2061
2062/// Current value of [`EXTENDED_PARTITION_HITS`].
2063pub(crate) fn extended_partition_hits() -> usize {
2064 EXTENDED_PARTITION_HITS.with(|c| c.get())
2065}
2066
2067// lane-partitions r1: how many 32x32 quadrants decoded a real
2068// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
2069// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
2070// gate's proof this round's arms actually fired.
2071thread_local! {
2072 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
2073 const { std::cell::Cell::new(0) };
2074}
2075
2076/// Current value of [`RECT_PARTITION_HITS`].
2077pub(crate) fn rect_partition_hits() -> usize {
2078 RECT_PARTITION_HITS.with(|c| c.get())
2079}
2080
2081// lane-inter8 r1: how many superblocks an inter tile coded as a single
2082// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for
2083// static content, previously a named refusal).
2084thread_local! {
2085 /// lane-sb128c r1: how many 128x128 `PARTITION_NONE` roots this INTER tile
2086 /// path decoded as one whole block (its gate's own witness).
2087 pub(crate) static INTER_SB128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2088}
2089
2090/// Current value of [`INTER_SB128_NONE_HITS`], for a gate's before/after delta.
2091pub fn inter_sb128_none_hits() -> usize {
2092 INTER_SB128_NONE_HITS.with(std::cell::Cell::get)
2093}
2094
2095thread_local! {
2096 /// lane-sb128c r3: how many INTRA-coded 128x128 blocks inside an INTER
2097 /// frame this decoder reconstructed (mu-chunk chroma, four TX_64X64 luma
2098 /// units) -- the gate's witness that the lifted refusal's case fired.
2099 pub(crate) static INTRA_128_IN_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2100}
2101
2102/// Current value of [`INTRA_128_IN_INTER_HITS`], for a gate's before/after delta.
2103pub fn intra_128_in_inter_hits() -> usize {
2104 INTRA_128_IN_INTER_HITS.with(std::cell::Cell::get)
2105}
2106
2107thread_local! {
2108 static INTER_SB_NONE_HITS: std::cell::Cell<usize> =
2109 const { std::cell::Cell::new(0) };
2110}
2111
2112/// Current value of [`INTER_SB_NONE_HITS`].
2113pub(crate) fn inter_sb_none_hits() -> usize {
2114 INTER_SB_NONE_HITS.with(|c| c.get())
2115}
2116
2117// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter
2118// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle
2119// path has always run that loop, so only this counter proves the newly-lifted
2120// alphabet value fired.
2121thread_local! {
2122 static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> =
2123 const { std::cell::Cell::new(0) };
2124}
2125
2126/// Current value of [`INTER_SUB16_SPLIT_HITS`].
2127pub(crate) fn inter_sub16_split_hits() -> usize {
2128 INTER_SUB16_SPLIT_HITS.with(|c| c.get())
2129}
2130
2131// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
2132// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
2133// rect coefficient reader itself fired, not just the strip-level partition
2134// symbol [`RECT_PARTITION_HITS`] already counts.
2135thread_local! {
2136 static RECT_COEFF_HITS: std::cell::Cell<usize> =
2137 const { std::cell::Cell::new(0) };
2138}
2139
2140/// Current value of [`RECT_COEFF_HITS`].
2141pub(crate) fn rect_coeff_hits() -> usize {
2142 RECT_COEFF_HITS.with(|c| c.get())
2143}
2144
2145// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`])
2146// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the
2147// charter's real-aomenc gate hard-asserts.
2148thread_local! {
2149 static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> =
2150 const { std::cell::Cell::new(0) };
2151}
2152
2153/// Current value of [`RECT_LEAF_COEFF_HITS`].
2154pub(crate) fn rect_leaf_coeff_hits() -> usize {
2155 RECT_LEAF_COEFF_HITS.with(|c| c.get())
2156}
2157
2158// lane-intrarect r1: how many intra-coded HORZ/VERT strips decoded on the
2159// INTER block path ([`decode_intra_rect_in_inter`]), per shape class --
2160// [0] the superblock-level 64x32/32x64, [1] 32x16/16x32, [2] 16x8/8x16.
2161// Every one of them was the named refusal "an intra-coded HORZ/VERT strip
2162// needs rectangular intra prediction" before this round.
2163thread_local! {
2164 static INTRA_RECT_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
2165 const { std::cell::Cell::new([0; 3]) };
2166}
2167
2168/// Current value of [`INTRA_RECT_IN_INTER_HITS`] for one shape class
2169/// (0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16).
2170pub(crate) fn intra_rect_strip_in_inter_hits(class: usize) -> usize {
2171 INTRA_RECT_IN_INTER_HITS.with(|c| c.get()[class])
2172}
2173
2174// lane-intra14 r1: how many intra-coded 1:4 strips decoded on the INTER
2175// block path, per shape -- [0] 64x16, [1] 16x64, [2] 32x8, [3] 8x32. Every
2176// one of them was the named refusal "an intra-coded 1:4 (or other non-2:1)
2177// rect strip on the inter block path" before this round.
2178thread_local! {
2179 static INTRA_RECT4_IN_INTER_HITS: std::cell::Cell<[usize; 4]> =
2180 const { std::cell::Cell::new([0; 4]) };
2181}
2182
2183/// Current value of [`INTRA_RECT4_IN_INTER_HITS`] for one shape
2184/// (0 = 64x16, 1 = 16x64, 2 = 32x8, 3 = 8x32).
2185pub(crate) fn intra_rect4_strip_in_inter_hits(shape: usize) -> usize {
2186 INTRA_RECT4_IN_INTER_HITS.with(|c| c.get()[shape])
2187}
2188
2189// lane-intra14 r1: set while an INTRA block of an INTER frame is decoded
2190// through one of the key-frame rect readers ([`decode_block_rect4`],
2191// [`decode_block_rect64`]). `Some((size_group, skip))` tells
2192// [`read_intra_mode_rect`] that (a) `skip`/segment id/cdef/delta-q were
2193// already read by [`decode_inter_block`] and (b) the luma mode comes off
2194// `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`,
2195// decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair.
2196thread_local! {
2197 static INTRA_IN_INTER_MODE: std::cell::Cell<Option<(usize, bool)>> =
2198 const { std::cell::Cell::new(None) };
2199}
2200
2201// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
2202// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
2203// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16
2204// slot -- i.e. how often the r5 defect would have picked the wrong CDF row.
2205thread_local! {
2206 static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
2207 const { std::cell::Cell::new(0) };
2208}
2209
2210/// Current value of [`MODE_MI_OVERRIDE_HITS`].
2211pub(crate) fn mode_mi_override_hits() -> usize {
2212 MODE_MI_OVERRIDE_HITS.with(|c| c.get())
2213}
2214
2215// lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a
2216// TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a
2217// mode from the previous tile, where libaom's `up_available`/`left_available`
2218// make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams:
2219// `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode`
2220// per superblock row in `start_row`, so the luma fallback cannot leak the way
2221// lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is
2222// the invariant that makes the coarse fallback safe.
2223thread_local! {
2224 static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell<usize> =
2225 const { std::cell::Cell::new(0) };
2226}
2227
2228/// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`].
2229pub(crate) fn mode_tile_edge_coarse_leaks() -> usize {
2230 MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get())
2231}
2232
2233// lane-cfl r1: how many times a chroma intra-edge filter-type read
2234// (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the
2235// mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the
2236// r1 defect would have filtered a chroma edge with the wrong strength.
2237thread_local! {
2238 static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
2239 const { std::cell::Cell::new(0) };
2240}
2241
2242/// Current value of [`UV_MODE_MI_OVERRIDE_HITS`].
2243pub(crate) fn uv_mode_mi_override_hits() -> usize {
2244 UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get())
2245}
2246
2247// lane-mtfix r1: how many times a chroma intra-edge filter-type read was
2248// suppressed at a TILE edge that is not a frame edge -- the above/left
2249// `uv_mode` neighbour of a block on a tile's first mi row/column lives in
2250// another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The
2251// coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per
2252// tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile
2253// above would decide this tile's chroma edge filter strength.
2254thread_local! {
2255 static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell<usize> =
2256 const { std::cell::Cell::new(0) };
2257}
2258
2259/// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`].
2260pub(crate) fn uv_tile_edge_suppressed_hits() -> usize {
2261 UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get())
2262}
2263
2264// lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs`
2265// read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block
2266// shapes the r1 chroma defect showed up on.
2267thread_local! {
2268 static CFL_BLOCK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2269 static UV_ANGLE_DELTA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2270}
2271
2272/// Current value of [`CFL_BLOCK_HITS`].
2273pub(crate) fn cfl_block_hits() -> usize {
2274 CFL_BLOCK_HITS.with(|c| c.get())
2275}
2276
2277/// Current value of [`UV_ANGLE_DELTA_HITS`].
2278pub(crate) fn uv_angle_delta_hits() -> usize {
2279 UV_ANGLE_DELTA_HITS.with(|c| c.get())
2280}
2281
2282// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
2283// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
2284// gate's proof this round's arms actually reached a real block, not just
2285// that `partition_w64` read one of those two symbol values.
2286thread_local! {
2287 static SB_RECT_HITS: std::cell::Cell<usize> =
2288 const { std::cell::Cell::new(0) };
2289}
2290
2291/// Current value of [`SB_RECT_HITS`].
2292// lane-hgkf r1: the frame-edge partition bit, one level each. Slot 0 = a
2293// 64-level gathered edge bit read as HORZ/VERT, 1 = the same bit read as
2294// SPLIT, 2/3 = the 32-level pair. A gate asserting slot 0 or 2 proves the
2295// non-SPLIT edge arm actually decoded (before this round the bit was read and
2296// thrown away, so that arm was unreachable).
2297thread_local! {
2298 static EDGE_PART_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
2299}
2300
2301/// Current value of [`EDGE_PART_HITS`].
2302pub(crate) fn edge_part_hits() -> [usize; 4] {
2303 EDGE_PART_HITS.with(|c| c.get())
2304}
2305
2306/// Reset [`EDGE_PART_HITS`] (a gate counts one stream at a time).
2307pub(crate) fn reset_edge_part_hits() {
2308 EDGE_PART_HITS.with(|c| c.set([0; 4]));
2309}
2310
2311fn bump_edge_part(slot: usize) {
2312 EDGE_PART_HITS.with(|c| {
2313 let mut h = c.get();
2314 h[slot] += 1;
2315 c.set(h);
2316 });
2317}
2318
2319pub(crate) fn sb_rect_hits() -> usize {
2320 SB_RECT_HITS.with(|c| c.get())
2321}
2322
2323// lane-golomb r2: the 32x32-level FRAME-EDGE partition. Slot 0/1 = the
2324// gathered edge bit read as 0 (HORZ/VERT) / 1 (SPLIT); slot 2 = a 32-level
2325// PARTITION_HORZ decoded with `has_rows32 == false` (only the top 32x16 half
2326// is coded), slot 3 = a PARTITION_VERT with `has_cols32 == false`. Both tile
2327// paths (intra and inter) feed the same counter.
2328//
2329// lane-golomb r3: slots 4..7 are the same four facts one level up, at the
2330// SUPERBLOCK (64x64) edge -- 4/5 = the gathered 64-level bit read as
2331// HORZ/VERT / SPLIT, 6 = a 64x32 bottom-edge strip decoded with
2332// `has_rows == false`, 7 = a 32x64 right-edge strip. Real aomenc answers a
2333// bottom-edge superblock with the 64-level HORZ (measured: 192x80 flat-band,
2334// every SB of the last row), so the 32-level slots stay 0 on that content and
2335// only these prove the arm fired.
2336thread_local! {
2337 static EDGE32_HITS: std::cell::Cell<[usize; 8]> =
2338 const { std::cell::Cell::new([0; 8]) };
2339}
2340
2341/// Current value of [`EDGE32_HITS`].
2342pub(crate) fn edge32_hits() -> [usize; 8] {
2343 EDGE32_HITS.with(|c| c.get())
2344}
2345
2346/// [`bump_edge32`] of `base + bit`, returning the bit -- the gathered edge
2347/// reads are `if`-conditions, so the counter has to ride the expression.
2348fn bump_edge32_bit(base: usize, bit: usize) -> usize {
2349 bump_edge32(base + bit.min(1));
2350 bit
2351}
2352
2353fn bump_edge32(slot: usize) {
2354 EDGE32_HITS.with(|c| {
2355 let mut h = c.get();
2356 h[slot] += 1;
2357 c.set(h)
2358 });
2359}
2360
2361// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/
2362// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64
2363// strip) fired. Real aomenc picks these at 64 even with
2364// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is
2365// the counter the gate hard-asserts.
2366thread_local! {
2367 static SB_AB_HITS: std::cell::Cell<[usize; 4]> =
2368 const { std::cell::Cell::new([0; 4]) };
2369}
2370
2371/// Current value of [`SB_AB_HITS`], summed over the four arms.
2372pub(crate) fn sb_ab_hits() -> usize {
2373 SB_AB_HITS.with(|c| c.get().iter().sum())
2374}
2375
2376/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`,
2377/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a
2378/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as
2379/// proof of all four.
2380pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] {
2381 SB_AB_HITS.with(std::cell::Cell::get)
2382}
2383
2384// lane-tx64x16: the two 1:4 superblock arms, counted per orientation --
2385// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64
2386// strips). Two counters, not one, because a gate that only proved "some 1:4
2387// strip fired" would pass on a stream that never coded the other axis, and
2388// every scan/context table this round added comes in a transposed pair.
2389thread_local! {
2390 static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2391 static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2392}
2393
2394/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded).
2395pub(crate) fn sb_rect4_horz_hits() -> usize {
2396 SB_RECT4_HORZ_HITS.with(|c| c.get())
2397}
2398
2399/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded).
2400pub(crate) fn sb_rect4_vert_hits() -> usize {
2401 SB_RECT4_VERT_HITS.with(|c| c.get())
2402}
2403
2404// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation --
2405// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32
2406// strips), the arms the ReelB mid-film extract stops at.
2407thread_local! {
2408 static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2409 static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2410 /// lane-inter4 r1: the INTER-frame twins of the two counters above --
2411 /// four 32x8 / 8x32 inter strips of a 32x32-level `PARTITION_HORZ_4` /
2412 /// `PARTITION_VERT_4`.
2413 static RECT4_32_HORZ_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2414 static RECT4_32_VERT_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2415 /// lane-inter4 r1: superblock-level inter `PARTITION_HORZ`/`PARTITION_VERT`
2416 /// strips (64x32 / 32x64) and their 1:4 pair (64x16 / 16x64).
2417 static INTER_SB_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2418 static INTER_SB_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2419 static INTER_SB_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2420 static INTER_SB_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2421}
2422
2423/// How many 32x32-level 1:4 strips actually read coefficients (non-skip):
2424/// a gate that only counted strips would pass on an all-skip stream, which
2425/// exercises none of the new scan/context tables.
2426thread_local! {
2427 static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2428}
2429
2430// lane-rectsplitx r1: 1:4 strips (32x8/8x32/64x16/16x64) decoded through the
2431// per-transform-unit split path, split by tx depth -- depth 1 is a 2:1 RECT
2432// unit (TX_16X8/TX_32X16), depth 2 a square one, and the two INTERLEAVE in
2433// every real stream, so a gate must prove both fired. `SUB16_SPLIT_HITS`
2434// counts the same for a 16x8/8x16 strip below 16x16.
2435thread_local! {
2436 static RECT4_SPLIT_DEPTH1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2437 static RECT4_SPLIT_DEPTH2_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2438 static SUB16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2439}
2440
2441/// Current values of `RECT4_SPLIT_DEPTH1_HITS` / `RECT4_SPLIT_DEPTH2_HITS`.
2442pub(crate) fn rect4_split_depth_hits() -> (usize, usize) {
2443 (
2444 RECT4_SPLIT_DEPTH1_HITS.with(|c| c.get()),
2445 RECT4_SPLIT_DEPTH2_HITS.with(|c| c.get()),
2446 )
2447}
2448
2449/// Current value of `SUB16_SPLIT_HITS`.
2450pub(crate) fn sub16_split_hits() -> usize {
2451 SUB16_SPLIT_HITS.with(|c| c.get())
2452}
2453
2454/// Current value of `RECT4_COEFF_HITS`.
2455pub(crate) fn rect4_coeff_hits() -> usize {
2456 RECT4_COEFF_HITS.with(|c| c.get())
2457}
2458
2459// lane-inter16ab r1: how many 16x16-level AB partitions fired IN AN INTER
2460// frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B`
2461// order (the intra-frame counterpart is `AB16_HITS`). Each arm is two 8x8
2462// inter leaves (`decode_inter_block8`) plus one true 16x8/8x16 inter strip
2463// (`decode_inter_block` with `write_w`/`write_h`); the gate asserts every
2464// arm separately so a run whose RD only picked one cannot pass as proof of
2465// four.
2466thread_local! {
2467 static AB16_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
2468}
2469
2470/// [`AB16_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16 in an
2471/// inter frame).
2472pub fn ab16_inter_hits_by_arm() -> [usize; 4] {
2473 AB16_INTER_HITS.with(std::cell::Cell::get)
2474}
2475
2476// lane-inter16ab r2: the 16x16-level 1:4 pair as INTER blocks -- four 16x4
2477// (`PARTITION_HORZ_4`) or 4x16 (`PARTITION_VERT_4`) strips. `CHROMA_PAIRS`
2478// counts the odd strips that close a 4:2:0 chroma pair
2479// (`is_chroma_reference`, av1_common_int.h:1454: bh == 1 mi => odd mi_row),
2480// `SUB8_PIECES` the pair chroma blocks whose TOP (LEFT) half was built from
2481// the PREVIOUS strip's own mv/ref/filters -- libaom
2482// `build_inter_predictors_sub8x8` (reconinter_template.inc:87-160), reached
2483// through `is_sub8x8_inter` (same file, :54).
2484thread_local! {
2485 static INTER16_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2486 static INTER16_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2487 static INTER16_CHROMA_PAIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2488 static INTER16_SUB8_PIECE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2489}
2490
2491/// Current values of the inter 16x16-level 1:4 counters: `(16x4 strips, 4x16
2492/// strips, chroma pairs closed, chroma pairs built from two different
2493/// strips' motion vectors)`.
2494pub fn inter16_rect4_counters() -> (usize, usize, usize, usize) {
2495 (
2496 INTER16_HORZ4_HITS.with(std::cell::Cell::get),
2497 INTER16_VERT4_HITS.with(std::cell::Cell::get),
2498 INTER16_CHROMA_PAIR_HITS.with(std::cell::Cell::get),
2499 INTER16_SUB8_PIECE_HITS.with(std::cell::Cell::get),
2500 )
2501}
2502
2503/// One 16x4 / 4x16 inter strip's chroma situation, handed to
2504/// [`decode_inter_block`] out of band (the same one-shot thread-local idiom
2505/// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites
2506/// that all mean "an ordinary block, chroma of its own".
2507#[derive(Clone, Copy)]
2508struct InterStripChroma {
2509 /// `is_chroma_reference` for this strip: false on strips 0 and 2, which
2510 /// read and reconstruct NO chroma at all.
2511 has_chroma: bool,
2512 /// `PARTITION_HORZ_4` (16x4 strips) rather than `PARTITION_VERT_4`.
2513 horz: bool,
2514 /// The mi position of the EVEN strip of this pair -- `setup_pred_plane`'s
2515 /// `if (ss_y && (mi_row & 1) && mi_size_high[bsize] == 1) mi_row -= 1`,
2516 /// i.e. the origin of the 8x4 (4x8) chroma transform.
2517 pair_mi: (usize, usize),
2518 /// The previous (even) strip's single-reference MC parameters, `None`
2519 /// when it was intra or compound -- `is_sub8x8_inter` then returns false
2520 /// and the whole chroma block is predicted from THIS strip's mv.
2521 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
2522}
2523
2524thread_local! {
2525 static INTER_STRIP_CHROMA: std::cell::Cell<Option<InterStripChroma>> =
2526 const { std::cell::Cell::new(None) };
2527 /// The single-reference MC parameters of the inter block that decoded
2528 /// last -- read by the next 1:4 strip to build its pair's chroma.
2529 static INTER_LAST_MC: std::cell::Cell<
2530 Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
2531 > = const { std::cell::Cell::new(None) };
2532}
2533
2534fn bump_ab16_inter(arm: usize) {
2535 AB16_INTER_HITS.with(|c| {
2536 let mut v = c.get();
2537 v[arm] += 1;
2538 c.set(v);
2539 });
2540}
2541
2542// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or
2543// 4x16 (`PARTITION_VERT_4`) strips, `CHROMA` counting the odd strips that
2544// close a 4:2:0 chroma pair and `COEFF` the strips with a coded residual.
2545thread_local! {
2546 static RECT4_16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2547 static RECT4_16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2548 static RECT4_16_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2549 static RECT4_16_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2550 static RECT4_16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2551 /// lane-kf1200: pairs whose chroma edge-filter type read from the PAIR's
2552 /// base mi differs from what the strip's own (odd) mi would have said --
2553 /// the shape that made 4 chroma samples of the ReelB `-ss 1200`
2554 /// key frame miss by 1. Zero here means a gate never exercised the fix.
2555 static RECT4_16_UV_PAIR_FILT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2556 /// lane-kf1200 r2: sub-8x8 chroma blocks that are `skip_txfm` AND
2557 /// `UV_CFL_PRED` -- the arm that used to drop the CfL alpha entirely.
2558 static SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2559}
2560
2561/// How many skipped sub-8x8 chroma blocks carried a CfL alpha (the shape
2562/// that reconstructed as flat DC before lane-kf1200 r2).
2563pub fn skip_cfl_hits() -> usize {
2564 SKIP_CFL_HITS.with(|c| c.get())
2565}
2566
2567/// How many 16x4/4x16 chroma pairs took a different `intra_edge_filter_type`
2568/// from the pair's base mi than the strip's own mi would have given.
2569pub fn rect4_16_uv_pair_filt_hits() -> usize {
2570 RECT4_16_UV_PAIR_FILT_HITS.with(|c| c.get())
2571}
2572
2573// lane-reelckf r1: the two chroma defects ReelC's key frames exposed --
2574// CHROMA_SKIP_CFL counts skipped intra blocks whose chroma is `UV_CFL_PRED`
2575// (prediction still runs, libaom `predict_and_reconstruct_intra_block`), and
2576// RECT4_16_CHROMA_DIR counts 1:4 chroma pairs predicted directionally (whose
2577// intra-edge filter type must come from the chroma-reference position).
2578thread_local! {
2579 static CHROMA_SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2580 static RECT4_16_CHROMA_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2581}
2582
2583/// `(skipped UV_CFL_PRED blocks, directional 1:4 chroma pairs)` -- lane-reelckf.
2584pub fn reelc_chroma_counters() -> (usize, usize) {
2585 (
2586 CHROMA_SKIP_CFL_HITS.with(|c| c.get()),
2587 RECT4_16_CHROMA_DIR_HITS.with(|c| c.get()),
2588 )
2589}
2590
2591/// Current values of the 16x16-level 1:4 counters: `(16x4 strips, 4x16
2592/// strips, chroma-reference strips, strips with a coded residual, strips
2593/// whose luma transform is split)`.
2594pub fn rect4_16_counters() -> (usize, usize, usize, usize, usize) {
2595 (
2596 RECT4_16_HORZ_HITS.with(|c| c.get()),
2597 RECT4_16_VERT_HITS.with(|c| c.get()),
2598 RECT4_16_CHROMA_HITS.with(|c| c.get()),
2599 RECT4_16_COEFF_HITS.with(|c| c.get()),
2600 RECT4_16_SPLIT_HITS.with(|c| c.get()),
2601 )
2602}
2603
2604/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded).
2605pub(crate) fn rect4_32_horz_hits() -> usize {
2606 RECT4_32_HORZ_HITS.with(|c| c.get())
2607}
2608
2609/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded).
2610pub(crate) fn rect4_32_vert_hits() -> usize {
2611 RECT4_32_VERT_HITS.with(|c| c.get())
2612}
2613
2614/// Current value of `RECT4_32_HORZ_INTER_HITS` (32x8 inter strips decoded).
2615pub(crate) fn rect4_32_horz_inter_hits() -> usize {
2616 RECT4_32_HORZ_INTER_HITS.with(|c| c.get())
2617}
2618
2619/// Current value of `RECT4_32_VERT_INTER_HITS` (8x32 inter strips decoded).
2620pub(crate) fn rect4_32_vert_inter_hits() -> usize {
2621 RECT4_32_VERT_INTER_HITS.with(|c| c.get())
2622}
2623
2624/// Current value of `INTER_SB_HORZ_HITS` (64x32 inter strips decoded).
2625pub(crate) fn inter_sb_horz_hits() -> usize {
2626 INTER_SB_HORZ_HITS.with(|c| c.get())
2627}
2628
2629/// Current value of `INTER_SB_VERT_HITS` (32x64 inter strips decoded).
2630pub(crate) fn inter_sb_vert_hits() -> usize {
2631 INTER_SB_VERT_HITS.with(|c| c.get())
2632}
2633
2634/// Current value of `INTER_SB_HORZ4_HITS` (64x16 inter strips decoded).
2635pub(crate) fn inter_sb_horz4_hits() -> usize {
2636 INTER_SB_HORZ4_HITS.with(|c| c.get())
2637}
2638
2639/// Current value of `INTER_SB_VERT4_HITS` (16x64 inter strips decoded).
2640pub(crate) fn inter_sb_vert4_hits() -> usize {
2641 INTER_SB_VERT4_HITS.with(|c| c.get())
2642}
2643
2644// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
2645// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
2646// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
2647// just inert-compiled. Zero forever on a passing gate means that gate's
2648// stream never carries `delta_q_present=1` through a rect64 block.
2649thread_local! {
2650 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
2651 const { std::cell::Cell::new(0) };
2652}
2653
2654/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
2655pub(crate) fn rect64_qidx_drift_hits() -> usize {
2656 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
2657}
2658
2659// lane-partab r1: how many 32x32 quadrants decoded an AB partition
2660// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
2661// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
2662// free-partition gate's proof this round's arms actually fired.
2663thread_local! {
2664 static PARTAB_HITS: std::cell::Cell<usize> =
2665 const { std::cell::Cell::new(0) };
2666}
2667
2668/// Current value of [`PARTAB_HITS`].
2669pub(crate) fn partab_hits() -> usize {
2670 PARTAB_HITS.with(|c| c.get())
2671}
2672
2673// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm,
2674// one counter per arm rather than one shared total -- the gate hard-asserts
2675// each of these individually nonzero so a recipe that only ever fires
2676// HORZ_A can't silently stand in for the whole set.
2677thread_local! {
2678 static INTRA_HORZ_A_HITS: std::cell::Cell<usize> =
2679 const { std::cell::Cell::new(0) };
2680 static INTRA_HORZ_B_HITS: std::cell::Cell<usize> =
2681 const { std::cell::Cell::new(0) };
2682 static INTRA_VERT_A_HITS: std::cell::Cell<usize> =
2683 const { std::cell::Cell::new(0) };
2684 static INTRA_VERT_B_HITS: std::cell::Cell<usize> =
2685 const { std::cell::Cell::new(0) };
2686}
2687
2688/// Current value of [`INTRA_HORZ_A_HITS`].
2689pub(crate) fn intra_horz_a_hits() -> usize {
2690 INTRA_HORZ_A_HITS.with(|c| c.get())
2691}
2692/// Current value of [`INTRA_HORZ_B_HITS`].
2693pub(crate) fn intra_horz_b_hits() -> usize {
2694 INTRA_HORZ_B_HITS.with(|c| c.get())
2695}
2696/// Current value of [`INTRA_VERT_A_HITS`].
2697pub(crate) fn intra_vert_a_hits() -> usize {
2698 INTRA_VERT_A_HITS.with(|c| c.get())
2699}
2700/// Current value of [`INTRA_VERT_B_HITS`].
2701pub(crate) fn intra_vert_b_hits() -> usize {
2702 INTRA_VERT_B_HITS.with(|c| c.get())
2703}
2704
2705// How many [`read_inter_compound_mode`] reads actually happened
2706// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
2707// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
2708// mvstack build), not just that `comp_mode` fired. Still refused right
2709// after (no MV assignment or MC wired), so this only counts attempted
2710// reads.
2711thread_local! {
2712 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
2713 const { std::cell::Cell::new(0) };
2714}
2715
2716/// Current value of [`COMPOUND_MODE_HITS`].
2717pub(crate) fn compound_mode_hits() -> usize {
2718 COMPOUND_MODE_HITS.with(|c| c.get())
2719}
2720
2721/// How many query blocks folded in at least one temporal MV candidate
2722/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
2723/// temporal-MV gate's own firing counter (lane-av1tmvp).
2724///
2725/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
2726/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
2727/// this file (`decode_inter_block`) still passes `tpl: None` -- this
2728/// counter compiles and the projection math it counts is unit-tested
2729/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
2730/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
2731/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
2732/// against any real stream today. See the module doc on
2733/// `crate::motion_field` and this crate's ledger for the remaining wiring.
2734pub(crate) fn tmv_hits() -> usize {
2735 crate::mvstack::tmv_hits()
2736}
2737
2738/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
2739/// produced on this thread, the 10-bit inter gate's firing proof.
2740pub(crate) fn inter_pred_hits() -> usize {
2741 crate::mc::inter_pred_hits()
2742}
2743
2744/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
2745/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
2746/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
2747/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
2748/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
2749/// needs to turn a query block's own resolved `ref_frame` into
2750/// `TplArgs::cur_offset_0` (spec 7.9.3).
2751pub(crate) struct TplFrameArgs<'a> {
2752 pub field: &'a crate::motion_field::TplField,
2753 pub order_hint_bits: u32,
2754 pub order_hint: u32,
2755 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
2756 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
2757 /// frame's own `ref_frame_idx` names for each single reference.
2758 pub ref_order_hints: [u32; 7],
2759}
2760
2761/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
2762/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
2763/// decoded `grid`: every 4x4 unit an inter block covers reads the same
2764/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
2765/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
2766/// exact — every block this crate ever codes is at least 8x8, so no 8x8
2767/// cell straddles two different blocks' values.
2768pub(crate) fn build_motion_field(
2769 grid: &MiGrid,
2770 mi_cols: usize,
2771 mi_rows: usize,
2772 order_hint: u32,
2773 order_hint_bits: u32,
2774 ref_order_hints: [u32; 7],
2775) -> crate::motion_field::MotionField {
2776 let mut field =
2777 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false);
2778 // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference
2779 // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other
2780 // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block
2781 // referencing one stores only its OTHER side's mv. With
2782 // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and
2783 // nothing is skipped.
2784 let other_side = |rf: i8| -> bool {
2785 if order_hint_bits == 0 {
2786 return false;
2787 }
2788 let oh = ref_order_hints[(rf - LAST_FRAME) as usize];
2789 crate::motion_field::get_relative_dist(order_hint_bits, oh, order_hint) > 0
2790 || oh == order_hint
2791 };
2792 // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is
2793 // capped at 12 bits per component; a longer one is not stored at all.
2794 const REFMVS_LIMIT: i32 = (1 << 12) - 1;
2795 for row in 0..mi_rows {
2796 for col in 0..mi_cols {
2797 let Some(info) = grid.get(row, col) else {
2798 continue;
2799 };
2800 // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and
2801 // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`),
2802 // so an intra block -- or an inter block whose every slot is on the
2803 // other side / over the limit -- wipes what an earlier block wrote
2804 // into the same 8x8 cell (only reachable from sub-8x8 leaves, which
2805 // share a cell).
2806 if !info.is_inter {
2807 field.set(row, col, None);
2808 continue;
2809 }
2810 // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST
2811 // qualifying one wins -- a compound block stores its second
2812 // reference's mv, never its first (unless the second is on the
2813 // other side or over the limit). Storing slot 0 unconditionally
2814 // put the wrong (mv, ref_frame_offset) pair in every compound
2815 // block's cell, which a later frame's temporal candidate then
2816 // projected with the wrong reference distance.
2817 let mut saved: Option<crate::motion_field::SavedMv> = None;
2818 for (rf, mv) in [
2819 (info.ref_frame, Some(info.mv)),
2820 (info.ref_frame1.unwrap_or(0), info.mv1),
2821 ] {
2822 let (Some(mv), true) = (mv, rf > 0) else {
2823 continue;
2824 };
2825 if other_side(rf) {
2826 continue;
2827 }
2828 if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT {
2829 continue;
2830 }
2831 saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf });
2832 }
2833 field.set(row, col, saved);
2834 }
2835 }
2836 field
2837}
2838
2839/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
2840/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
2841pub(crate) fn ref_hits(ref_frame: i8) -> usize {
2842 let c = match ref_frame {
2843 LAST2_FRAME => &LAST2_HITS,
2844 LAST3_FRAME => &LAST3_HITS,
2845 GOLDEN_FRAME => &GOLDEN_HITS,
2846 BWDREF_FRAME => &BWDREF_HITS,
2847 ALTREF2_FRAME => &ALTREF2_HITS,
2848 ALTREF_FRAME => &ALTREF_HITS,
2849 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
2850 };
2851 c.with(|v| v.get())
2852}
2853
2854thread_local! {
2855 /// The sequence header's `enable_intra_edge_filter`, set once per
2856 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
2857 /// own read of it, kept off the call stack (see that function's own doc
2858 /// comment for why) rather than threaded through every `read_plane`/
2859 /// `decode_block`/`decode_leaf8` call between here and there.
2860 static ENABLE_EDGE_FILTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2861}
2862
2863/// Set [`ENABLE_EDGE_FILTER`] for this thread.
2864///
2865/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
2866/// never did -- so an inter frame's intra blocks read whatever value the last
2867/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
2868/// harmless (its own key frame sets it first), but a caller that decodes an
2869/// inter frame directly, or a test harness running several streams on one
2870/// thread, inherits a foreign sequence's bit: decode stops being a pure
2871/// function of the bitstream. `decode_stream` now calls this once per stream
2872/// from the sequence header, which covers every frame including inter ones.
2873pub(crate) fn set_enable_edge_filter(value: bool) {
2874 ENABLE_EDGE_FILTER.with(|f| f.set(value));
2875}
2876
2877/// Current value of [`ANGLE_DELTA_HITS`].
2878pub(crate) fn angle_delta_hits() -> usize {
2879 ANGLE_DELTA_HITS.with(|c| c.get())
2880}
2881
2882/// Current value of [`TX_CLASS1_HITS`].
2883pub(crate) fn tx_class1_hits() -> usize {
2884 TX_CLASS1_HITS.with(|c| c.get())
2885}
2886
2887// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent
2888// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion
2889// bottom) this thread's decode actually reconstructed -- the same
2890// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream
2891// genuinely exercised the sub-8x8 leaf path rather than every attempt
2892// coincidentally landing on `PARTITION_NONE`.
2893thread_local! {
2894 static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2895 /// How many 8x8 groups an INTER frame split into four BLOCK_4X4 inter
2896 /// sub-blocks (lane-intersub8).
2897 static SUB8_INTER_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2898 /// How many 8x8 groups an INTER frame split into two rectangular sub-8x8
2899 /// inter leaves (lane-intersub8 r3), indexed `[0] = HORZ` (two BLOCK_8X4),
2900 /// `[1] = VERT` (two BLOCK_4X8).
2901 static SUB8_INTER_RECT_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
2902}
2903
2904/// Current value of [`SUB8_INTER_RECT_HITS`]: `(8x4 groups, 4x8 groups)`.
2905pub fn sub8_inter_rect_hits() -> (usize, usize) {
2906 SUB8_INTER_RECT_HITS.with(|c| {
2907 let h = c.get();
2908 (h[0], h[1])
2909 })
2910}
2911
2912// lane-cdef r1: (a) how many 8x8 CDEF units `apply_cdef` EXCLUDED because all
2913// four of their mi cells are `skip_txfm` (libaom `cdef.c:29-38`
2914// `is_8x8_block_skip` / `av1_cdef_compute_sb_list`'s dlist test), and (b) how
2915// many 8x8 inter leaves (`decode_inter_block8`) wrote that skip band at all.
2916// (b) was 0 for every stream before this round -- the leaf path never touched
2917// the band, so an all-skip 8x8 group kept the PREVIOUS frame's flags and got
2918// filtered where libaom skips it. A gate asserts both are non-zero.
2919thread_local! {
2920 static CDEF_SKIPPED_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2921 static INTER8_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2922 // lane-cdef r2: (c) 8x8 CDEF units that are FILTERED and whose extent
2923 // crosses the cropped frame edge -- the only units for which "clamp at
2924 // the crop" and "pad past the mi-rounded extent with CDEF_VERY_LARGE"
2925 // (libaom `cdef.c:249-256`, `cdef_prepare_fb`'s hsize/vsize are
2926 // `nhb << mi_wide_l2` off the MI grid, not the crop) differ. A frame
2927 // whose width or height is not a multiple of 8 is the only shape that
2928 // produces one; the straddling-band gate arms assert it grew.
2929 static CDEF_STRADDLE_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2930}
2931
2932/// Current value of `CDEF_SKIPPED_UNITS`.
2933pub(crate) fn cdef_skipped_units() -> usize {
2934 CDEF_SKIPPED_UNITS.with(|c| c.get())
2935}
2936
2937/// Current value of `INTER8_SKIP_BAND_HITS`.
2938pub(crate) fn inter8_skip_band_hits() -> usize {
2939 INTER8_SKIP_BAND_HITS.with(|c| c.get())
2940}
2941
2942/// Current value of `CDEF_STRADDLE_UNITS`.
2943pub(crate) fn cdef_straddle_units() -> usize {
2944 CDEF_STRADDLE_UNITS.with(|c| c.get())
2945}
2946
2947/// Current value of [`SUB8_SPLIT_HITS`].
2948pub(crate) fn sub8_split_hits() -> usize {
2949 SUB8_SPLIT_HITS.with(|c| c.get())
2950}
2951
2952/// Current value of [`SUB8_INTER_SPLIT_HITS`].
2953pub fn sub8_inter_split_hits() -> usize {
2954 SUB8_INTER_SPLIT_HITS.with(|c| c.get())
2955}
2956
2957// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ`
2958// of an 8x8 block) this thread's decode reconstructed with REAL coefficients
2959// -- a skipped leaf exercises the prediction and the mi bookkeeping but never
2960// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate
2961// asserts on these two rather than a plain leaf count.
2962thread_local! {
2963 static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2964 static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2965 /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's
2966 /// two 4x4 transform units, predicted one after the other. A separate
2967 /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so
2968 /// the gate can prove THIS path fired.
2969 static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2970 /// 16x8/8x16 intra strips whose prediction actually read past the block's
2971 /// own width (above-right) or height (below-left) -- the samples
2972 /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/
2973 /// `has_bl_*` table row can corrupt (lane-tx4x8 r3).
2974 static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2975 /// Every 16x8/8x16 intra strip predicted, reaching or not -- the
2976 /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of.
2977 static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2978}
2979
2980/// Current value of [`RECT8_SPLIT_TX_HITS`].
2981pub(crate) fn rect8_split_tx_hits() -> usize {
2982 RECT8_SPLIT_TX_HITS.with(|c| c.get())
2983}
2984
2985/// Current value of [`RECT_STRIP_PRED_HITS`].
2986pub(crate) fn rect_strip_pred_hits() -> usize {
2987 RECT_STRIP_PRED_HITS.with(|c| c.get())
2988}
2989
2990/// Current value of [`RECT_STRIP_REACH_HITS`].
2991pub(crate) fn rect_strip_reach_hits() -> usize {
2992 RECT_STRIP_REACH_HITS.with(|c| c.get())
2993}
2994
2995/// Current value of [`TX4X8_CODED_HITS`].
2996pub(crate) fn tx4x8_coded_hits() -> usize {
2997 TX4X8_CODED_HITS.with(|c| c.get())
2998}
2999
3000/// Current value of [`TX8X4_CODED_HITS`].
3001pub(crate) fn tx8x4_coded_hits() -> usize {
3002 TX8X4_CODED_HITS.with(|c| c.get())
3003}
3004
3005// How many CHROMA coefficient blocks read their `eob_pt` from the class-1
3006// (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread.
3007// Chroma never codes a `tx_type` symbol -- it inherits the colocated luma
3008// type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on
3009// an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired
3010// (`eob_pt_{16,64,128,256}_chroma_class1`).
3011thread_local! {
3012 static CHROMA_EOB_CLASS1_HITS: std::cell::Cell<usize> =
3013 const { std::cell::Cell::new(0) };
3014}
3015
3016/// Current value of [`CHROMA_EOB_CLASS1_HITS`].
3017pub(crate) fn chroma_eob_class1_hits() -> usize {
3018 CHROMA_EOB_CLASS1_HITS.with(|c| c.get())
3019}
3020
3021/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
3022/// `tx_type` put this block's `eob_pt` on the class-1 row.
3023fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
3024 if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD {
3025 CHROMA_EOB_CLASS1_HITS.with(|c| c.set(c.get() + 1));
3026 }
3027}
3028
3029const SUB_MI: u32 = 4;
3030const MI: usize = 4;
3031const SB: usize = 64;
3032/// The `above_side`/`left_side` value a cell with no decoded neighbour holds
3033/// (tile start, superblock-row start).
3034///
3035/// [`Neighbours::partition_ctx_mi`] reads it as libaom's
3036/// `av1_get_partition_plane_context` reads its own zero-initialised
3037/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at
3038/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB`
3039/// (64), which reads identically at every level up to 64x64 but sets the bit
3040/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition
3041/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec
3042/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`).
3043const NO_NEIGHBOUR_SIDE: usize = 128;
3044const BLOCK: usize = 32;
3045const SUB: usize = 16;
3046const TX32: usize = 32;
3047const TX16: usize = 16;
3048const TX8: usize = 8;
3049const TX4: usize = 4;
3050const DC_PRED: usize = 0;
3051/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
3052/// carries an angle delta — [`crate::tile`]'s own private copy of the same
3053/// constant.
3054const V_PRED: usize = 1;
3055const H_PRED: usize = 2;
3056/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
3057/// `Fimode_To_Intradir`, libaom `blockd.h`).
3058const D157_PRED: usize = 6;
3059/// The last directional mode, `D67_PRED`.
3060const D67_PRED: usize = 8;
3061/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
3062/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
3063/// codes anything else, so this decoder never reads anything else either.
3064const ANGLE_DELTA_ZERO: usize = 3;
3065const NUM_BASE_LEVELS: i32 = 2;
3066const COEFF_BASE_RANGE: i32 = 12;
3067const BR_STEP: i32 = 3;
3068const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
3069
3070/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
3071/// whose probability mass a superblock or block half outside the frame
3072/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
3073/// duplicated here (that module is another lane's territory this round) and
3074/// kept in step with it by the byte-exact round-trip tests below rather than
3075/// by sharing code.
3076const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
3077const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
3078
3079fn trace_edge(mi_r: usize, mi_c: usize, bsize: u32, ctx: usize, rng: u32) {
3080 if std::env::var_os("EC_AV1_TRACE").is_some() {
3081 eprintln!("OUR_PART mi_row={mi_r} mi_col={mi_c} bsize={bsize} ctx={ctx} rng={rng}");
3082 }
3083}
3084
3085fn element_prob(cdf: &[u16], element: usize) -> u16 {
3086 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
3087}
3088
3089/// The two-symbol CDF a partial superblock/block's forced-split flag is read
3090/// with: the mass of `elements` becomes the probability of the one partition
3091/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
3092/// (the encoder's non-adapting counterpart to this read).
3093fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
3094 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
3095 [32768 - split, 32768, 0]
3096}
3097
3098fn unsupported(what: impl Into<String>) -> Error {
3099 Error::unsupported("AV1 tile", what.into())
3100}
3101
3102/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
3103/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
3104/// same rule.
3105pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
3106 match base_q_idx {
3107 0..=20 => 0,
3108 21..=60 => 1,
3109 61..=120 => 2,
3110 _ => 3,
3111 }
3112}
3113
3114/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
3115/// [`crate::tile`]'s writer generates its scan tables with.
3116fn default_scan(side: usize) -> Vec<u16> {
3117 let mut scan = Vec::with_capacity(side * side);
3118 for d in 0..(2 * side - 1) {
3119 let lo = d.saturating_sub(side - 1);
3120 let hi = d.min(side - 1);
3121 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
3122 if d % 2 == 0 {
3123 scan.extend(diagonal.rev());
3124 } else {
3125 scan.extend(diagonal);
3126 }
3127 }
3128 scan
3129}
3130
3131/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
3132/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
3133/// in, instead of the default zigzag. libaom's own tables are keyed by a
3134/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
3135/// physically column-major level buffer, but they decompose to the exact
3136/// same (row, col) walk as a flat row-major traversal of *our* row-major
3137/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
3138/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
3139/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
3140/// transposed (column 0 down every row, then column 1, ...).
3141fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
3142 class_scan_table_wh(side, side, class)
3143}
3144
3145/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
3146/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
3147/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
3148/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
3149/// transcribed with -- `mrow` is the plain row-major raster in our indexing
3150/// and `mcol` its transpose, at rect sizes exactly as at square ones.
3151fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
3152 match class {
3153 TxClass::Vert => (0..(w * h) as u16).collect(),
3154 TxClass::Horiz => (0..w)
3155 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
3156 .collect(),
3157 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
3158 }
3159}
3160
3161fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
3162 match scan_idx {
3163 0 => 0,
3164 i if i <= area / 8 => 1,
3165 i if i <= area / 4 => 2,
3166 _ => 3,
3167 }
3168}
3169
3170fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
3171 if row >= side || col >= side {
3172 0
3173 } else {
3174 grid[row * side + col]
3175 }
3176}
3177
3178/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
3179/// `txb_common.h`): everything but the two lone-axis-identity types this
3180/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
3181#[derive(Clone, Copy, PartialEq, Eq)]
3182enum TxClass {
3183 TwoD,
3184 Horiz,
3185 Vert,
3186}
3187
3188impl TxClass {
3189 fn of(tx_type: TxType) -> Self {
3190 match tx_type {
3191 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
3192 // key on axis alone -- FLIPADST is still ADST for this purpose.
3193 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
3194 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
3195 _ => Self::TwoD,
3196 }
3197 }
3198}
3199
3200/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
3201/// table (indexed by the position along the transform's *coded* axis --
3202/// `col` for horiz, `row` for vert) that places their contexts past the 2D
3203/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
3204/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
3205fn nz_map_ctx_offset_1d(i: usize) -> usize {
3206 match i {
3207 0 => 26,
3208 1 => 31,
3209 _ => 36,
3210 }
3211}
3212
3213fn base_ctx(
3214 grid: &[i32],
3215 side: usize,
3216 row: usize,
3217 col: usize,
3218 class: TxClass,
3219 rect_shape: Option<(usize, usize)>,
3220) -> usize {
3221 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
3222 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
3223 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
3224 // position through the full 1D neighbour sum and offset table. Skipping
3225 // that for every class desynced the last (DC) coefficient of a
3226 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
3227 // 0, which then read one extra `BR` symbol at the max and forced a
3228 // spurious third Golomb call).
3229 if class == TxClass::TwoD && row == 0 && col == 0 {
3230 return 0;
3231 }
3232 let offsets: [(usize, usize); 5] = match class {
3233 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
3234 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
3235 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
3236 };
3237 let mag: i32 = offsets
3238 .iter()
3239 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
3240 .sum();
3241 let ctx = ((mag + 1) >> 1).min(4) as usize;
3242 match class {
3243 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
3244 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
3245 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
3246 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
3247 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
3248 // strip, which own a genuinely different table from the square one
3249 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
3250 // square table vs the real ctx 13 the rect table gives).
3251 TxClass::TwoD => {
3252 // lane-rectsplit r4: apply libaom's GENERATING RULE
3253 // (`txb_common.h:199-209`) directly instead of indexing the
3254 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
3255 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
3256 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
3257 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
3258 // so 32 consecutive entries are one COLUMN: the [`cdf`]
3259 // transcriptions are `[col][row]` and this read had them as
3260 // `[row][col]` -- the transpose, i.e. the other shape's rule with
3261 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
3262 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
3263 // pins the rule against the tables over their whole 5x5 domain.
3264 if let Some((w, h)) = rect_shape {
3265 if std::env::var_os("EC_NZOFF_DUMP").is_some() {
3266 eprintln!("NZOFF side={side} shape={w}x{h} row={row} col={col}");
3267 }
3268 if w < h && row < 2 {
3269 return ctx + 11;
3270 }
3271 if w > h && col < 2 {
3272 return ctx + 16;
3273 }
3274 }
3275 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
3276 }
3277 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
3278 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
3279 }
3280}
3281
3282fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize, class: TxClass) -> usize {
3283 let extra = match class {
3284 TxClass::TwoD => neighbour(grid, side, row + 1, col + 1).abs(),
3285 TxClass::Horiz => neighbour(grid, side, row, col + 2).abs(),
3286 TxClass::Vert => neighbour(grid, side, row + 2, col).abs(),
3287 };
3288 let mag = neighbour(grid, side, row + 1, col).abs()
3289 + neighbour(grid, side, row, col + 1).abs()
3290 + extra;
3291 let mag = (((mag + 1) >> 1).min(6)) as usize;
3292 if row == 0 && col == 0 {
3293 return mag;
3294 }
3295 let near_origin = match class {
3296 TxClass::TwoD => row < 2 && col < 2,
3297 TxClass::Horiz => col == 0,
3298 TxClass::Vert => row == 0,
3299 };
3300 if near_origin { mag + 7 } else { mag + 14 }
3301}
3302
3303/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
3304/// transposed from libaom's column-major buffer into this decoder's row-major
3305/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
3306/// against the real table). Not the square zigzag formula generalized to
3307/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
3308const SCAN_32X16: [u16; 512] = [
3309 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161,
3310 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39,
3311 8, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72,
3312 41, 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229,
3313 198, 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44,
3314 13, 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418,
3315 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326,
3316 295, 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234,
3317 203, 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142,
3318 111, 80, 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19,
3319 485, 454, 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424,
3320 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332,
3321 301, 270, 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240,
3322 209, 178, 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148,
3323 117, 86, 55, 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25,
3324 491, 460, 429, 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430,
3325 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338,
3326 307, 276, 245, 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246,
3327 215, 184, 153, 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154,
3328 123, 92, 61, 30, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31,
3329 497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405,
3330 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251,
3331 220, 189, 158, 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439,
3332 408, 377, 346, 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503,
3333 472, 441, 410, 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443,
3334 412, 381, 350, 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415,
3335 509, 478, 447, 510, 479, 511,
3336];
3337
3338/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
3339/// [`SCAN_32X16`]'s doc comment).
3340const SCAN_16X32: [u16; 512] = [
3341 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,
3342 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
3343 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
3344 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
3345 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
3346 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
3347 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
3348 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
3349 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
3350 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
3351 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
3352 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
3353 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
3354 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
3355 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
3356 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
3357 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
3358 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
3359 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
3360 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
3361 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
3362 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
3363 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
3364 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
3365 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
3366 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
3367];
3368
3369/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
3370/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
3371/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
3372/// the same source).
3373const SCAN_4X8: [u16; 32] = [
3374 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,
3375 23, 26, 29, 27, 30, 31,
3376];
3377
3378/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
3379const SCAN_8X4: [u16; 32] = [
3380 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,
3381 29, 22, 15, 30, 23, 31,
3382];
3383
3384/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
3385/// [`SCAN_32X16`]'s doc comment).
3386const SCAN_16X8: [u16; 128] = [
3387 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,
3388 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
3389 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
3390 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
3391 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
3392 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
3393];
3394
3395/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
3396/// [`SCAN_32X16`]'s doc comment).
3397const SCAN_8X16: [u16; 128] = [
3398 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,
3399 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
3400 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
3401 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
3402 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
3403 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
3404];
3405
3406/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
3407/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
3408/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
3409/// scans column-major (`p = col * height + row`), so a naive copy of
3410/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
3411/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
3412/// are byte-identical to this decoder's [`SCAN_8X16`].
3413const SCAN_32X8: [u16; 256] = [
3414 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
3415 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226, 195,
3416 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104, 73, 42,
3417 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200, 169,
3418 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78, 47, 16,
3419 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205, 174, 143,
3420 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83, 52, 21, 239,
3421 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210, 179, 148, 117,
3422 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88, 57, 26, 244, 213,
3423 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215, 184, 153, 122, 91,
3424 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93, 62, 31, 249, 218, 187,
3425 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127, 252, 221, 190, 159, 253,
3426 222, 191, 254, 223, 255,
3427];
3428/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
3429/// 16x64 `PARTITION_VERT_4` strip).
3430const SCAN_8X32: [u16; 256] = [
3431 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,
3432 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
3433 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
3434 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
3435 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
3436 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
3437 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
3438 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
3439 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
3440 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
3441 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
3442 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
3443 239, 246, 253, 247, 254, 255,
3444];
3445/// `Default_Scan_16x4`, this decoder's own row-major transcription of
3446/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
3447/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
3448/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
3449/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
3450/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
3451/// were emitted -- a naive copy installs the transpose (class
3452/// reference-layout-not-spec).
3453const SCAN_16X4: [u16; 64] = [
3454 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,
3455 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
3456 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
3457];
3458/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
3459/// 8x32 `PARTITION_VERT_4` strip).
3460const SCAN_4X16: [u16; 64] = [
3461 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,
3462 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
3463 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
3464];
3465
3466/// [`neighbour`] with independent `w` (row stride)/`h` (row-bound) extents
3467/// (lane-rectwire, mirrors [`record_rect`](Neighbours::record_rect)'s
3468/// asymmetric-extent pattern).
3469fn neighbour_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> i32 {
3470 if row >= h || col >= w {
3471 0
3472 } else {
3473 grid[row * w + col]
3474 }
3475}
3476
3477/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
3478/// the rect generalization is libaom's own comment in
3479/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
3480/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
3481/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
3482/// [`decode_block_rect`] codes (see that function's own doc comment).
3483fn base_ctx_rect(
3484 grid: &[i32],
3485 w: usize,
3486 h: usize,
3487 row: usize,
3488 col: usize,
3489 class: TxClass,
3490) -> usize {
3491 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
3492 // the 2D class short-circuits the DC position.
3493 if class == TxClass::TwoD && row == 0 && col == 0 {
3494 return 0;
3495 }
3496 let offsets: [(usize, usize); 5] = match class {
3497 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
3498 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
3499 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
3500 };
3501 let mag: i32 = offsets
3502 .iter()
3503 .map(|&(dr, dc)| neighbour_rect(grid, w, h, row + dr, col + dc).abs().min(3))
3504 .sum();
3505 let ctx = ((mag + 1) >> 1).min(4) as usize;
3506 match class {
3507 TxClass::TwoD => {
3508 if w < h && row < 2 {
3509 return ctx + 11;
3510 }
3511 if w > h && col < 2 {
3512 return ctx + 16;
3513 }
3514 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
3515 }
3516 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
3517 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
3518 // position along one axis only).
3519 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
3520 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
3521 }
3522}
3523
3524/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
3525/// neighbour-offset math itself is shape-independent, only the boundary
3526/// clamp needs the real bound in each axis.
3527fn br_ctx_rect(
3528 grid: &[i32],
3529 w: usize,
3530 h: usize,
3531 row: usize,
3532 col: usize,
3533 class: TxClass,
3534) -> usize {
3535 let extra = match class {
3536 TxClass::TwoD => neighbour_rect(grid, w, h, row + 1, col + 1).abs(),
3537 TxClass::Horiz => neighbour_rect(grid, w, h, row, col + 2).abs(),
3538 TxClass::Vert => neighbour_rect(grid, w, h, row + 2, col).abs(),
3539 };
3540 let mag = neighbour_rect(grid, w, h, row + 1, col).abs()
3541 + neighbour_rect(grid, w, h, row, col + 1).abs()
3542 + extra;
3543 let mag = (((mag + 1) >> 1).min(6)) as usize;
3544 if row == 0 && col == 0 {
3545 return mag;
3546 }
3547 let near_origin = match class {
3548 TxClass::TwoD => row < 2 && col < 2,
3549 TxClass::Horiz => col == 0,
3550 TxClass::Vert => row == 0,
3551 };
3552 if near_origin { mag + 7 } else { mag + 14 }
3553}
3554
3555fn dc_vote(dc: Option<bool>) -> i32 {
3556 match dc {
3557 None => 0,
3558 Some(true) => -1,
3559 Some(false) => 1,
3560 }
3561}
3562
3563fn dc_sign_ctx(vote: i32) -> usize {
3564 match vote.signum() {
3565 0 => 0,
3566 -1 => 1,
3567 _ => 2,
3568 }
3569}
3570
3571/// The remainder of a level the base and base-range syntax could not reach
3572/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
3573/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
3574fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
3575 // lane-scaledref r1: this cap MASKS A REAL DEFECT and must not be lifted
3576 // on its own. Reading up to 32 leading zeros (dav1d's `len < 32`; libaom
3577 // itself calls a 21st bit a corrupt frame, decodetxb.c:30) is bit-identical
3578 // for every tail any encoder writes -- our own writer tops out at 19 zeros
3579 // (`tile::MAX_LEVEL == MAX_BR_LEVEL + (1 << 19)`) -- and was implemented
3580 // and round-trip tested here (commit ee1f980, reverted in 314ee08). It
3581 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
3582 // RED: seed 67 stops here today, and with the cap raised it decodes to a
3583 // frame-0 LUMA MISMATCH instead. A key frame cannot legitimately carry a
3584 // level above 1<<19, so the long tail is the SYMPTOM of an earlier desync
3585 // in that intra rect64 stream -- class `refusal-hides-a-defect`. Lift this
3586 // together with that defect's fix, not before.
3587 let mut length = 1u32;
3588 while dec.literal(1) == 0 {
3589 length += 1;
3590 if length > 20 {
3591 return Err(unsupported("a Golomb tail longer than this decoder reads"));
3592 }
3593 }
3594 let mut x = 1u32;
3595 for _ in 1..length {
3596 x = (x << 1) | dec.literal(1);
3597 }
3598 Ok(x - 1)
3599}
3600
3601/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
3602/// [`crate::tile`]'s `write_eob`.
3603fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
3604 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
3605 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
3606
3607 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
3608 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
3609 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
3610 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
3611 // `eob_multi_ctx`). Missing that split desynced the very first
3612 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
3613 // against a real aomdec trace).
3614 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
3615 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
3616 (_, Some(class1)) => class1,
3617 };
3618 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
3619 let (range, value) = dec.debug_state();
3620 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
3621 }
3622 let group = dec.symbol(eob_pt) + 1;
3623 if trace {
3624 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
3625 }
3626 let bits = OFFSET_BITS[group];
3627 let mut offset = 0u32;
3628 if bits > 0 {
3629 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
3630 if trace {
3631 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
3632 }
3633 offset = top << (bits - 1);
3634 if bits > 1 {
3635 offset |= dec.literal(bits - 1);
3636 }
3637 }
3638 GROUP_START[group] + offset as usize
3639}
3640
3641/// One transform block's levels, the inverse of [`crate::tile`]'s
3642/// `write_coeffs`, returned as a `side * side` grid in raster order, along
3643/// with the transform type that grid was coded under (`DCT_DCT` when the
3644/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
3645/// 64-point transforms, which never code anything else).
3646///
3647/// # Errors
3648/// Returns an error if the `tx_type` symbol decodes to a value outside its
3649/// CDF's own set (a corrupt or unsupported bitstream) — every value the
3650/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
3651/// produce dispatches to a real inverse transform.
3652/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
3653/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
3654/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
3655/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
3656/// the plane's own predicted mode instead. Every entry this table can
3657/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
3658/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
3659/// table ever names), so unlike the CDF-coded luma path there is no
3660/// ext-tx-set membership check to fall back from here.
3661fn default_intra_tx_type(mode: u8) -> TxType {
3662 use crate::intra::{
3663 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
3664 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
3665 };
3666 match mode {
3667 DC_PRED | D45_PRED => TxType::DctDct,
3668 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
3669 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
3670 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
3671 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
3672 }
3673}
3674
3675/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
3676/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
3677/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
3678fn is_smooth_mode(mode: usize) -> bool {
3679 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
3680}
3681
3682fn read_coeffs(
3683 dec: &mut SymbolDecoder,
3684 coding: &mut TxbTables,
3685 scan: &[u16],
3686 skip_ctx: usize,
3687 sign_ctx: usize,
3688 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
3689 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
3690 // nothing at all; `DctDct` for every luma call and every chroma call at
3691 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
3692 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
3693 default_tx_type: TxType,
3694 // `Some((w, h))` with `w != h` when this read is a superblock-level
3695 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
3696 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
3697 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
3698 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
3699 // caller's block genuinely is `side` x `side`.
3700 rect_shape: Option<(usize, usize)>,
3701) -> Result<(Vec<i32>, TxType)> {
3702 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
3703 let side = coding.side;
3704 let mut grid = vec![0i32; side * side];
3705 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
3706 let (range, value) = dec.debug_state();
3707 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
3708 }
3709 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
3710 if std::env::var_os("EC_TRACE_COEFF").is_some() {
3711 let (rng, _) = dec.debug_state();
3712 eprintln!(
3713 "EC_COEFF_STEP tag=all_zero ctx={skip_ctx} all_zero={} rng={rng}",
3714 all_zero as i32
3715 );
3716 }
3717 if std::env::var_os("EC_AV1_TELL").is_some() {
3718 eprintln!(
3719 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
3720 all_zero as u8, dec.debug_bitpos(), dec.debug_state().0
3721 );
3722 }
3723 if trace {
3724 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
3725 }
3726 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
3727 let (range, value) = dec.debug_state();
3728 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
3729 }
3730 if all_zero {
3731 return Ok((grid, TxType::DctDct));
3732 }
3733 let mut tx_type = default_tx_type;
3734 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
3735 // The CDF row's own width names its set (lane-cdffwd2: extended
3736 // past the original two-way intra split once wider `reduced_tx_set
3737 // == 0` inter sets joined the table): 17 slots (16 symbols) is
3738 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
3739 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
3740 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
3741 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
3742 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
3743 let len = tx_type_cdf.len();
3744 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() && len == 3 {
3745 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
3746 }
3747 let t = dec.symbol(tx_type_cdf);
3748 if std::env::var_os("EC_TRACE_COEFF").is_some() {
3749 let (rng, _) = dec.debug_state();
3750 eprintln!("EC_COEFF_STEP tag=tx_type rng={rng}");
3751 }
3752 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
3753 let (range, value) = dec.debug_state();
3754 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
3755 }
3756 if trace {
3757 eprintln!("TRACE tx_type value={t} len={len}");
3758 }
3759 tx_type = match len {
3760 17 => TxType::from_symbol_all16(t),
3761 13 => TxType::from_symbol_set2_12(t),
3762 8 => TxType::from_symbol_set1(t),
3763 _ => TxType::from_symbol(t),
3764 }
3765 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
3766 }
3767
3768 let class = TxClass::of(tx_type);
3769 if class != TxClass::TwoD {
3770 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
3771 RECT_CLASS1_HITS.with(|c| c.set(c.get() + 1));
3772 }
3773 let eob = read_eob(dec, coding, class);
3774 if trace {
3775 eprintln!("TRACE eob value={eob}");
3776 }
3777 let ec_trace_coeff = std::env::var_os("EC_TRACE_COEFF").is_some();
3778 if ec_trace_coeff {
3779 let (rng, _) = dec.debug_state();
3780 let cls = match class { TxClass::TwoD => "2d", TxClass::Horiz => "horiz", TxClass::Vert => "vert" };
3781 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
3782 }
3783 let class_scan;
3784 let scan: &[u16] = if class == TxClass::TwoD {
3785 scan
3786 } else {
3787 class_scan = class_scan_table(side, class);
3788 &class_scan
3789 };
3790 let mut levels = vec![0i32; side * side];
3791 for scan_idx in (0..eob).rev() {
3792 let pos = scan[scan_idx] as usize;
3793 let (row, col) = (pos / side, pos % side);
3794 let level = if scan_idx == eob - 1 {
3795 let ctx = eob_coeff_ctx(scan_idx, side * side);
3796 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
3797 if trace {
3798 eprintln!(
3799 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
3800 );
3801 }
3802 v
3803 } else {
3804 let ctx = base_ctx(&levels, side, row, col, class, rect_shape);
3805 let v = dec.symbol(&mut coding.base[ctx]) as i32;
3806 if ec_trace_coeff {
3807 let (rng, _) = dec.debug_state();
3808 // `pos` in libaom's column-major `coeff_idx` convention, so
3809 // the ladder lines up with instrumented `aomdec`.
3810 let apos = col * side + row;
3811 eprintln!(
3812 "EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}"
3813 );
3814 }
3815 if trace {
3816 eprintln!(
3817 "TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
3818 );
3819 }
3820 v
3821 };
3822 let level = if level > NUM_BASE_LEVELS {
3823 let ctx = br_ctx(&levels, side, row, col, class);
3824 let mut level = level;
3825 let mut sent = 0;
3826 loop {
3827 let k = dec.symbol(&mut coding.br[ctx]) as i32;
3828 if trace {
3829 eprintln!(
3830 "TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}"
3831 );
3832 }
3833 level += k;
3834 sent += BR_STEP;
3835 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
3836 break;
3837 }
3838 }
3839 level
3840 } else {
3841 level
3842 };
3843 if ec_trace_coeff && scan_idx == eob - 1 {
3844 let (rng, _) = dec.debug_state();
3845 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
3846 }
3847 levels[pos] = level;
3848 }
3849 if ec_trace_coeff {
3850 let (rng, _) = dec.debug_state();
3851 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
3852 }
3853
3854 for (c, &pos) in scan[..eob].iter().enumerate() {
3855 let level = levels[pos as usize];
3856 if level == 0 {
3857 continue;
3858 }
3859 let negative = if pos == 0 {
3860 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
3861 if trace {
3862 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
3863 }
3864 v
3865 } else {
3866 dec.literal(1) == 1
3867 };
3868 if ec_trace_coeff {
3869 let (rng, _) = dec.debug_state();
3870 eprintln!("EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}", negative as i32);
3871 }
3872 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
3873 let g = read_golomb(dec)?;
3874 if trace {
3875 eprintln!("TRACE golomb pos={pos} value={g}");
3876 }
3877 level + g as i32
3878 } else {
3879 level
3880 };
3881 if ec_trace_coeff {
3882 let (rng, _) = dec.debug_state();
3883 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
3884 }
3885 grid[pos as usize] = if negative { -level } else { level };
3886 }
3887 Ok((grid, tx_type))
3888}
3889
3890/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
3891/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
3892/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
3893/// can ever produce, since every `tx_type` this decoder's rect sets can read
3894/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
3895/// rather than guess-decode if a non-2D class ever shows up here, since
3896/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
3897/// form for those.
3898fn read_coeffs_rect(
3899 dec: &mut SymbolDecoder,
3900 coding: &mut TxbTables,
3901 scan: &[u16],
3902 w: usize,
3903 h: usize,
3904 skip_ctx: usize,
3905 sign_ctx: usize,
3906 default_tx_type: TxType,
3907) -> Result<(Vec<i32>, TxType)> {
3908 let rect_trace = std::env::var_os("EC_TRACE_COEFF").is_some();
3909 let mut grid = vec![0i32; w * h];
3910 let entry_rng = dec.debug_state().0;
3911 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
3912 if rect_trace {
3913 eprintln!(
3914 "EC_COEFF_STEP tag=all_zero plane=0 ctx={skip_ctx} entry={entry_rng} all_zero={} rng={}",
3915 all_zero as i32,
3916 dec.debug_state().0
3917 );
3918 }
3919 if all_zero {
3920 return Ok((grid, TxType::DctDct));
3921 }
3922 RECT_COEFF_TU_HITS.with(|c| c.set(c.get() + 1));
3923 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
3924 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
3925 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
3926 // context offsets -- both of which now have rect forms
3927 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
3928 // The rect sets that carry no symbol at all still pass `None` here.
3929 let mut tx_type = default_tx_type;
3930 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
3931 let len = tx_type_cdf.len();
3932 let t = dec.symbol(tx_type_cdf);
3933 tx_type = match len {
3934 17 => TxType::from_symbol_all16(t),
3935 13 => TxType::from_symbol_set2_12(t),
3936 8 => TxType::from_symbol_set1(t),
3937 _ => TxType::from_symbol(t),
3938 }
3939 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
3940 if rect_trace {
3941 eprintln!("EC_COEFF_STEP tag=tx_type plane=0 rng={}", dec.debug_state().0);
3942 }
3943 }
3944 let class = TxClass::of(tx_type);
3945 if class != TxClass::TwoD {
3946 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
3947 }
3948 let eob = read_eob(dec, coding, class);
3949 if rect_trace {
3950 eprintln!("EC_COEFF_STEP tag=eob eob={eob} rng={}", dec.debug_state().0);
3951 }
3952 let class_scan;
3953 let scan: &[u16] = if class == TxClass::TwoD {
3954 scan
3955 } else {
3956 class_scan = class_scan_table_wh(w, h, class);
3957 &class_scan
3958 };
3959 let mut levels = vec![0i32; w * h];
3960 for scan_idx in (0..eob).rev() {
3961 let pos = scan[scan_idx] as usize;
3962 let (row, col) = (pos / w, pos % w);
3963 // libaom's column-major `coeff_idx`, for ladder comparison.
3964 let apos = col * h + row;
3965 let level = if scan_idx == eob - 1 {
3966 let ctx = eob_coeff_ctx(scan_idx, w * h);
3967 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
3968 if rect_trace {
3969 eprintln!(
3970 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
3971 dec.debug_state().0
3972 );
3973 }
3974 v
3975 } else {
3976 let ctx = base_ctx_rect(&levels, w, h, row, col, class);
3977 let v = dec.symbol(&mut coding.base[ctx]) as i32;
3978 if rect_trace {
3979 eprintln!(
3980 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
3981 dec.debug_state().0
3982 );
3983 }
3984 v
3985 };
3986 let level = if level > NUM_BASE_LEVELS {
3987 let ctx = br_ctx_rect(&levels, w, h, row, col, class);
3988 let mut level = level;
3989 let mut sent = 0;
3990 loop {
3991 let k = dec.symbol(&mut coding.br[ctx]) as i32;
3992 if rect_trace {
3993 eprintln!(
3994 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
3995 dec.debug_state().0
3996 );
3997 }
3998 level += k;
3999 sent += BR_STEP;
4000 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
4001 break;
4002 }
4003 }
4004 level
4005 } else {
4006 level
4007 };
4008 levels[pos] = level;
4009 if rect_trace {
4010 let (rng, _) = dec.debug_state();
4011 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}");
4012 }
4013 }
4014 if rect_trace {
4015 let (rng, _) = dec.debug_state();
4016 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
4017 }
4018 for &pos in &scan[..eob] {
4019 let level = levels[pos as usize];
4020 if level == 0 {
4021 continue;
4022 }
4023 let negative = if pos == 0 {
4024 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
4025 } else {
4026 dec.literal(1) == 1
4027 };
4028 if rect_trace {
4029 let (rng, _) = dec.debug_state();
4030 eprintln!("EC_COEFF_STEP tag=sign_rect pos={pos} sign={} rng={rng}", u8::from(negative));
4031 }
4032 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
4033 let g = read_golomb(dec)?;
4034 level + g as i32
4035 } else {
4036 level
4037 };
4038 grid[pos as usize] = if negative { -level } else { level };
4039 }
4040 Ok((grid, tx_type))
4041}
4042
4043/// What one coded block leaves behind for the blocks that read it as a
4044/// neighbour: whether it coded anything at all, and the sign of its DC —
4045/// [`crate::tile`]'s own private `Neighbour`.
4046#[derive(Clone, Copy, Default)]
4047struct Neighbour {
4048 /// The transform unit's cumulative coefficient level (spec `cul_level`,
4049 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
4050 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
4051 /// boolean (`level != 0`) is enough for every context this decoder read
4052 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
4053 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
4054 /// needs the actual magnitude tier of its above/left neighbours, not
4055 /// just whether they coded anything.
4056 level: u8,
4057 dc: Option<bool>,
4058}
4059
4060fn neighbour_state(grid: &[i32]) -> Neighbour {
4061 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
4062 Neighbour {
4063 level: cul.min(7) as u8,
4064 dc: (grid[0] != 0).then_some(grid[0] < 0),
4065 }
4066}
4067
4068/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
4069/// transform unit smaller than the block it sits in): `top`/`left` are the
4070/// above/left neighbours' magnitude tiers, each already clamped to 4.
4071const SKIP_CONTEXTS: [[usize; 5]; 5] = [
4072 [1, 2, 2, 2, 3],
4073 [2, 4, 4, 4, 5],
4074 [2, 4, 4, 4, 5],
4075 [2, 4, 4, 4, 5],
4076 [3, 5, 5, 5, 6],
4077];
4078
4079/// The neighbour state a block's contexts are read from — a duplicate of
4080/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
4081/// territory this round), kept at the same two granularities the real writer
4082/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
4083/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
4084/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
4085/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
4086/// chroma transform straddling the true, odd-sized frame edge see its
4087/// neighbour's state clamped at its own subsampled edge rather than luma's.
4088struct Neighbours {
4089 above: Vec<[Neighbour; 3]>,
4090 left: Vec<[Neighbour; 3]>,
4091 above_mode: Vec<usize>,
4092 left_mode: Vec<usize>,
4093 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
4094 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
4095 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
4096 /// luma one -- the same block can (and often does) code a different
4097 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
4098 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
4099 /// within-block neighbour finer than this grid) is luma-only -- a known,
4100 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
4101 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
4102 above_uv_mode: Vec<usize>,
4103 left_uv_mode: Vec<usize>,
4104 above_side: Vec<usize>,
4105 left_side: Vec<usize>,
4106 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
4107 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
4108 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
4109 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
4110 /// array cannot tell the second leaf's partition symbol that the first
4111 /// one was coded at 8x8.
4112 above_side_mi: Vec<usize>,
4113 left_side_mi: Vec<usize>,
4114 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
4115 /// / row, with the mi position it was written at
4116 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
4117 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
4118 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
4119 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
4120 /// leaf whose neighbour is another split group needs that group's leaf 3
4121 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
4122 /// and read only by [`decode_leaf_split4`]; the position guard makes it
4123 /// fall back to the coarse slot whenever the real neighbour was a block
4124 /// of 8x8 or larger (whose one mode is correct for every row it spans).
4125 sub8_mode_col: Vec<(usize, usize)>,
4126 sub8_mode_row: Vec<(usize, usize)>,
4127 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
4128 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
4129 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
4130 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
4131 /// the leaf above writes the same row slot the block to the left owns.
4132 uv_mode_col: Vec<(usize, usize)>,
4133 uv_mode_row: Vec<(usize, usize)>,
4134 /// Whether the block above/left of this column/row was coded `skip` --
4135 /// an inter frame's own `skip` context (spec `SkipContext`), which the
4136 /// key-frame writer never tracks (its skip context is always zero); a
4137 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
4138 /// `left_skip`.
4139 above_skip: Vec<bool>,
4140 left_skip: Vec<bool>,
4141 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
4142 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
4143 /// pixels last written over each unit by `set_txfm_ctxs`/
4144 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
4145 /// symbol reads its context from (lane-txselect, spec 5.11.17).
4146 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
4147 /// array is exactly libaom's per-superblock-row reset, since each mi row
4148 /// is only ever visited inside one superblock row.
4149 above_txfm: Vec<u8>,
4150 left_txfm: Vec<u8>,
4151 /// Whether the block above/left of this column/row coded `skip_mode`
4152 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
4153 /// lane-av1comp round 14.
4154 above_skip_mode: Vec<bool>,
4155 left_skip_mode: Vec<bool>,
4156 /// Whether the block above/left was coded inter -- the `is_inter`
4157 /// context (spec `av1_get_intra_inter_context`), a duplicate of
4158 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
4159 above_inter: Vec<bool>,
4160 left_inter: Vec<bool>,
4161 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
4162 /// alphabet) the block above/left of this column/row coded, or `-1` for
4163 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
4164 /// functions (`mvstack::ref_ctx` family) need the real reference, not
4165 /// just "was it inter" (lane-av1refs: every inter block used to be
4166 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
4167 /// enough).
4168 above_ref: Vec<i8>,
4169 left_ref: Vec<i8>,
4170 /// The block above/left's *second* reference frame when it was coded
4171 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
4172 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
4173 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
4174 /// `i8`, once a compound `read_ref_frames` lands. Always `None` today
4175 /// (no decode path here ever produces a compound block yet).
4176 above_ref1: Vec<Option<i8>>,
4177 left_ref1: Vec<Option<i8>>,
4178 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
4179 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
4180 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
4181 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
4182 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
4183 above_comp_group_idx: Vec<u8>,
4184 left_comp_group_idx: Vec<u8>,
4185 above_compound_idx: Vec<u8>,
4186 left_compound_idx: Vec<u8>,
4187 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
4188 /// `3` = "no info": an intra neighbour or the frame's own border) of the
4189 /// block above/left of this column/row -- spec
4190 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
4191 above_filter: Vec<[u8; 2]>,
4192 left_filter: Vec<[u8; 2]>,
4193 mi_cols: usize,
4194 mi_rows: usize,
4195 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
4196 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
4197 /// 7.15) never filters an 8x8 luma block whose covering coded block read
4198 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
4199 /// grain [`Self::record_mi`] already writes at), read back at 8x8
4200 /// granularity by [`apply_cdef`] since `skip` is constant across every
4201 /// mi cell one coded block covers.
4202 skip_grid: Vec<bool>,
4203 /// Per-4x4-mi origin `(mi_row, mi_col)` of the coded (prediction) block
4204 /// covering that cell -- spec 7.14.2's `isBlockEdge`/libaom `pu_edge`,
4205 /// which re-enables the loop filter at a prediction boundary between two
4206 /// skipped inter blocks (lane-mergefix r4). Written by
4207 /// [`Self::fill_skip_grid_rect`], whose `at_mi` IS that origin.
4208 blk_org_grid: Vec<[u16; 2]>,
4209 skip_grid_cols_mi: usize,
4210 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
4211 /// never splits a coded block's transform below its own size (round 2:
4212 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
4213 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
4214 /// edge-length lookup (`apply_deblock`).
4215 tx_grid: Vec<u8>,
4216 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
4217 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
4218 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
4219 tx_h_grid: Vec<u8>,
4220 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
4221 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
4222 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
4223 /// does NOT follow luma's `tx_depth` split, so deriving it as
4224 /// `tx_grid / 2` invented chroma transform edges the deblocker then
4225 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
4226 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
4227 /// every caller routes through.
4228 uv_tx_grid: Vec<u8>,
4229 uv_tx_h_grid: Vec<u8>,
4230 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
4231 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
4232 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
4233 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
4234 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
4235 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
4236 /// reference onto `LAST_FRAME`'s own delta).
4237 ref_grid: Vec<i8>,
4238 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
4239 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
4240 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
4241 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
4242 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
4243 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
4244 /// to know which mode produced the value.
4245 delta_lf_grid: Vec<[i8; 4]>,
4246 /// The block above/left's own palette-Y size (0 = not a palette block)
4247 /// and its base colours -- `av1_get_palette_mode_ctx`/
4248 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
4249 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
4250 above_palette_size: Vec<usize>,
4251 left_palette_size: Vec<usize>,
4252 above_palette_colors: Vec<[u16; 8]>,
4253 left_palette_colors: Vec<[u16; 8]>,
4254 /// As the four fields above, for the neighbour's own chroma (U-channel
4255 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
4256 /// palette size/colours (lane-palette2 r1).
4257 above_palette_uv_size: Vec<usize>,
4258 left_palette_uv_size: Vec<usize>,
4259 above_palette_uv_colors: Vec<[u16; 8]>,
4260 left_palette_uv_colors: Vec<[u16; 8]>,
4261 /// This tile's own top-left corner, in 4x4 mode-info units (spec
4262 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
4263 /// neighbour" check compares against this instead of literal `0`, since a
4264 /// block at the tile's own top/left edge has no usable neighbour even
4265 /// though a decoded block sits there in the picture (spec `decode_tile`'s
4266 /// per-tile `clear_above_context`/`left_available`/`up_available`).
4267 /// `0` for a single-tile frame, matching every existing caller exactly.
4268 tile_row0_mi: usize,
4269 tile_col0_mi: usize,
4270}
4271
4272impl Neighbours {
4273 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
4274 /// true (unpadded) size in 4x4 mode-info units.
4275 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
4276 Self {
4277 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
4278 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
4279 above_mode: vec![DC_PRED; cols],
4280 left_mode: vec![DC_PRED; rows],
4281 above_uv_mode: vec![DC_PRED; cols],
4282 left_uv_mode: vec![DC_PRED; rows],
4283 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
4284 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
4285 above_side_mi: vec![NO_NEIGHBOUR_SIDE; cols * (SUB / MI)],
4286 left_side_mi: vec![NO_NEIGHBOUR_SIDE; rows * (SUB / MI)],
4287 sub8_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],
4288 sub8_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)],
4289 uv_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],
4290 uv_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)],
4291 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
4292 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
4293 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
4294 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
4295 // 16x16 block beside it, which a SUB-grid slot cannot name
4296 // (class context-read-from-one-cell).
4297 above_skip: vec![false; cols * (SUB / MI)],
4298 left_skip: vec![false; rows * (SUB / MI)],
4299 above_skip_mode: vec![false; cols * (SUB / MI)],
4300 left_skip_mode: vec![false; rows * (SUB / MI)],
4301 above_inter: vec![false; cols * (SUB / MI)],
4302 left_inter: vec![false; rows * (SUB / MI)],
4303 above_ref: vec![-1; cols * (SUB / MI)],
4304 left_ref: vec![-1; rows * (SUB / MI)],
4305 above_ref1: vec![None; cols * (SUB / MI)],
4306 left_ref1: vec![None; rows * (SUB / MI)],
4307 above_comp_group_idx: vec![0; cols * (SUB / MI)],
4308 left_comp_group_idx: vec![0; rows * (SUB / MI)],
4309 above_compound_idx: vec![0; cols * (SUB / MI)],
4310 left_compound_idx: vec![0; rows * (SUB / MI)],
4311 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
4312 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
4313 mi_cols,
4314 mi_rows,
4315 skip_grid: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
4316 blk_org_grid: vec![[0u16; 2]; cols * (SUB / MI) * rows * (SUB / MI)],
4317 skip_grid_cols_mi: cols * (SUB / MI),
4318 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
4319 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
4320 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
4321 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
4322 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
4323 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
4324 above_palette_size: vec![0; cols],
4325 left_palette_size: vec![0; rows],
4326 above_palette_colors: vec![[0u16; 8]; cols],
4327 left_palette_colors: vec![[0u16; 8]; rows],
4328 above_palette_uv_size: vec![0; cols],
4329 left_palette_uv_size: vec![0; rows],
4330 above_palette_uv_colors: vec![[0u16; 8]; cols],
4331 left_palette_uv_colors: vec![[0u16; 8]; rows],
4332 tile_row0_mi: 0,
4333 tile_col0_mi: 0,
4334 }
4335 }
4336
4337 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
4338 /// tile's own column span (`col1_mi` exclusive), plus recording
4339 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
4340 /// availability check below. Left context resets every superblock row
4341 /// regardless of tile ([`Self::start_row`], already called once per SB
4342 /// row by every caller) so it needs no tile-specific reset here.
4343 fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize) {
4344 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
4345 // are tile-relative, same as every other neighbour lookup here.
4346 SEG_TILE_ORIGIN.with(|c| c.set((row0_mi, col0_mi)));
4347 self.tile_row0_mi = row0_mi;
4348 self.tile_col0_mi = col0_mi;
4349 let end = col1_mi.min(self.above.len());
4350 for i in col0_mi.min(end)..end {
4351 self.above[i] = Default::default();
4352 self.above_side_mi[i] = NO_NEIGHBOUR_SIDE;
4353 }
4354 let (sc0, sc1) = (
4355 col0_mi / (SUB / MI),
4356 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
4357 );
4358 for i in sc0.min(sc1)..sc1 {
4359 self.above_mode[i] = DC_PRED;
4360 self.above_side[i] = NO_NEIGHBOUR_SIDE;
4361 }
4362 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
4363 // the tile's own mi column span directly.
4364 let mend = col1_mi.min(self.above_skip.len());
4365 for i in col0_mi.min(mend)..mend {
4366 self.above_skip[i] = false;
4367 self.above_skip_mode[i] = false;
4368 self.above_inter[i] = false;
4369 self.above_ref[i] = -1;
4370 self.above_ref1[i] = None;
4371 self.above_comp_group_idx[i] = 0;
4372 self.above_compound_idx[i] = 0;
4373 self.above_filter[i] = [3u8; 2];
4374 }
4375 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
4376 // stale `(row, mode)` from the tile to the LEFT names an mi row this
4377 // tile's first block would read as its own above neighbour.
4378 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
4379 for i in col0_mi.min(mcol_end)..mcol_end {
4380 self.sub8_mode_col[i] = (usize::MAX, 0);
4381 self.uv_mode_col[i] = (usize::MAX, 0);
4382 }
4383 // lane-mergefix r2: `av1_zero_above_context` also memsets the txfm row
4384 // over the tile's own column span (to `tx_size_wide[TX_SIZES_LARGEST]`,
4385 // not zero) -- without it a second tile column reads the first one's
4386 // resolved transform sizes as its own above context.
4387 let tend = col1_mi.min(self.above_txfm.len());
4388 for i in col0_mi.min(tend)..tend {
4389 self.above_txfm[i] = TXFM_CTX_INIT;
4390 }
4391 }
4392
4393 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
4394 /// for a non-palette block, clearing any stale neighbour state) into every
4395 /// [`SUB`]-grid cell it covers on both the above and left edges --
4396 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
4397 /// call sites are all square blocks).
4398 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
4399 self.record_palette_y_rect(at, side, side, size, colors);
4400 }
4401
4402 /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
4403 /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
4404 /// [`Self::record`]): a true rect strip's above/left neighbour spans
4405 /// differ.
4406 fn record_palette_y_rect(
4407 &mut self,
4408 at: (usize, usize),
4409 w: usize,
4410 h: usize,
4411 size: usize,
4412 colors: [u16; 8],
4413 ) {
4414 let (r, c) = at;
4415 // `.max(1)`: a below-16px span covers no whole SUB cell, so the plain
4416 // `w / SUB` loop was a NO-OP for every 16x8/8x16/8x8/4x4 leaf and the
4417 // next block read a long-dead palette out of the above/left arrays
4418 // (class [[cdf-row-held-constant]], lane-palette2 r8). libaom keeps
4419 // `palette_size` per 4px mi cell; corner-cut: our grid is 16px, so a
4420 // sub-16 leaf stamps its whole containing cell -- safe today because
4421 // every sub-16 leaf path refuses palette outright (so it can only
4422 // ever stamp `size == 0`, and its cell holds no palette sibling).
4423 // Upgrade path: widen the palette arrays to mi granularity.
4424 for cell in 0..(w / SUB).max(1) {
4425 self.above_palette_size[c + cell] = size;
4426 self.above_palette_colors[c + cell] = colors;
4427 }
4428 for cell in 0..(h / SUB).max(1) {
4429 self.left_palette_size[r + cell] = size;
4430 self.left_palette_colors[r + cell] = colors;
4431 }
4432 }
4433
4434 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
4435 /// neighbours that are themselves a palette-Y block, plus
4436 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
4437 /// cache (pred_common.c:73).
4438 ///
4439 /// The SB-top-row exclusion of the above neighbour (`row % 64` in
4440 /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
4441 /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
4442 /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
4443 /// the ctx too made every superblock in the frame's second SB row read
4444 /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
4445 /// palette block decoded as "no palette" and the tile desynced from
4446 /// there (class [[cdf-row-held-constant]]).
4447 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
4448 self.palette_ctx_and_cache_mi(at, at.0 * (SUB / MI))
4449 }
4450
4451 /// [`Self::palette_ctx_and_cache`] with the block's REAL mi row, which a
4452 /// 1:4 strip does not share with its [`SUB`] cell: `av1_get_palette_cache`
4453 /// drops the above neighbour on a 64-px superblock boundary
4454 /// (pred_common.c:76, `row % (1 << MIN_SB_SIZE_LOG2)` with `row` the
4455 /// block's own PIXEL row), and strip 1 of a HORZ_4 sits 8 px into the
4456 /// cell -- reading `at.0 % 4` there excludes strip 0 from the cache of
4457 /// every strip in an SB's top cell row, which libaom does not do.
4458 fn palette_ctx_and_cache_mi(&self, at: (usize, usize), mi_r: usize) -> (usize, Vec<u16>) {
4459 let (r, c) = at;
4460 let above_ok = mi_r % 16 != 0;
4461 // `xd->above_mbmi` exists for every row but the tile's own first.
4462 let above_is_palette = mi_r > self.tile_row0_mi && self.above_palette_size[c] > 0;
4463 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
4464 (self.above_palette_size[c], self.above_palette_colors[c])
4465 } else {
4466 (0, [0u16; 8])
4467 };
4468 // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which
4469 // is NULL whenever the block sits at its TILE's own left column
4470 // (`left_available`), not the frame's -- without this guard a second
4471 // tile column reads the previous tile's palette colours into its cache
4472 // and its `palette_y_mode` ctx.
4473 let left_ok = c > self.tile_col0_mi / (SUB / MI);
4474 let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 {
4475 (self.left_palette_size[r], self.left_palette_colors[r])
4476 } else {
4477 (0, [0u16; 8])
4478 };
4479 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
4480 let mut cache = Vec::with_capacity(16);
4481 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
4482 if cache.last() != Some(&v) {
4483 cache.push(v);
4484 }
4485 };
4486 let (mut ai, mut li) = (0usize, 0usize);
4487 while ai < above_n && li < left_n {
4488 let (va, vl) = (above_colors[ai], left_colors[li]);
4489 if vl < va {
4490 push_dedup(&mut cache, vl);
4491 li += 1;
4492 } else {
4493 push_dedup(&mut cache, va);
4494 ai += 1;
4495 if vl == va {
4496 li += 1;
4497 }
4498 }
4499 }
4500 while ai < above_n {
4501 push_dedup(&mut cache, above_colors[ai]);
4502 ai += 1;
4503 }
4504 while li < left_n {
4505 push_dedup(&mut cache, left_colors[li]);
4506 li += 1;
4507 }
4508 (ctx, cache)
4509 }
4510
4511 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
4512 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
4513 /// same way (lane-palette2 r1).
4514 fn record_palette_uv(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
4515 self.record_palette_uv_rect(at, side, side, size, colors);
4516 }
4517
4518 /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
4519 /// extents, in LUMA pixels (lane-palette2 r4, same convention as
4520 /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
4521 /// luma resolution regardless of which plane the recorded state is for).
4522 fn record_palette_uv_rect(
4523 &mut self,
4524 at: (usize, usize),
4525 w: usize,
4526 h: usize,
4527 size: usize,
4528 colors: [u16; 8],
4529 ) {
4530 let (r, c) = at;
4531 // See [`Self::record_palette_y_rect`] for the `.max(1)`.
4532 for cell in 0..(w / SUB).max(1) {
4533 self.above_palette_uv_size[c + cell] = size;
4534 self.above_palette_uv_colors[c + cell] = colors;
4535 }
4536 for cell in 0..(h / SUB).max(1) {
4537 self.left_palette_uv_size[r + cell] = size;
4538 self.left_palette_uv_colors[r + cell] = colors;
4539 }
4540 }
4541
4542 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
4543 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
4544 /// no neighbour lookup at all (it is this block's own just-decided Y
4545 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
4546 /// so only the cache is wanted here.
4547 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
4548 self.palette_uv_cache_mi(at, at.0 * (SUB / MI))
4549 }
4550
4551 /// [`Self::palette_uv_cache`] with the block's real mi row -- see
4552 /// [`Self::palette_ctx_and_cache_mi`].
4553 fn palette_uv_cache_mi(&self, at: (usize, usize), mi_r: usize) -> Vec<u16> {
4554 let (r, c) = at;
4555 let above_ok = mi_r % 16 != 0;
4556 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
4557 (self.above_palette_uv_size[c], self.above_palette_uv_colors[c])
4558 } else {
4559 (0, [0u16; 8])
4560 };
4561 // Same tile-relative left availability as the luma cache above.
4562 let left_ok = c > self.tile_col0_mi / (SUB / MI);
4563 let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 {
4564 (self.left_palette_uv_size[r], self.left_palette_uv_colors[r])
4565 } else {
4566 (0, [0u16; 8])
4567 };
4568 let mut cache = Vec::with_capacity(16);
4569 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
4570 if cache.last() != Some(&v) {
4571 cache.push(v);
4572 }
4573 };
4574 let (mut ai, mut li) = (0usize, 0usize);
4575 while ai < above_n && li < left_n {
4576 let (va, vl) = (above_colors[ai], left_colors[li]);
4577 if vl < va {
4578 push_dedup(&mut cache, vl);
4579 li += 1;
4580 } else {
4581 push_dedup(&mut cache, va);
4582 ai += 1;
4583 if vl == va {
4584 li += 1;
4585 }
4586 }
4587 }
4588 while ai < above_n {
4589 push_dedup(&mut cache, above_colors[ai]);
4590 ai += 1;
4591 }
4592 while li < left_n {
4593 push_dedup(&mut cache, left_colors[li]);
4594 li += 1;
4595 }
4596 cache
4597 }
4598
4599 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
4600 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
4601 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
4602 /// units as [`Self::fill_skip_grid`].
4603 fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8) {
4604 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame);
4605 }
4606
4607 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
4608 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
4609 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
4610 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
4611 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
4612 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
4613 /// libaom `set_one_param_for_line_luma`/`_chroma`: an edge that is a
4614 /// transform-unit edge but NOT a prediction-unit edge is not filtered when
4615 /// `curr_skipped = mbmi->skip_txfm && is_inter_block(mbmi)`. Widening this
4616 /// block's published transform extent to its own size is exactly that
4617 /// suppression for the deblocker's `x0 % tx != 0` test -- the only shape
4618 /// that needs it is the 128 root, whose chroma extent (64) is the one
4619 /// [`Self::fill_lf_grid_rect`]'s TX_32X32 cap narrows. An INTRA block is
4620 /// never suppressed (libaom's `is_inter_block` term), so this is called
4621 /// only from the skipped-inter branch.
4622 fn suppress_internal_lf_edges(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize) {
4623 let (mi_r, mi_c) = at_mi;
4624 let (uv_w, uv_h) = ((w_mi * MI / 2).max(4) as u8, (h_mi * MI / 2).max(4) as u8);
4625 for rr in 0..h_mi {
4626 for cc in 0..w_mi {
4627 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
4628 if let Some(cell) = self.uv_tx_grid.get_mut(idx) {
4629 *cell = uv_w;
4630 }
4631 if let Some(cell) = self.uv_tx_h_grid.get_mut(idx) {
4632 *cell = uv_h;
4633 }
4634 }
4635 }
4636 }
4637
4638 fn fill_lf_grid_rect(
4639 &mut self,
4640 at_mi: (usize, usize),
4641 w_mi: usize,
4642 h_mi: usize,
4643 tx_px: u8,
4644 tx_h_px: u8,
4645 ref_frame: i8,
4646 ) {
4647 let (mi_r, mi_c) = at_mi;
4648 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
4649 // half its luma one (min 4 px, the smallest transform), capped at
4650 // TX_32X32 -- independent of this block's luma `tx_depth`.
4651 let uv_tx_w = ((w_mi * MI / 2).max(4).min(32)) as u8;
4652 let uv_tx_h = ((h_mi * MI / 2).max(4).min(32)) as u8;
4653 if std::env::var_os("EC_TXGRID_TRACE").is_some() {
4654 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}");
4655 }
4656 let cur = CURRENT_DELTA_LF.with(|c| c.get());
4657 let snapshot: [i8; 4] = if DELTA_LF_MULTI.with(|c| c.get()) {
4658 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
4659 } else {
4660 [cur[0].clamp(-63, 63) as i8; 4]
4661 };
4662 for rr in 0..h_mi {
4663 for cc in 0..w_mi {
4664 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
4665 if let Some(cell) = self.tx_grid.get_mut(idx) {
4666 *cell = tx_px;
4667 }
4668 if let Some(cell) = self.tx_h_grid.get_mut(idx) {
4669 *cell = tx_h_px;
4670 }
4671 if let Some(cell) = self.uv_tx_grid.get_mut(idx) {
4672 *cell = uv_tx_w;
4673 }
4674 if let Some(cell) = self.uv_tx_h_grid.get_mut(idx) {
4675 *cell = uv_tx_h;
4676 }
4677 if let Some(cell) = self.ref_grid.get_mut(idx) {
4678 *cell = ref_frame;
4679 }
4680 if let Some(cell) = self.delta_lf_grid.get_mut(idx) {
4681 *cell = snapshot;
4682 }
4683 }
4684 }
4685 }
4686
4687 /// One var-tx / split-tx LEAF's own LUMA transform dims over its mi span.
4688 /// libaom `get_transform_size` (av1_loopfilter.c:207) applies the split
4689 /// override only `if ((plane == AOM_PLANE_Y) && ...)` -- chroma keeps
4690 /// `av1_get_max_uv_txsize(mbmi->bsize)`, the whole BLOCK's uv transform.
4691 /// Routing a leaf through [`Self::fill_lf_grid_rect`] recomputed the uv
4692 /// dims from the LEAF span and so invented chroma transform edges the
4693 /// deblocker then filtered (lane-golomb r6). `ref_grid`/`delta_lf_grid`
4694 /// are already correct from the block's own fill over the same span.
4695 fn fill_lf_grid_leaf_luma(
4696 &mut self,
4697 at_mi: (usize, usize),
4698 w_mi: usize,
4699 h_mi: usize,
4700 tx_px: u8,
4701 tx_h_px: u8,
4702 ) {
4703 let (mi_r, mi_c) = at_mi;
4704 for rr in 0..h_mi {
4705 for cc in 0..w_mi {
4706 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
4707 if let Some(cell) = self.tx_grid.get_mut(idx) {
4708 *cell = tx_px;
4709 }
4710 if let Some(cell) = self.tx_h_grid.get_mut(idx) {
4711 *cell = tx_h_px;
4712 }
4713 }
4714 }
4715 }
4716
4717 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
4718 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
4719 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
4720 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
4721 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
4722 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
4723 }
4724
4725 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
4726 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
4727 let (mi_r, mi_c) = at_mi;
4728 for rr in 0..h_mi {
4729 for cc in 0..w_mi {
4730 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
4731 if let Some(cell) = self.skip_grid.get_mut(idx) {
4732 *cell = skip;
4733 }
4734 if let Some(org) = self.blk_org_grid.get_mut(idx) {
4735 *org = [mi_r as u16, mi_c as u16];
4736 }
4737 }
4738 }
4739 }
4740
4741 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
4742 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
4743 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
4744 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
4745 /// straddle the region with a mix of skip/non-skip blocks).
4746 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
4747 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
4748 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
4749 /// filtered edge's two sides are each exactly one coded block wide.
4750 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
4751 self.skip_grid
4752 .get(mi_r * self.skip_grid_cols_mi + mi_c)
4753 .copied()
4754 .unwrap_or(false)
4755 }
4756
4757 /// The `skip_txfm` context of a block whose top-left mi cell is
4758 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
4759 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
4760 /// with an absent neighbour contributing 0. The mi grid is per tile, so
4761 /// row/column 0 is a tile edge and has no neighbour on that axis.
4762 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
4763 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
4764 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
4765 }
4766
4767 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
4768 (0..2).all(|rr| {
4769 (0..2).all(|cc| {
4770 self.skip_grid
4771 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
4772 .copied()
4773 .unwrap_or(false)
4774 })
4775 })
4776 }
4777
4778 fn start_row(&mut self) {
4779 self.left.iter_mut().for_each(|l| *l = Default::default());
4780 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
4781 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
4782 self.left_side.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
4783 self.left_side_mi.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
4784 self.left_skip.iter_mut().for_each(|s| *s = false);
4785 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
4786 self.left_inter.iter_mut().for_each(|i| *i = false);
4787 self.left_ref.iter_mut().for_each(|r| *r = -1);
4788 self.left_ref1.iter_mut().for_each(|r| *r = None);
4789 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
4790 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
4791 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
4792 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
4793 // context (a tile/SB-row boundary has no left neighbour).
4794 self.sub8_mode_row.iter_mut().for_each(|s| *s = (usize::MAX, 0));
4795 self.uv_mode_row.iter_mut().for_each(|s| *s = (usize::MAX, 0));
4796 // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands
4797 // are per-mi maps like every other one here, so they reset with the
4798 // row too -- the left guard above is what actually stops a cross-tile
4799 // read, this keeps a stale colour out of the arrays at all.
4800 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
4801 self.left_palette_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
4802 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
4803 self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
4804 // lane-mergefix r2: `av1_zero_left_context` memsets
4805 // `left_txfm_context_buffer` to `tx_size_high[TX_SIZES_LARGEST]` at
4806 // every superblock row of every tile -- the var-tx left context does
4807 // NOT carry over a tile boundary (its `txfm_partition` ctx read the
4808 // previous tile column's last block otherwise).
4809 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
4810 }
4811
4812 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
4813 /// block that reads it as a neighbour -- [`crate::tile`]'s
4814 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
4815 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
4816 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
4817 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
4818 /// the real value, not just `is_inter`).
4819 fn record_inter(
4820 &mut self,
4821 at: (usize, usize),
4822 side: usize,
4823 skip: bool,
4824 is_inter: bool,
4825 ref_frame: i8,
4826 filter: [u8; 2],
4827 skip_mode: bool,
4828 ) {
4829 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
4830 }
4831
4832 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
4833 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
4834 /// r1: a true rectangular strip's above-context span (its own width) and
4835 /// left-context span (its own height) differ, unlike every caller before
4836 /// this round (class neighbour-votes-all-its-fields).
4837 #[allow(clippy::too_many_arguments)]
4838 fn record_inter_rect(
4839 &mut self,
4840 at: (usize, usize),
4841 w_sub: usize,
4842 h_sub: usize,
4843 skip: bool,
4844 is_inter: bool,
4845 ref_frame: i8,
4846 filter: [u8; 2],
4847 skip_mode: bool,
4848 ) {
4849 let (r, c) = at;
4850 self.record_inter_rect_mi(
4851 (r * (SUB / MI), c * (SUB / MI)),
4852 w_sub / MI,
4853 h_sub / MI,
4854 skip,
4855 is_inter,
4856 ref_frame,
4857 filter,
4858 skip_mode,
4859 );
4860 }
4861
4862 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
4863 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
4864 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
4865 /// routes through the wrapper above.
4866 #[allow(clippy::too_many_arguments)]
4867 fn record_inter_rect_mi(
4868 &mut self,
4869 at_mi: (usize, usize),
4870 w_mi: usize,
4871 h_mi: usize,
4872 skip: bool,
4873 is_inter: bool,
4874 ref_frame: i8,
4875 filter: [u8; 2],
4876 skip_mode: bool,
4877 ) {
4878 let (r, c) = at_mi;
4879 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
4880 for cell in 0..w_mi {
4881 self.above_skip[c + cell] = skip;
4882 self.above_skip_mode[c + cell] = skip_mode;
4883 self.above_inter[c + cell] = is_inter;
4884 self.above_ref[c + cell] = ref_frame;
4885 // lane-av1comp: no caller of `record_inter` ever decodes a
4886 // compound block yet (see [`Self::above_ref1`]'s doc); the
4887 // parameter this becomes lands with `read_ref_frames`.
4888 self.above_ref1[c + cell] = None;
4889 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
4890 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
4891 // as `3`/`1` even though this block has no second reference.
4892 // `record_compound_ctx` overwrites this with the real bit for an
4893 // actual compound block's cells, called right after this one.
4894 self.above_comp_group_idx[c + cell] = if altref { 3 } else { 0 };
4895 self.above_compound_idx[c + cell] = u8::from(altref);
4896 self.above_filter[c + cell] = filter;
4897 }
4898 for cell in 0..h_mi {
4899 self.left_skip[r + cell] = skip;
4900 self.left_skip_mode[r + cell] = skip_mode;
4901 self.left_inter[r + cell] = is_inter;
4902 self.left_ref[r + cell] = ref_frame;
4903 self.left_ref1[r + cell] = None;
4904 self.left_comp_group_idx[r + cell] = if altref { 3 } else { 0 };
4905 self.left_compound_idx[r + cell] = u8::from(altref);
4906 self.left_filter[r + cell] = filter;
4907 }
4908 }
4909
4910 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
4911 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
4912 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
4913 /// `get_comp_index_context`) -- called right after `record_inter` for
4914 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
4915 /// stamps `above_ref1`/`left_ref1` with the block's real second
4916 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
4917 /// this is the one caller that actually knows it) -- so the next block's
4918 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
4919 /// neighbour instead of `record_inter`'s single-ref default.
4920 fn record_compound_ctx(
4921 &mut self,
4922 at: (usize, usize),
4923 side: usize,
4924 ref1: i8,
4925 comp_group_idx: u8,
4926 compound_idx: u8,
4927 ) {
4928 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
4929 }
4930
4931 /// [`Self::record_compound_ctx`] with independent above/left extents,
4932 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
4933 #[allow(clippy::too_many_arguments)]
4934 fn record_compound_ctx_rect(
4935 &mut self,
4936 at: (usize, usize),
4937 w_sub: usize,
4938 h_sub: usize,
4939 ref1: i8,
4940 comp_group_idx: u8,
4941 compound_idx: u8,
4942 ) {
4943 let (r, c) = at;
4944 self.record_compound_ctx_rect_mi(
4945 (r * (SUB / MI), c * (SUB / MI)),
4946 w_sub / MI,
4947 h_sub / MI,
4948 ref1,
4949 comp_group_idx,
4950 compound_idx,
4951 );
4952 }
4953
4954 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
4955 /// [`Self::record_inter_rect_mi`]).
4956 fn record_compound_ctx_rect_mi(
4957 &mut self,
4958 at_mi: (usize, usize),
4959 w_mi: usize,
4960 h_mi: usize,
4961 ref1: i8,
4962 comp_group_idx: u8,
4963 compound_idx: u8,
4964 ) {
4965 let (r, c) = at_mi;
4966 for cell in 0..w_mi {
4967 self.above_ref1[c + cell] = Some(ref1);
4968 self.above_comp_group_idx[c + cell] = comp_group_idx;
4969 self.above_compound_idx[c + cell] = compound_idx;
4970 }
4971 for cell in 0..h_mi {
4972 self.left_ref1[r + cell] = Some(ref1);
4973 self.left_comp_group_idx[r + cell] = comp_group_idx;
4974 self.left_compound_idx[r + cell] = compound_idx;
4975 }
4976 }
4977
4978 /// The context of a block's partition symbol: delegates to the mi-precise
4979 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
4980 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
4981 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
4982 /// only touches the finer mi arrays -- leaves them stale for the *next*
4983 /// sibling's own partition symbol.
4984 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
4985 let (r, c) = at;
4986 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
4987 }
4988
4989 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
4990 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
4991 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
4992 /// than the enclosing 16x16 slot's stale, shared state.
4993 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
4994 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side)
4995 + usize::from(self.above_side_mi[mi_c] * 2 <= side)
4996 }
4997
4998 /// The gathered coded/DC-sign state of the blocks above and to the left
4999 /// of a block `side` samples across, per plane.
5000 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
5001 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
5002 }
5003
5004 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
5005 /// units, for the same reason [`Self::record_mi`] does.
5006 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
5007 let side_mi = side / MI;
5008 std::array::from_fn(|plane| {
5009 let mut above_coded = false;
5010 let mut left_coded = false;
5011 let mut vote = 0;
5012 for cell in 0..side_mi {
5013 let above = &self.above[mi_c + cell][plane];
5014 let left = &self.left[mi_r + cell][plane];
5015 above_coded |= above.level != 0;
5016 left_coded |= left.level != 0;
5017 vote += dc_vote(above.dc) + dc_vote(left.dc);
5018 }
5019 (above_coded, left_coded, vote)
5020 })
5021 }
5022
5023 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
5024 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
5025 /// extent pattern for a true rectangular strip's own coefficient context.
5026 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
5027 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
5028 }
5029
5030 /// [`Self::around_rect`] taking the block's position directly in 4x4
5031 /// mode-info units, mirroring [`Self::around_mi`].
5032 fn around_mi_rect(&self, (mi_r, mi_c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
5033 let (w_mi, h_mi) = (w / MI, h / MI);
5034 std::array::from_fn(|plane| {
5035 let mut above_coded = false;
5036 let mut left_coded = false;
5037 let mut vote = 0;
5038 for cell in 0..w_mi {
5039 let above = &self.above[mi_c + cell][plane];
5040 above_coded |= above.level != 0;
5041 vote += dc_vote(above.dc);
5042 }
5043 for cell in 0..h_mi {
5044 let left = &self.left[mi_r + cell][plane];
5045 left_coded |= left.level != 0;
5046 vote += dc_vote(left.dc);
5047 }
5048 (above_coded, left_coded, vote)
5049 })
5050 }
5051
5052 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
5053 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
5054 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
5055 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
5056 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
5057 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
5058 /// is always 0, spec's `plane_bsize == tx_size` branch).
5059 fn luma_skip_ctx(&self, at_mi: (usize, usize), side_mi: usize) -> usize {
5060 self.luma_skip_ctx_rect(at_mi, side_mi, side_mi)
5061 }
5062
5063 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi
5064 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above
5065 /// context over `tx_size_wide` and the left one over `tx_size_high`.
5066 fn luma_skip_ctx_rect(
5067 &self,
5068 (mi_r, mi_c): (usize, usize),
5069 w_mi: usize,
5070 h_mi: usize,
5071 ) -> usize {
5072 let side_mi = w_mi;
5073 let mut top = 0u8;
5074 let mut left = 0u8;
5075 for cell in 0..w_mi {
5076 top |= self.above[mi_c + cell][0].level;
5077 }
5078 for cell in 0..h_mi {
5079 left |= self.left[mi_r + cell][0].level;
5080 }
5081 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
5082 if std::env::var_os("EC_AV1_TRACE").is_some() {
5083 eprintln!(
5084 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx}"
5085 );
5086 }
5087 ctx
5088 }
5089
5090 /// Writes one coded block into every cell it covers, on both grids: the
5091 /// mode/side arrays up to `side`'s own width, and the coefficient-context
5092 /// arrays up to the true frame edge — the units past it are left at their
5093 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
5094 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
5095 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
5096 /// not from this block's own side).
5097 fn record(
5098 &mut self,
5099 at: (usize, usize),
5100 side: usize,
5101 mode: usize,
5102 uv_mode: usize,
5103 grids: &[Vec<i32>; 3],
5104 ) {
5105 self.record_rect(at, side, side, mode, uv_mode, grids);
5106 }
5107
5108 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
5109 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
5110 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
5111 /// spec's per-edge partition-context rule, so a true rectangular block
5112 /// naturally wants two different values here rather than one.
5113 /// Writes this block's luma `mode` into the mi-granular
5114 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
5115 /// position a *later* neighbour would read it from: the block's LAST mi
5116 /// row for every column it spans (what the block below reads via
5117 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
5118 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
5119 /// read these back, and only when the recorded position is exactly their
5120 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
5121 fn record_mode_mi(
5122 &mut self,
5123 mi_r: usize,
5124 mi_c: usize,
5125 mi_w: usize,
5126 mi_h: usize,
5127 mode: usize,
5128 ) {
5129 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
5130 for cell in 0..mi_w {
5131 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
5132 *slot = (last_r, mode);
5133 }
5134 }
5135 for cell in 0..mi_h {
5136 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
5137 *slot = (last_c, mode);
5138 }
5139 }
5140 }
5141
5142 /// The mi-exact above/left neighbour luma mode for a block whose top-left
5143 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
5144 /// mi position (then the coarse [`SUB`]-grid slot is right by
5145 /// construction). See [`Self::record_mode_mi`].
5146 fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
5147 match self.sub8_mode_col.get(mi_c) {
5148 Some(&(row, m)) if mi_r > self.tile_row0_mi && row == mi_r - 1 => Some(m),
5149 _ => None,
5150 }
5151 }
5152
5153 fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
5154 match self.sub8_mode_row.get(mi_r) {
5155 Some(&(col, m)) if mi_c > self.tile_col0_mi && col == mi_c - 1 => Some(m),
5156 _ => None,
5157 }
5158 }
5159
5160 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
5161 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
5162 fn record_uv_mode_mi(
5163 &mut self,
5164 mi_r: usize,
5165 mi_c: usize,
5166 mi_w: usize,
5167 mi_h: usize,
5168 uv_mode: usize,
5169 ) {
5170 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
5171 for cell in 0..mi_w {
5172 if let Some(slot) = self.uv_mode_col.get_mut(mi_c + cell) {
5173 *slot = (last_r, uv_mode);
5174 }
5175 }
5176 for cell in 0..mi_h {
5177 if let Some(slot) = self.uv_mode_row.get_mut(mi_r + cell) {
5178 *slot = (last_c, uv_mode);
5179 }
5180 }
5181 }
5182
5183 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
5184 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
5185 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
5186 /// block has recorded the exact neighbouring mi.
5187 fn smooth_uv_neighbour(&self, mi_r: usize, mi_c: usize, r: usize, c: usize) -> bool {
5188 // lane-kf900 r2: libaom reads the chroma neighbours off the CHROMA
5189 // REFERENCE block, not off the mi that carries the chroma syntax.
5190 // `set_mi_row_col` (`blockd.h`) takes
5191 // `base_mi = &xd->mi[-(mi_row & ss_y) * stride - (mi_col & ss_x)]` and
5192 // only then `chroma_above_mbmi = base_mi[-stride]` /
5193 // `chroma_left_mbmi = base_mi[-1]`. A sub-8 pair codes its chroma at
5194 // the ODD mi, so without the snap we looked one mi row/column too far
5195 // down/right -- the mi-exact slot never matched and the coarse
5196 // fallback answered instead. Measured on a 4K 10-bit key frame, chroma
5197 // 8x4 at (688, 100) = mi (51, 344): libaom's
5198 // `get_intra_edge_filter_type` is 1 (the chroma block above it is
5199 // `UV_SMOOTH_PRED`), ours was 0, which flips
5200 // `av1_use_intra_edge_upsample(8, 4, -6, type)` (`blk_wh == 12`:
5201 // false for type 1, TRUE for type 0) and upsampled an edge libaom
5202 // leaves alone -- +1 on rows 2/3 of that block and every chroma block
5203 // predicting from it (class `context-read-from-one-cell`).
5204 self.smooth_uv_neighbour_unsnapped(mi_r & !1, mi_c & !1, r, c)
5205 }
5206
5207 /// [`Self::smooth_uv_neighbour`] without the chroma-reference snap, i.e.
5208 /// read off the mi passed in exactly. Only the 16x4/4x16 pair witness
5209 /// counter wants this: it measures how often the snap CHANGES the answer,
5210 /// which is what the lane-kf1200/kf900 chroma-reference fix buys. Every
5211 /// decode path uses the snapping form.
5212 fn smooth_uv_neighbour_unsnapped(
5213 &self,
5214 mi_r: usize,
5215 mi_c: usize,
5216 r: usize,
5217 c: usize,
5218 ) -> bool {
5219 // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the
5220 // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid
5221 // array that `start_tile` does not clear, so a block on a tile's first
5222 // mi row used to read the uv_mode of the block above it in the tile
5223 // ABOVE and filter its chroma edge at that neighbour's strength
5224 // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block
5225 // at chroma (120, 32), the top-right tile's first block).
5226 let have_above = mi_r > self.tile_row0_mi;
5227 let have_left = mi_c > self.tile_col0_mi;
5228 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
5229 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
5230 {
5231 UV_TILE_EDGE_SUPPRESSED_HITS.with(|h| h.set(h.get() + 1));
5232 }
5233 let above = match self.uv_mode_col.get(mi_c) {
5234 Some(&(row, m)) if have_above && row == mi_r - 1 => m,
5235 _ if have_above => self.above_uv_mode[c],
5236 _ => DC_PRED,
5237 };
5238 let left = match self.uv_mode_row.get(mi_r) {
5239 Some(&(col, m)) if have_left && col == mi_c - 1 => m,
5240 _ if have_left => self.left_uv_mode[r],
5241 _ => DC_PRED,
5242 };
5243 // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs
5244 // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would
5245 // have been filtered at the wrong strength by the coarse map alone.
5246 if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] {
5247 UV_MODE_MI_OVERRIDE_HITS.with(|h| h.set(h.get() + 1));
5248 }
5249 is_smooth_mode(above) || is_smooth_mode(left)
5250 }
5251
5252 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
5253 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
5254 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
5255 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
5256 /// holding an OLDER, larger block's mode -- it only ever recorded into the
5257 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
5258 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
5259 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
5260 /// a different CDF for the same mode value).
5261 /// lane-rectsplitx r2: availability-correct above/left luma modes for a
5262 /// block whose top-left mi is `(mi_r, mi_c)`. libaom reads `above_mbmi`
5263 /// only when `up_available` and `left_mbmi` only when `left_available`;
5264 /// the coarse [`SUB`] bands cannot express that, and with 8-px strips they
5265 /// actively lie -- four 32x8 strips of one `HORZ_4` share ONE 16x16
5266 /// `left_mode` cell, so the second strip at tile column 0 read the FIRST
5267 /// strip's mode as its "left neighbour" (measured on the band fixture at
5268 /// mi(10,0): mode 2 where libaom has DC, a different `kf_y_mode` row).
5269 fn modes_above_left_mi(
5270 &self,
5271 mi_r: usize,
5272 mi_c: usize,
5273 fallback: (usize, usize),
5274 ) -> (usize, usize) {
5275 let above = if mi_r > self.tile_row0_mi {
5276 self.mode_above_mi(mi_r, mi_c).unwrap_or(fallback.0)
5277 } else {
5278 DC_PRED
5279 };
5280 let left = if mi_c > self.tile_col0_mi {
5281 self.mode_left_mi(mi_r, mi_c).unwrap_or(fallback.1)
5282 } else {
5283 DC_PRED
5284 };
5285 (above, left)
5286 }
5287
5288 /// lane-modectx r1: the coarse-[`SUB`]-grid entry point, now availability
5289 /// correct. The mi-exact lookups already refuse to cross a tile edge, but
5290 /// their FALLBACK (`above_mode`/`left_mode`) did not: `left_mode` is reset
5291 /// per superblock row and never per tile, so the first block column of
5292 /// tile 2..N read the previous tile's mode as its left neighbour, and the
5293 /// above band survives across a tile ROW boundary the same way lane-mtfix's
5294 /// `above_uv_mode` did. libaom reads `above_mbmi`/`left_mbmi` only when
5295 /// `up_available`/`left_available` and uses DC_PRED otherwise
5296 /// ([`Self::modes_above_left_mi`]).
5297 fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
5298 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
5299 let (above, left) =
5300 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));
5301 if above != self.above_mode[c] || left != self.left_mode[r] {
5302 MODE_MI_OVERRIDE_HITS.with(|h| h.set(h.get() + 1));
5303 }
5304 // A neighbour the coarse band offered where the tile edge makes it
5305 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).
5306 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)
5307 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)
5308 {
5309 MODE_TILE_EDGE_COARSE_LEAKS.with(|h| h.set(h.get() + 1));
5310 }
5311 (above, left)
5312 }
5313
5314 fn record_rect(
5315 &mut self,
5316 at: (usize, usize),
5317 w: usize,
5318 h: usize,
5319 mode: usize,
5320 uv_mode: usize,
5321 grids: &[Vec<i32>; 3],
5322 ) {
5323 self.record_rect_mi(sub16_to_mi(at), w, h, mode, uv_mode, grids);
5324 }
5325
5326 /// [`Self::record_rect`] in mi (4 px) units -- lane-inter4 r1: a
5327 /// 32x8/8x32 strip of a 32-level 1:4 partition sits at an 8-px offset the
5328 /// [`SUB`]-unit `at` cannot name. The coarse 16-px bands are still keyed
5329 /// by the enclosing cell (a sub-16 extent writes none of them, exactly as
5330 /// the [`SUB`]-unit path does).
5331 fn record_rect_mi(
5332 &mut self,
5333 at_mi: (usize, usize),
5334 w: usize,
5335 h: usize,
5336 mode: usize,
5337 uv_mode: usize,
5338 grids: &[Vec<i32>; 3],
5339 ) {
5340 let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI));
5341 // lane-inter4 r2: a strip whose own footprint runs past the frame's
5342 // last 16-px column/row stamps only the cells that exist (libaom's
5343 // arrays are padded past the frame and those cells are never read).
5344 for cell in 0..w / SUB {
5345 if c + cell >= self.above_mode.len() {
5346 break;
5347 }
5348 self.above_mode[c + cell] = mode;
5349 self.above_uv_mode[c + cell] = uv_mode;
5350 self.above_side[c + cell] = w;
5351 }
5352 for cell in 0..h / SUB {
5353 if r + cell >= self.left_mode.len() {
5354 break;
5355 }
5356 self.left_mode[r + cell] = mode;
5357 self.left_uv_mode[r + cell] = uv_mode;
5358 self.left_side[r + cell] = h;
5359 }
5360 self.record_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, mode);
5361 self.record_uv_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, uv_mode);
5362 self.record_mi_rect(at_mi, w, h, grids);
5363 }
5364
5365 /// The coefficient-context half of [`Self::record`], taking the block's
5366 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
5367 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
5368 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
5369 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
5370 self.record_mi_rect(at_mi, side, side, grids);
5371 }
5372
5373 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
5374 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
5375 fn record_mi_rect(
5376 &mut self,
5377 at_mi: (usize, usize),
5378 w: usize,
5379 h: usize,
5380 grids: &[Vec<i32>; 3],
5381 ) {
5382 let (mi_r, mi_c) = at_mi;
5383 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
5384 let (w_mi, h_mi) = (w / MI, h / MI);
5385 for cell in 0..h_mi {
5386 if let Some(slot) = self.left_side_mi.get_mut(mi_r + cell) {
5387 *slot = h;
5388 }
5389 }
5390 for cell in 0..w_mi {
5391 if let Some(slot) = self.above_side_mi.get_mut(mi_c + cell) {
5392 *slot = w;
5393 }
5394 }
5395 // A chroma 4x4 unit straddling the true luma edge is still whole in
5396 // chroma's own halved grid, so libaom rounds the luma bound up to the
5397 // plane's own 4x4 unit before clamping a subsampled plane
5398 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
5399 let round_up_even = |n: usize| n.div_ceil(2) * 2;
5400 let bound_h = [
5401 self.mi_rows,
5402 round_up_even(self.mi_rows),
5403 round_up_even(self.mi_rows),
5404 ];
5405 let bound_w = [
5406 self.mi_cols,
5407 round_up_even(self.mi_cols),
5408 round_up_even(self.mi_cols),
5409 ];
5410 for cell in 0..h_mi {
5411 self.left[mi_r + cell] = std::array::from_fn(|plane| {
5412 if cell < h_mi.min(bound_h[plane].saturating_sub(mi_r)) {
5413 states[plane]
5414 } else {
5415 Default::default()
5416 }
5417 });
5418 }
5419 for cell in 0..w_mi {
5420 self.above[mi_c + cell] = std::array::from_fn(|plane| {
5421 if cell < w_mi.min(bound_w[plane].saturating_sub(mi_c)) {
5422 states[plane]
5423 } else {
5424 Default::default()
5425 }
5426 });
5427 }
5428 }
5429
5430 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
5431 /// inside a coded block whose luma transform is smaller than its own
5432 /// side (`TxMode::Select`): the real per-transform-unit coefficient
5433 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
5434 /// coarse per-block `tx_grid`/`fill_lf_grid` state
5435 /// [`Self::record_split_luma`] still writes once for the whole block.
5436 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
5437 /// the caller's own [`Self::record_split_luma`] call sets those once,
5438 /// at the block's own true side, not this TU's.
5439 fn record_mi_luma(&mut self, at_mi: (usize, usize), tx_px: usize, grid: &[i32]) {
5440 self.record_mi_luma_rect(at_mi, tx_px, tx_px, grid);
5441 }
5442
5443 /// [`Self::record_mi_luma`] for ONE CHROMA transform unit of a block whose
5444 /// uv plane block is several units (lane-sb128b r2: a 128x128 block's
5445 /// 64x64 uv plane block is four TX_32X32 units, `av1_get_max_uv_txsize`).
5446 /// `w_px`/`h_px` are the unit's extent in LUMA pixels -- the chroma
5447 /// coefficient-context arrays are indexed by luma mi, the convention
5448 /// [`Self::record_split_luma_rect_mi`] already writes them in, frame-edge
5449 /// clamp included.
5450 fn record_mi_chroma(
5451 &mut self,
5452 (mi_r, mi_c): (usize, usize),
5453 w_px: usize,
5454 h_px: usize,
5455 plane: usize,
5456 grid: &[i32],
5457 ) {
5458 let round_up_even = |n: usize| n.div_ceil(2) * 2;
5459 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
5460 let state = neighbour_state(grid);
5461 for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) {
5462 self.left[mi_r + cell][plane] = state;
5463 }
5464 for cell in 0..(w_px / MI).min(bound_w.saturating_sub(mi_c)) {
5465 self.above[mi_c + cell][plane] = state;
5466 }
5467 }
5468
5469 /// [`Self::record_mi_luma`] for a RECTANGULAR transform unit (lane-rectsplitx
5470 /// r1): the above context spans the unit's width, the left context its
5471 /// height, which for a square unit is the same loop it always was.
5472 fn record_mi_luma_rect(
5473 &mut self,
5474 (mi_r, mi_c): (usize, usize),
5475 w_px: usize,
5476 h_px: usize,
5477 grid: &[i32],
5478 ) {
5479 let state = neighbour_state(grid);
5480 for cell in 0..h_px / MI {
5481 if mi_r + cell < self.mi_rows {
5482 self.left[mi_r + cell][0] = state;
5483 }
5484 }
5485 for cell in 0..w_px / MI {
5486 if mi_c + cell < self.mi_cols {
5487 self.above[mi_c + cell][0] = state;
5488 }
5489 }
5490 }
5491
5492 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
5493 /// block whose luma was decoded as several transform units through
5494 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
5495 /// whole-block luma write -- everything [`Self::record`] does except
5496 /// plane 0, which is already correct per-TU by the time this runs.
5497 fn record_split_luma(
5498 &mut self,
5499 at: (usize, usize),
5500 side: usize,
5501 mode: usize,
5502 uv_mode: usize,
5503 chroma_grids: [&[i32]; 2],
5504 ) {
5505 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
5506 }
5507
5508 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
5509 /// extents in pixels (lane-rectsplit r1), the same relationship
5510 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
5511 /// luma transform split into several square units needs exactly this
5512 /// bookkeeping, at its own true rectangular extents.
5513 fn record_split_luma_rect(
5514 &mut self,
5515 at: (usize, usize),
5516 w: usize,
5517 h: usize,
5518 mode: usize,
5519 uv_mode: usize,
5520 chroma_grids: [&[i32]; 2],
5521 ) {
5522 let (r, c) = at;
5523 self.record_split_luma_rect_mi(
5524 (r * (SUB / MI), c * (SUB / MI)),
5525 w,
5526 h,
5527 mode,
5528 uv_mode,
5529 chroma_grids,
5530 );
5531 }
5532
5533 /// [`Self::record_split_luma_rect`] addressed in mi units (lane-rectsplitx
5534 /// r1) -- a strip 8 px tall starts mid-[`SUB`]-cell, which the coarse
5535 /// `(r, c)` form cannot name. The coarse mode/side arrays are stamped for
5536 /// every cell the strip TOUCHES (`div_ceil`), last writer wins, the
5537 /// convention [`decode_block_rect4`] already established for 1:4 strips.
5538 fn record_split_luma_rect_mi(
5539 &mut self,
5540 at_mi: (usize, usize),
5541 w: usize,
5542 h: usize,
5543 mode: usize,
5544 uv_mode: usize,
5545 chroma_grids: [&[i32]; 2],
5546 ) {
5547 let (mi_r, mi_c) = at_mi;
5548 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
5549 for cell in 0..w.div_ceil(SUB) {
5550 if c + cell >= self.above_mode.len() {
5551 break;
5552 }
5553 self.above_mode[c + cell] = mode;
5554 self.above_uv_mode[c + cell] = uv_mode;
5555 self.above_side[c + cell] = w;
5556 }
5557 for cell in 0..h.div_ceil(SUB) {
5558 if r + cell >= self.left_mode.len() {
5559 break;
5560 }
5561 self.left_mode[r + cell] = mode;
5562 self.left_uv_mode[r + cell] = uv_mode;
5563 self.left_side[r + cell] = h;
5564 }
5565
5566 let (w_mi, h_mi) = (w / MI, h / MI);
5567 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
5568 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
5569 for cell in 0..h_mi {
5570 if let Some(slot) = self.left_side_mi.get_mut(mi_r + cell) {
5571 *slot = h;
5572 }
5573 }
5574 for cell in 0..w_mi {
5575 if let Some(slot) = self.above_side_mi.get_mut(mi_c + cell) {
5576 *slot = w;
5577 }
5578 }
5579 let round_up_even = |n: usize| n.div_ceil(2) * 2;
5580 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
5581 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
5582 let plane = plane_idx + 1;
5583 let state = neighbour_state(grid);
5584 for cell in 0..h_mi {
5585 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
5586 self.left[mi_r + cell][plane] = state;
5587 }
5588 }
5589 for cell in 0..w_mi {
5590 if cell < w_mi.min(bound_w.saturating_sub(mi_c)) {
5591 self.above[mi_c + cell][plane] = state;
5592 }
5593 }
5594 }
5595 }
5596}
5597
5598/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
5599/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
5600/// exactly — including its skip context, which the real key-frame writer
5601/// always writes at a fixed context of zero (it never tracks a neighbour-based
5602/// one for intra blocks; that is the inter-frame writer's rule instead).
5603/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
5604/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
5605/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
5606/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
5607/// plain DC chroma.
5608/// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which
5609/// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's
5610/// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode
5611/// instead (the defect commit 1a89ed9 fixed at the square sites).
5612fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize {
5613 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
5614 filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi])
5615}
5616
5617/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
5618/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
5619/// bound (spec `filter_intra_mode_info` never reads a symbol there).
5620fn filter_intra_size_class(side: usize) -> Option<usize> {
5621 match side {
5622 4 => Some(0),
5623 8 => Some(1),
5624 16 => Some(2),
5625 32 => Some(3),
5626 _ => None,
5627 }
5628}
5629
5630/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
5631/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
5632/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
5633/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
5634fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
5635 match (bw, bh) {
5636 (32, 16) => Some(4),
5637 (16, 32) => Some(5),
5638 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
5639 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
5640 // here dropped that symbol on every DC_PRED strip of that size and
5641 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
5642 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
5643 (16, 8) => Some(6),
5644 (8, 16) => Some(7),
5645 // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <=
5646 // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of
5647 // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0.
5648 (4, 8) => Some(8),
5649 (8, 4) => Some(9),
5650 // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair
5651 // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no
5652 // `use_filter_intra` symbol on those strips although aomenc writes
5653 // one for every DC_PRED block of that shape with
5654 // `--enable-filter-intra=1` (its default), silently desyncing the
5655 // tile (class symbol-consumption-gap).
5656 (32, 8) => Some(10),
5657 (8, 32) => Some(11),
5658 // lane-r14: the 16x16-level 1:4 pair (`decode_rect4_16`'s 16x4/4x16
5659 // strips), rows 17/16 of `default_filter_intra_cdfs`.
5660 (16, 4) => Some(12),
5661 (4, 16) => Some(13),
5662 _ if bw == bh => filter_intra_size_class(bw),
5663 _ => None,
5664 }
5665}
5666
5667/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
5668/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
5669/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
5670/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
5671/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
5672fn palette_bsize_ctx(side: usize) -> Option<usize> {
5673 palette_bsize_ctx_wh(side, side)
5674}
5675
5676/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
5677/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
5678/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
5679/// for ANY bsize, not just the square ones a hand-picked table happened to
5680/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
5681/// row breaks the moment its indexing field moves off the diagonal, and a
5682/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
5683/// block dimension is a power of two, so `bw*bh` always is too and
5684/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
5685/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
5686fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
5687 // lane-r14: `av1_allow_palette`'s bound is `sb_type >= BLOCK_8X8` by the
5688 // BLOCK_SIZES_ALL enum INDEX, which the 1:4 shapes BLOCK_4X16 (16) and
5689 // BLOCK_16X4 (17) clear -- a 64-pixel block, so `av1_get_palette_bsize_ctx`
5690 // (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`) is 0 for them, exactly as
5691 // for an 8x8. Reading the dimension bound as "both sides >= 8" dropped
5692 // `palette_y_mode` on every 16x4/4x16 strip of a screen-content frame.
5693 if bw > 64 || bh > 64 || bw * bh < 64 {
5694 return None;
5695 }
5696 Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
5697}
5698
5699/// A just-decoded palette-Y block's own size, base colours (only the first
5700/// `size` entries are real), and per-pixel colour-index map (`side*side`,
5701/// row-major, each entry `< size`).
5702struct PaletteY {
5703 size: usize,
5704 colors: [u16; 8],
5705 map: Vec<u8>,
5706}
5707
5708/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
5709/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
5710/// shared between U and V, both co-located after 4:2:0 subsampling) plus
5711/// each plane's own base colours.
5712struct PaletteUv {
5713 size: usize,
5714 u_colors: [u16; 8],
5715 v_colors: [u16; 8],
5716 map: Vec<u8>,
5717}
5718
5719/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
5720/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
5721/// `get_unsigned_bits`, which is the same formula): smallest `n` with
5722/// `2^n >= x`, `0` for `x <= 1`.
5723fn ceil_log2(x: u32) -> u32 {
5724 if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() }
5725}
5726
5727/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
5728/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
5729fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
5730 let l = ceil_log2(n as u32);
5731 let m = (1usize << l) - n;
5732 let v = dec.literal(l - 1) as usize;
5733 if v < m {
5734 v
5735 } else {
5736 (v << 1) - m + dec.literal(1) as usize
5737 }
5738}
5739
5740/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
5741/// colours (already-known, from the above/left neighbours) with the
5742/// ascending `transmitted` ones (delta-coded off the wire) back into one
5743/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
5744/// value picks the cached copy first, matching the C `<=`.
5745fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
5746 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
5747 let (mut ci, mut ti) = (0, 0);
5748 while ci < cached.len() && ti < transmitted.len() {
5749 if cached[ci] <= transmitted[ti] {
5750 out.push(cached[ci]);
5751 ci += 1;
5752 } else {
5753 out.push(transmitted[ti]);
5754 ti += 1;
5755 }
5756 }
5757 out.extend_from_slice(&cached[ci..]);
5758 out.extend_from_slice(&transmitted[ti..]);
5759 out
5760}
5761
5762/// `read_palette_colors_y` (decodemv.c:478), at the sequence's real
5763/// `bit_depth` -- lane-kf900 r3: every raw literal here (the first colour,
5764/// each delta's width, the `range` bound and the clamp) is sized by
5765/// `bit_depth`, and hardcoding 8 read 2 bits too few per colour on every
5766/// 10-bit palette block. Raw literals are EQUIPROBABLE, and at the ranges
5767/// this stream reaches (e.g. 62728) an equiprobable read is a FIXED POINT of
5768/// the msac range, so a cross-decoder range ladder stays bit-identical
5769/// through the whole miscount -- only the decoded VALUE differs (class
5770/// `compare-range-not-tell`'s blind spot). (this
5771/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
5772/// (one flag bit each, in cache order), then delta-codes the remainder
5773/// (first value raw, each following delta `>= 1` off a shrinking bit width),
5774/// and merges the two ascending lists back together.
5775fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> [u16; 8] {
5776 let mut cached = Vec::with_capacity(n);
5777 for &c in cache {
5778 if cached.len() >= n {
5779 break;
5780 }
5781 if dec.literal(1) == 1 {
5782 cached.push(c);
5783 }
5784 }
5785 let bd = u32::from(bit_depth());
5786 let max_val = (1i32 << bd) - 1;
5787 let mut colors = [0u16; 8];
5788 let n_cached = cached.len();
5789 if n_cached < n {
5790 let mut transmitted = Vec::with_capacity(n - n_cached);
5791 let first = dec.literal(bd) as u16;
5792 transmitted.push(first);
5793 if n_cached + 1 < n {
5794 let min_bits = bd - 3;
5795 let mut bits = min_bits + dec.literal(2);
5796 let mut range = (1i32 << bd) - i32::from(first) - 1;
5797 for _ in (n_cached + 1)..n {
5798 let delta = dec.literal(bits) as i32 + 1;
5799 let prev = *transmitted.last().unwrap();
5800 let val = (i32::from(prev) + delta).clamp(0, max_val) as u16;
5801 range -= i32::from(val) - i32::from(prev);
5802 bits = bits.min(ceil_log2(range.max(0) as u32));
5803 transmitted.push(val);
5804 }
5805 }
5806 let merged = merge_colors(&transmitted, &cached);
5807 colors[..n].copy_from_slice(&merged);
5808 } else {
5809 colors[..n].copy_from_slice(&cached[..n]);
5810 }
5811 colors
5812}
5813
5814/// `read_palette_colors_uv` (decodemv.c:509), at the sequence's real
5815/// `bit_depth` (see [`read_palette_colors_y`]): U reads
5816/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
5817/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
5818/// unbiased by `+1` -- both differences from Y's own reader, matching the C
5819/// side by side). V never uses a cache: a leading bit picks either `n` raw
5820/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
5821/// rather than clamp.
5822fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> ([u16; 8], [u16; 8]) {
5823 let mut cached = Vec::with_capacity(n);
5824 for &c in cache {
5825 if cached.len() >= n {
5826 break;
5827 }
5828 if dec.literal(1) == 1 {
5829 cached.push(c);
5830 }
5831 }
5832 let bd = u32::from(bit_depth());
5833 let max_val = 1i32 << bd;
5834 let mut u_colors = [0u16; 8];
5835 let n_cached = cached.len();
5836 if n_cached < n {
5837 let mut transmitted = Vec::with_capacity(n - n_cached);
5838 let first = dec.literal(bd) as u16;
5839 transmitted.push(first);
5840 if n_cached + 1 < n {
5841 let min_bits = bd - 3;
5842 let mut bits = min_bits + dec.literal(2);
5843 let mut range = max_val - i32::from(first);
5844 for _ in (n_cached + 1)..n {
5845 let delta = dec.literal(bits) as i32;
5846 let prev = *transmitted.last().unwrap();
5847 let val = (i32::from(prev) + delta).clamp(0, max_val - 1) as u16;
5848 range -= i32::from(val) - i32::from(prev);
5849 bits = bits.min(ceil_log2(range.max(0) as u32));
5850 transmitted.push(val);
5851 }
5852 }
5853 let merged = merge_colors(&transmitted, &cached);
5854 u_colors[..n].copy_from_slice(&merged);
5855 } else {
5856 u_colors[..n].copy_from_slice(&cached[..n]);
5857 }
5858 let mut v_colors = [0u16; 8];
5859 if dec.literal(1) == 1 {
5860 let min_bits_v = bd - 4;
5861 let bits = min_bits_v + dec.literal(2);
5862 v_colors[0] = dec.literal(bd) as u16;
5863 for i in 1..n {
5864 let mut delta = dec.literal(bits) as i32;
5865 if delta != 0 && dec.literal(1) == 1 {
5866 delta = -delta;
5867 }
5868 let mut val = i32::from(v_colors[i - 1]) + delta;
5869 if val < 0 {
5870 val += max_val;
5871 }
5872 if val >= max_val {
5873 val -= max_val;
5874 }
5875 v_colors[i] = val as u16;
5876 }
5877 } else {
5878 for i in 0..n {
5879 v_colors[i] = dec.literal(bd) as u16;
5880 }
5881 }
5882 (u_colors, v_colors)
5883}
5884
5885/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
5886/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
5887/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
5888const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
5889
5890/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
5891/// map's own per-pixel context and colour-order permutation, from the
5892/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
5893/// selection sort). `map`'s stride is `side` (this decoder never crops a
5894/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
5895/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
5896/// actual colour index to store.
5897fn palette_color_index_context(
5898 map: &[u8],
5899 side: usize,
5900 row: usize,
5901 col: usize,
5902 n: usize,
5903) -> (usize, [u8; 8]) {
5904 let left = if col >= 1 { Some(map[row * side + col - 1]) } else { None };
5905 let up_left = if col >= 1 && row >= 1 {
5906 Some(map[(row - 1) * side + col - 1])
5907 } else {
5908 None
5909 };
5910 let up = if row >= 1 { Some(map[(row - 1) * side + col]) } else { None };
5911 let mut scores = [0i32; 8];
5912 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
5913 if let Some(v) = neighbour {
5914 scores[v as usize] += weight;
5915 }
5916 }
5917 let mut color_order = [0u8; 8];
5918 for i in 0..8 {
5919 color_order[i] = i as u8;
5920 }
5921 for i in 0..3 {
5922 let mut max = scores[i];
5923 let mut max_idx = i;
5924 for j in (i + 1)..n {
5925 if scores[j] > max {
5926 max = scores[j];
5927 max_idx = j;
5928 }
5929 }
5930 if max_idx != i {
5931 let max_score = scores[max_idx];
5932 let max_color = color_order[max_idx];
5933 for k in (i + 1..=max_idx).rev() {
5934 scores[k] = scores[k - 1];
5935 color_order[k] = color_order[k - 1];
5936 }
5937 scores[i] = max_score;
5938 color_order[i] = max_color;
5939 }
5940 }
5941 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
5942 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
5943 (ctx as usize, color_order)
5944}
5945
5946/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
5947/// map's wavefront decode over a `side x side` grid -- this decoder's
5948/// palette blocks are always square and never straddle the frame's true
5949/// (possibly odd) edge without already allocating the full `side*side`
5950/// region (every other skip/residual path here does the same), so no
5951/// rows/cols-vs-plane_width/height cropping special case is needed, unlike
5952/// libaom's own non-block-aligned split.
5953fn decode_color_index_map(
5954 dec: &mut SymbolDecoder,
5955 cdfs: &mut Cdfs,
5956 n: usize,
5957 side: usize,
5958 uv: bool,
5959) -> Vec<u8> {
5960 decode_color_index_map_wh(dec, cdfs, n, side, side, uv)
5961}
5962
5963/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
5964/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
5965/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
5966/// independently rather than one shared `side` -- the square call above is
5967/// just `bw == bh`.
5968fn decode_color_index_map_wh(
5969 dec: &mut SymbolDecoder,
5970 cdfs: &mut Cdfs,
5971 n: usize,
5972 bw: usize,
5973 bh: usize,
5974 uv: bool,
5975) -> Vec<u8> {
5976 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
5977 let mut map = vec![0u8; bw * bh];
5978 if trace {
5979 let (rng, _) = dec.debug_state();
5980 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
5981 }
5982 map[0] = read_uniform(dec, n) as u8;
5983 if trace {
5984 let (rng, _) = dec.debug_state();
5985 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
5986 }
5987 for i in 1..(bw + bh - 1) {
5988 let j_hi = i.min(bw - 1);
5989 let j_lo = i.saturating_sub(bh - 1);
5990 for j in (j_lo..=j_hi).rev() {
5991 let row = i - j;
5992 let col = j;
5993 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
5994 if trace {
5995 let (rng, _) = dec.debug_state();
5996 eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} rng={rng}");
5997 }
5998 let symbol = if uv {
5999 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
6000 } else {
6001 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
6002 };
6003 map[row * bw + col] = color_order[symbol];
6004 if trace {
6005 let (rng, _) = dec.debug_state();
6006 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
6007 }
6008 }
6009 }
6010 map
6011}
6012
6013/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
6014/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
6015/// size class comes from [`filter_intra_size_class_rect`] instead of the
6016/// square-only [`filter_intra_size_class`], and the palette read (when
6017/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
6018/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
6019/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
6020/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
6021#[allow(clippy::too_many_arguments)]
6022fn read_intra_mode_rect(
6023 dec: &mut SymbolDecoder,
6024 cdfs: &mut Cdfs,
6025 above_mode: usize,
6026 left_mode: usize,
6027 cfl: bool,
6028 // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall
6029 // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads
6030 // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's
6031 // chroma is coded once, on the closing strip). Every other caller is a
6032 // block big enough to own its chroma and passes `true`.
6033 has_chroma: bool,
6034 bw: usize,
6035 bh: usize,
6036 enable_filter_intra: bool,
6037 skip_ctx: usize,
6038 allow_screen_content_tools: bool,
6039 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
6040 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
6041 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
6042 palette: Option<(usize, &[u16])>,
6043 palette_uv_cache: &[u16],
6044 mi_r: usize,
6045 mi_c: usize,
6046) -> Result<(
6047 bool,
6048 usize,
6049 i32,
6050 usize,
6051 i32,
6052 Option<(i32, i32)>,
6053 Option<usize>,
6054 Option<PaletteY>,
6055 Option<PaletteUv>,
6056)> {
6057 let ec_istep = std::env::var_os("EC_TRACE_MODE_STEP").is_some();
6058 if ec_istep {
6059 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
6060 // (decodemv.c:818), printed at the same point: before the first
6061 // mode-info symbol of the block, so a cross-decoder range ladder can
6062 // be keyed on the BLOCK, not just on the symbol sequence.
6063 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);
6064 }
6065 macro_rules! istep {
6066 ($name:literal, $val:expr) => {
6067 if ec_istep {
6068 let (rng, _) = dec.debug_state();
6069 eprintln!(
6070 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
6071 $name, $val
6072 );
6073 }
6074 };
6075 }
6076 // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is
6077 // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at
6078 // the one point every rect caller routes through, so no call site can
6079 // offer the 14-symbol CFL alphabet on a 64-axis block (class
6080 // wrong-alphabet-same-value: same value, wrong interval, silent desync).
6081 // This funnel covers the lane-intra14 intra-1:4-in-inter callers too: they
6082 // reach their chroma through this same reader, never a private CFL read.
6083 let cfl = if cfl && bw.max(bh) > 32 {
6084 NOCFL_UV_MODE_HITS.with(|c| c.set(c.get() + 1));
6085 false
6086 } else {
6087 cfl
6088 };
6089 // lane-intra14 r1: on the INTER block path everything up to and including
6090 // `is_inter` was already read by [`decode_inter_block`], so this reader
6091 // starts at the mode syntax with the `skip` that caller read.
6092 let inter = INTRA_IN_INTER_MODE.with(std::cell::Cell::get);
6093 let skip = if let Some((_, skip)) = inter {
6094 skip
6095 } else {
6096 // Same `intra_segment_id` placement as the square reader above.
6097 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
6098 if seg_id_pre_skip() {
6099 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);
6100 }
6101 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
6102 istep!("skip", skip as i32);
6103 if !seg_id_pre_skip() {
6104 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);
6105 }
6106 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
6107 istep!("cdef", 0);
6108 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
6109 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
6110 // `false`.
6111 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip);
6112 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip);
6113 istep!("dq", 0);
6114 skip
6115 };
6116 // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after
6117 // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the
6118 // `use_intrabc` symbol is read for EVERY intra block of an `allow_intrabc`
6119 // frame -- `av1_allow_intrabc` is a frame-level test with no shape term, so
6120 // rect strips read it exactly like square leaves ([`read_intra_mode`],
6121 // [`read_intra_mode_sub8`]). Missing it here desynced the arithmetic
6122 // decoder at the FIRST symbol of the first rect block of every
6123 // `--tune-content=screen` key frame. Reconstruction of a real intrabc
6124 // block at this shape is out of scope, so the flag is consumed and
6125 // refused by name when it fires.
6126 if allow_intrabc_frame() {
6127 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
6128 RECT_INTRABC_READS.with(|c| c.set(c.get() + 1));
6129 istep!("intrabc", use_intrabc as i32);
6130 if use_intrabc {
6131 INTRABC_HITS.with(|c| c.set(c.get() + 1));
6132 return Err(unsupported(
6133 "intra block copy on a HORZ/VERT/1:4 rect intra strip (reconstruction is not ported at this shape)",
6134 ));
6135 }
6136 }
6137 // libaom `read_intra_block_mode_info` (decodemv.c:1189) vs the key
6138 // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode`
6139 // off `kf_y_mode_cdf[above][left]`).
6140 let mode = if let Some((size_group, _)) = inter {
6141 dec.symbol(&mut cdfs.y_mode[size_group])
6142 } else {
6143 let above_ctx = INTRA_MODE_CTX[above_mode];
6144 let left_ctx = INTRA_MODE_CTX[left_mode];
6145 dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx])
6146 };
6147 istep!("mode", mode as i32);
6148 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
6149 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
6150 } else {
6151 0
6152 };
6153 istep!("angle_y", angle_delta_y);
6154 // lane-sb128c r3 (class sweep): libaom `read_intra_mode_uv(.., is_cfl_allowed(xd), ..)`
6155 // and `is_cfl_allowed` (blockd.h) is `block_size_wide[bsize] <= 32 &&
6156 // block_size_high[bsize] <= 32` on the LUMA bsize. Deciding the alphabet
6157 // here, from the block's own size, is the single point every caller routes
6158 // through -- a caller passing `true` for a >32 strip used to pick the
6159 // 14-symbol CFL CDF, same value but a different range (class
6160 // wrong-alphabet-same-value).
6161 let cfl = cfl && bw <= 32 && bh <= 32;
6162 let uv_mode = if !has_chroma {
6163 DC_PRED
6164 } else if cfl {
6165 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
6166 } else {
6167 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
6168 };
6169 istep!("uv_mode", uv_mode as i32);
6170 let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED {
6171 Some(read_cfl_alphas(dec, cdfs))
6172 } else {
6173 None
6174 };
6175 if has_chroma && (9..=12).contains(&uv_mode) {
6176 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
6177 }
6178 let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) {
6179 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
6180 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
6181 } else {
6182 0
6183 };
6184 istep!("angle_uv", angle_delta_uv);
6185 if angle_delta_uv != 0 {
6186 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
6187 }
6188 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
6189 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
6190 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
6191 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
6192 // colours only here, the colour-index maps deferred past `filter_intra`
6193 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
6194 // runs from the caller, after the whole mode-info read).
6195 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
6196 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
6197 if allow_screen_content_tools
6198 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
6199 {
6200 // r6: this is the exact site the removed blanket refusal used to
6201 // guard -- reached for EVERY rect strip in a screen-content frame,
6202 // independent of whether the block ends up using a palette.
6203 RECT_SCREEN_CONTENT_HITS.with(|c| c.set(c.get() + 1));
6204 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
6205 let use_palette_y =
6206 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
6207 if use_palette_y {
6208 if palette.is_none() {
6209 return Err(unsupported(
6210 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
6211 ));
6212 }
6213 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
6214 let colors = read_palette_colors_y(dec, n, cache);
6215 palette_y_pending = Some((n, colors));
6216 }
6217 let palette_uv_mode_ctx = usize::from(use_palette_y);
6218 // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard.
6219 if has_chroma
6220 && uv_mode == DC_PRED
6221 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
6222 {
6223 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
6224 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache);
6225 palette_uv_pending = Some((n, u_colors, v_colors));
6226 }
6227 }
6228 let mut filter_intra = None;
6229 if std::env::var_os("EC_AV1_TRACE").is_some() {
6230 let (rng, _) = dec.debug_state();
6231 eprintln!(
6232 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
6233 class={:?} rng={rng}",
6234 enable_filter_intra as i32,
6235 filter_intra_size_class_rect(bw, bh)
6236 );
6237 }
6238 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
6239 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
6240 if mode == DC_PRED
6241 && enable_filter_intra
6242 && palette_y_pending.is_none()
6243 && let Some(class) = filter_intra_size_class_rect(bw, bh)
6244 {
6245 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
6246 if std::env::var_os("EC_AV1_TRACE").is_some() {
6247 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
6248 }
6249 istep!("use_filter_intra", use_filter_intra as i32);
6250 if use_filter_intra {
6251 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
6252 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
6253 istep!("filter_intra_mode", fi_mode as i32);
6254 filter_intra = Some(fi_mode);
6255 }
6256 }
6257 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
6258 // same order as [`read_intra_mode`]'s own square path.
6259 let palette_y = palette_y_pending.map(|(n, colors)| {
6260 let map = decode_color_index_map_wh(dec, cdfs, n, bw, bh, false);
6261 PALETTE_HITS.with(|c| c.set(c.get() + 1));
6262 PALETTE_RECT_HITS.with(|c| c.set(c.get() + 1));
6263 PaletteY { size: n, colors, map }
6264 });
6265 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
6266 // `av1_get_plane_block_size(bsize, 1, 1)` (`ss_size_lookup`), NOT a
6267 // plain halving: BLOCK_16X4 subsamples to BLOCK_8X4 and BLOCK_4X16 to
6268 // BLOCK_4X8, both floored at the 4-px transform. Halving the short
6269 // axis to 2 read HALF the colour-index symbols of a 1:4 strip's
6270 // chroma palette and desynced the tile from there.
6271 let (cw, ch) = ((bw / 2).max(4), (bh / 2).max(4));
6272 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, true);
6273 PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
6274 PaletteUv { size: n, u_colors, v_colors, map }
6275 });
6276 Ok((
6277 skip,
6278 mode,
6279 angle_delta_y,
6280 uv_mode,
6281 angle_delta_uv,
6282 alpha,
6283 filter_intra,
6284 palette_y,
6285 palette_uv,
6286 ))
6287}
6288
6289/// Stamps a 1:4 strip's palette state into the coarse above/left arrays.
6290/// `av1_get_palette_cache` reads `xd->above_mbmi`/`xd->left_mbmi`, and inside
6291/// a HORZ_4 (VERT_4) the next strip's ABOVE (LEFT) neighbour is this strip
6292/// while its LEFT (ABOVE) neighbour is still the parent block's. The coarse
6293/// [`SUB`]-cell arrays alias all four strips onto one entry, so writing BOTH
6294/// axes after every strip would hand strip i+1 this strip's colours on the
6295/// wrong axis too -- a wrong cache costs the same bits, so the tile stays in
6296/// sync and only the pixels are wrong (class [[cdf-row-held-constant]]).
6297/// Only the split axis is written until the closing strip, which stamps both
6298/// for whatever follows the parent block.
6299#[allow(clippy::too_many_arguments)]
6300fn record_strip_palette(
6301 n: &mut Neighbours,
6302 at: (usize, usize),
6303 bw: usize,
6304 bh: usize,
6305 y_size: usize,
6306 y_colors: [u16; 8],
6307 uv_size: usize,
6308 uv_colors: [u16; 8],
6309 last: bool,
6310) {
6311 let (r, c) = at;
6312 let horz = bw > bh;
6313 if horz || last {
6314 for cell in 0..(bw / SUB).max(1) {
6315 n.above_palette_size[c + cell] = y_size;
6316 n.above_palette_colors[c + cell] = y_colors;
6317 n.above_palette_uv_size[c + cell] = uv_size;
6318 n.above_palette_uv_colors[c + cell] = uv_colors;
6319 }
6320 }
6321 if !horz || last {
6322 for cell in 0..(bh / SUB).max(1) {
6323 n.left_palette_size[r + cell] = y_size;
6324 n.left_palette_colors[r + cell] = y_colors;
6325 n.left_palette_uv_size[r + cell] = uv_size;
6326 n.left_palette_uv_colors[r + cell] = uv_colors;
6327 }
6328 }
6329}
6330
6331/// [`tx_size_context`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
6332/// `get_tx_size_context` (libaom `pred_common.h`) compares the neighbour
6333/// above against this block's own *width* and the neighbour to the left
6334/// against its own *height* -- for a square block those are the same value,
6335/// which is why the square-only version can get away with one `own_side`.
6336fn tx_size_context_rect(
6337 n: &Neighbours,
6338 (mi_r, mi_c): (usize, usize),
6339 own_w: usize,
6340 own_h: usize,
6341) -> usize {
6342 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w;
6343 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h;
6344 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
6345 eprintln!(
6346 "EC_TXCTX mi_row={mi_r} mi_col={mi_c} w={own_w} h={own_h} above_px={} left_px={} ctx={}",
6347 if mi_r > n.tile_row0_mi { tx_px_at(n, false, mi_r - 1, mi_c) } else { 0 },
6348 if mi_c > n.tile_col0_mi { tx_h_px_at(n, false, mi_r, mi_c - 1) } else { 0 },
6349 usize::from(above) + usize::from(left)
6350 );
6351 }
6352 usize::from(above) + usize::from(left)
6353}
6354
6355/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
6356fn cfl_ac_q3_rect(y: &PlaneBuf, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
6357 let (cw, ch) = (bw / 2, bh / 2);
6358 let mut ac = vec![0i32; cw * ch];
6359 let mut sum = 0i32;
6360 for cy in 0..ch {
6361 for cx in 0..cw {
6362 let (lx, ly) = (px + cx * 2, py + cy * 2);
6363 let q3 = (i32::from(y.data[ly * y.width + lx])
6364 + i32::from(y.data[ly * y.width + lx + 1])
6365 + i32::from(y.data[(ly + 1) * y.width + lx])
6366 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
6367 << 1;
6368 ac[cy * cw + cx] = q3;
6369 sum += q3;
6370 }
6371 }
6372 let num_pel = (cw * ch) as i32;
6373 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
6374 ac.iter_mut().for_each(|v| *v -= avg);
6375 ac
6376}
6377
6378/// Everything a rect strip already read out of the stream before its luma
6379/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
6380/// (nine values that would otherwise be nine more parameters).
6381struct RectStripModes {
6382 skip: bool,
6383 mode: usize,
6384 angle_delta_y: i32,
6385 uv_predict_mode: usize,
6386 angle_delta_uv: i32,
6387 alpha: Option<(i32, i32)>,
6388 filter_intra: Option<usize>,
6389 smooth_neighbor: bool,
6390 smooth_neighbor_uv: bool,
6391 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
6392 /// mapped through the colour table), sliced per transform unit below --
6393 /// palette prediction reads no edge pixels, so a unit's slice of the
6394 /// whole-block map IS its prediction. Without this a palette strip whose
6395 /// transform splits predicted DC and came out flat grey while the entropy
6396 /// stream stayed in sync (the coefficients are read either way).
6397 palette_y: Option<Vec<u16>>,
6398 /// As `palette_y`, for the un-split chroma transform (U, V).
6399 palette_uv: Option<(Vec<u16>, Vec<u16>)>,
6400}
6401
6402/// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth`
6403/// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times
6404/// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the
6405/// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's
6406/// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 ->
6407/// TX_32X16`) and only the second reaches a square -- the reason
6408/// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
6409/// already square) mis-tiled 1:4 strips.
6410fn depth_to_tx_wh(bw: usize, bh: usize, depth: usize) -> (usize, usize) {
6411 let (mut w, mut h) = (bw.min(64), bh.min(64));
6412 for _ in 0..depth {
6413 match w.cmp(&h) {
6414 std::cmp::Ordering::Greater => w /= 2,
6415 std::cmp::Ordering::Less => h /= 2,
6416 std::cmp::Ordering::Equal => {
6417 w /= 2;
6418 h /= 2;
6419 }
6420 }
6421 }
6422 (w, h)
6423}
6424
6425/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
6426/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
6427/// rect path here refused by name until now ("per-unit rect prediction is not
6428/// ported").
6429///
6430/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
6431/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
6432/// strip the very first step already lands on a SQUARE transform
6433/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
6434/// every further step halves a square) -- so each unit is square and reads
6435/// through the ordinary square [`read_plane`]. What is genuinely rectangular
6436/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
6437/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
6438/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
6439/// split by luma's depth.
6440///
6441/// Each unit predicts off whatever the earlier units of this same block
6442/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
6443/// inside `av1_foreach_transformed_block`, raster order), which is exactly
6444/// what predicting the whole strip in one shot got wrong.
6445#[allow(clippy::too_many_arguments)]
6446fn decode_rect_split(
6447 dec: &mut SymbolDecoder,
6448 cdfs: &mut Cdfs,
6449 neighbours: &mut Neighbours,
6450 at_mi: (usize, usize),
6451 bw: usize,
6452 bh: usize,
6453 // The transform unit's own width and height in pixels. Square for every
6454 // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
6455 // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
6456 // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
6457 tx_w: usize,
6458 tx_h: usize,
6459 m: &RectStripModes,
6460 y: &mut PlaneBuf,
6461 u: &mut PlaneBuf,
6462 v: &mut PlaneBuf,
6463 base_q_idx: u8,
6464 reduced_tx_set: bool,
6465) -> Result<()> {
6466 let (mi_r, mi_c) = at_mi;
6467 let (px, py) = (mi_c * MI, mi_r * MI);
6468 let (cpx, cpy) = (px / 2, py / 2);
6469 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
6470 // The chroma transform is picked before any symbol is read, so an
6471 // unsupported chroma shape refuses before this strip desyncs the tile.
6472 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
6473 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
6474 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
6475 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
6476 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
6477 // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32
6478 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx`
6479 // squares a rect transform down to a CDF set by
6480 // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set,
6481 // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets
6482 // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`)
6483 // paths already prove for these same shapes.
6484 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
6485 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
6486 (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])),
6487 (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])),
6488 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
6489 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
6490 _ => None,
6491 };
6492 if !m.skip {
6493 if let Some(i) = match (chroma_w, chroma_h) {
6494 (32, 8) => Some(0),
6495 (8, 32) => Some(1),
6496 (8, 4) => Some(2),
6497 (4, 8) => Some(3),
6498 _ => None,
6499 } {
6500 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
6501 let mut hits = c.get();
6502 hits[i] += 1;
6503 c.set(hits);
6504 });
6505 }
6506 if chroma.is_none() {
6507 // Diagnostic for the next caller that lands here (class
6508 // refusal-names-a-correlate: the message names the tool, not the
6509 // shape); the refusal below keeps its inventory-pinned wording.
6510 eprintln!("EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} chroma={chroma_w}x{chroma_h}");
6511 }
6512 }
6513 // lane-rectsplit r2 (verifier finding): with both callers wired
6514 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
6515 // 64x32/32x64) every shape that reaches here has a table above, so this
6516 // arm is UNREACHABLE today. It stays as the shape guard for the next
6517 // caller -- a new strip size would otherwise hit the `expect` below and
6518 // panic instead of refusing by name -- and so stays in
6519 // `refusal_inventory::REFUSALS`.
6520 if !m.skip && chroma.is_none() {
6521 return Err(unsupported(
6522 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
6523 ));
6524 }
6525 RECT_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
6526 if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 {
6527 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.set(c.get() + 1));
6528 }
6529 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
6530 // A square unit reads through the ordinary square [`read_plane`]; a rect
6531 // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with
6532 // the very tables the unsplit 16x8/32x16 paths use.
6533 let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) {
6534 (w, h) if w == h => None,
6535 (16, 8) | (8, 16) => Some((
6536 if reduced_tx_set {
6537 TxbSet::LumaRect16x8
6538 } else {
6539 TxbSet::LumaRect16x8Set1
6540 },
6541 if tx_w == 16 { &SCAN_16X8[..] } else { &SCAN_8X16[..] },
6542 )),
6543 (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])),
6544 (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])),
6545 _ => {
6546 return Err(unsupported(format!(
6547 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \
6548 coefficient tables for that shape here)"
6549 )))
6550 }
6551 };
6552 // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact
6553 // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole
6554 // frame exactly, two sub-16 split strips in it), but the RECT-unit arm --
6555 // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the
6556 // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the
6557 // per-unit rect walk stay wired above/below; the round that finds that
6558 // defect deletes this refusal and nothing else.
6559 let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set);
6560 let luma_scan = default_scan(tx_w.min(tx_h));
6561 let zero_tu = vec![0i32; tx_w * tx_h];
6562 // The strip's OWN edge availability, the fallback for a transform unit
6563 // whose top-right/bottom-left pixels fall outside the strip.
6564 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
6565 for tu_row in 0..bh / tx_h {
6566 for tu_col in 0..bw / tx_w {
6567 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
6568 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
6569 let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h);
6570 // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged):
6571 // libaom clips `av1_foreach_transformed_block_in_plane` to
6572 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
6573 // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose
6574 // TOP-LEFT sample falls outside the frame is never coded. We read
6575 // coefficients for those phantom units and desynced the stream at
6576 // the very next symbol.
6577 if tu_px >= y.true_width || tu_py >= y.true_height {
6578 continue;
6579 }
6580 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
6581 // transform unit INSIDE a block, which is a different rule from
6582 // the standalone-block table [`Reach::of`] applies -- and the
6583 // reason a depth-2 superblock strip came out one sample off
6584 // before this: `Reach::of(tx, ..)` answered as if the unit were
6585 // its own block at that superblock position.
6586 // * top-right: if the unit's right neighbour is still inside the
6587 // strip the pixels are already reconstructed (`col_off +
6588 // tx_wide < plane_bw`); otherwise only the strip's own top row
6589 // of units can reach past it, through the block-level answer.
6590 // * bottom-left: a unit that is not in the strip's left column
6591 // has none (`col_off > 0` returns 0); inside the strip
6592 // (`row_off + tx_high < plane_bh`) they are the left
6593 // neighbour's, already reconstructed; the last row falls back
6594 // to the block-level answer.
6595 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach);
6596 // The unit's own window on the block's palette prediction.
6597 if let Some(buf) = &m.palette_y {
6598 let tu_buf: Vec<u16> = (0..tx_h)
6599 .flat_map(|i| {
6600 let base = (row_off + i) * bw + col_off;
6601 buf[base..base + tx_w].iter().copied()
6602 })
6603 .collect();
6604 set_palette_pred(tu_buf);
6605 }
6606 if m.skip {
6607 y.reconstruct_rect(
6608 tu_px,
6609 tu_py,
6610 tx_w,
6611 tx_h,
6612 m.mode,
6613 m.angle_delta_y,
6614 tu_reach,
6615 &zero_tu,
6616 None,
6617 m.filter_intra,
6618 m.smooth_neighbor,
6619 );
6620 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
6621 } else if let Some((rect_set, rect_scan)) = luma_rect {
6622 // The rect-unit twin of the square arm below: same contexts,
6623 // same order, through the rect coefficient reader. The
6624 // `tx_type` CDF row of a filter-intra block is
6625 // `fimode_to_intradir[filter_intra_mode]`, never the block's
6626 // own (always DC_PRED) mode -- [`read_plane`] applies that
6627 // for the square arm, so this one must too.
6628 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
6629 // libaom `get_txb_ctx`: a LUMA transform that covers its whole
6630 // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the
6631 // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the
6632 // neighbour-magnitude table is for a unit SMALLER than its
6633 // block. [`decode_block_rect`]'s own unsplit read passes a
6634 // literal 0 for the same reason; this arm applied the table
6635 // unconditionally and desynced every depth-0 rect strip that
6636 // reached it (lane-intrarect r2: ctx 5 where aomdec read 0).
6637 let tu_skip_ctx = if tx_w == bw && tx_h == bh {
6638 0
6639 } else {
6640 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI)
6641 };
6642 let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra));
6643 let (tu_grid, tu_tx_type) = read_coeffs_rect(
6644 dec,
6645 &mut coding,
6646 rect_scan,
6647 tx_w,
6648 tx_h,
6649 tu_skip_ctx,
6650 dc_sign_ctx(tu_around.2),
6651 TxType::DctDct,
6652 )?;
6653 let residual = dequant_and_inverse_typed_wh(
6654 &tu_grid,
6655 tx_w,
6656 tx_h,
6657 crate::decode::bit_depth(),
6658 block_q_idx(),
6659 plane_q_delta(0).0,
6660 plane_q_delta(0).1,
6661 tu_tx_type,
6662 );
6663 y.reconstruct_rect(
6664 tu_px,
6665 tu_py,
6666 tx_w,
6667 tx_h,
6668 m.mode,
6669 m.angle_delta_y,
6670 tu_reach,
6671 &residual,
6672 None,
6673 m.filter_intra,
6674 m.smooth_neighbor,
6675 );
6676 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
6677 } else {
6678 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
6679 // This unit is smaller than the block it sits in, so
6680 // `txb_skip_ctx` is the neighbour-magnitude table, not the
6681 // lone-TU 0 (spec `get_txb_ctx_general`).
6682 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
6683 let tu_grid = read_plane(
6684 dec,
6685 cdfs,
6686 luma_set,
6687 &luma_scan,
6688 0,
6689 tu_around,
6690 m.mode,
6691 m.mode,
6692 m.angle_delta_y,
6693 tu_reach,
6694 y,
6695 tu_px,
6696 tu_py,
6697 tx_w,
6698 tx_w,
6699 base_q_idx,
6700 None,
6701 m.filter_intra,
6702 Some(tu_skip_ctx),
6703 m.smooth_neighbor,
6704 )?;
6705 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
6706 }
6707 }
6708 }
6709 // CHROMA: one un-split rect transform for the whole strip.
6710 let ac = m.alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
6711 let reach = block_reach;
6712 let (u_grid, v_grid) = if m.skip {
6713 let zero = vec![0i32; chroma_w * chroma_h];
6714 if let Some((ub, _)) = &m.palette_uv {
6715 set_palette_pred(ub.clone());
6716 }
6717 u.reconstruct_rect(
6718 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
6719 m.alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv,
6720 );
6721 if let Some((_, vb)) = &m.palette_uv {
6722 set_palette_pred(vb.clone());
6723 }
6724 v.reconstruct_rect(
6725 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
6726 m.alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv,
6727 );
6728 (zero.clone(), zero)
6729 } else {
6730 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
6731 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
6732 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
6733 // so only the 16x8/8x16 pair takes the mode-indexed default.
6734 let default_tx = if chroma_w.max(chroma_h) >= 32 {
6735 TxType::DctDct
6736 } else {
6737 default_intra_tx_type(m.uv_predict_mode as u8)
6738 };
6739 let around = neighbours.around_mi_rect(at_mi, bw, bh);
6740 let mut grids: Vec<Vec<i32>> = Vec::with_capacity(2);
6741 for plane_idx in 1..=2 {
6742 let skip_ctx =
6743 usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
6744 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
6745 let (levels, tx_type) = read_coeffs_rect(
6746 dec,
6747 &mut coding,
6748 chroma_scan,
6749 chroma_w,
6750 chroma_h,
6751 skip_ctx,
6752 dc_sign_ctx(around[plane_idx].2),
6753 default_tx,
6754 )?;
6755 // The same delta_q proof the unsplit rect64 path records
6756 // (lane-rectsplit r4: lifting the split-transform refusal moved
6757 // superblock strips onto this path, so only counting there would
6758 // leave the delta_q gate's counter silent for them).
6759 if bw.max(bh) == 64 && CURRENT_Q_IDX.with(|c| c.get()) != i32::from(base_q_idx) {
6760 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
6761 }
6762 let residual = dequant_and_inverse_typed_wh(
6763 &levels,
6764 chroma_w,
6765 chroma_h,
6766 crate::decode::bit_depth(),
6767 CURRENT_Q_IDX.with(|c| c.get()),
6768 plane_q_delta(plane_idx).0,
6769 plane_q_delta(plane_idx).1,
6770 tx_type,
6771 );
6772 let cfl = m
6773 .alpha
6774 .zip(ac.as_deref())
6775 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
6776 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
6777 if let Some((ub, vb)) = &m.palette_uv {
6778 let buf = if plane_idx == 1 { ub } else { vb };
6779 set_palette_pred(buf.clone());
6780 }
6781 plane.reconstruct_rect(
6782 cpx,
6783 cpy,
6784 chroma_w,
6785 chroma_h,
6786 m.uv_predict_mode,
6787 m.angle_delta_uv,
6788 reach,
6789 &residual,
6790 cfl,
6791 None,
6792 m.smooth_neighbor_uv,
6793 );
6794 grids.push(levels);
6795 }
6796 let mut it = grids.into_iter();
6797 (it.next().unwrap(), it.next().unwrap())
6798 };
6799 neighbours.record_split_luma_rect_mi(
6800 at_mi,
6801 bw,
6802 bh,
6803 m.mode,
6804 m.uv_predict_mode,
6805 [&u_grid, &v_grid],
6806 );
6807 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
6808 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
6809 if std::env::var_os("EC_AV1_TRACE").is_some() {
6810 let (rng, _) = dec.debug_state();
6811 eprintln!(
6812 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
6813 tx={tx_w}x{tx_h} rng={rng}"
6814 );
6815 }
6816 Ok(())
6817}
6818
6819/// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect
6820/// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name
6821/// because it predicts squares only. Every pixel here goes through the rect
6822/// machinery the key-frame paths already prove: [`decode_rect_split`], which
6823/// at `depth == 0` is the unsplit strip as a single transform unit and
6824/// beyond it the per-unit walk of [`depth_to_tx_wh`].
6825///
6826/// What is genuinely different from [`decode_block_rect`] is the mode
6827/// syntax: on an inter frame an intra block reads `y_mode[size_group]` and
6828/// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never
6829/// the key frame's `kf_y_mode` above/left pair. This mirrors the square
6830/// intra-in-inter arm's own reads at the rect footprint, including its
6831/// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe
6832/// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the
6833/// square and this arm) and a nonzero luma angle delta refused by name.
6834///
6835/// The strip's own neighbour records (luma per transform unit, chroma, skip
6836/// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the
6837/// inter-side bands and the mi map.
6838#[allow(clippy::too_many_arguments)]
6839fn decode_intra_rect_in_inter(
6840 dec: &mut SymbolDecoder,
6841 cdfs: &mut Cdfs,
6842 neighbours: &mut Neighbours,
6843 at: (usize, usize),
6844 bw: usize,
6845 bh: usize,
6846 skip: bool,
6847 allow_screen_content_tools: bool,
6848 y: &mut PlaneBuf,
6849 u: &mut PlaneBuf,
6850 v: &mut PlaneBuf,
6851 base_q_idx: u8,
6852) -> Result<()> {
6853 // `at` is in MI units (the inter path's own unit since lane-inter4);
6854 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands
6855 // below are still keyed by.
6856 let (mi_r, mi_c) = at;
6857 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
6858 // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat`
6859 // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 /
6860 // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx
6861 // finding -- the category is NOT the same for every strip size).
6862 // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so
6863 // it is refused by name rather than read from the wrong CDF row.
6864 let (size_group, tx_cat) = match (bw.min(bh), bw.max(bh)) {
6865 (8, 16) => (1usize, 1usize),
6866 (16, 32) => (2, 2),
6867 (32, 64) => (3, 3),
6868 // lane-intra14 r1: the 1:4 strips, read off libaom's own tables --
6869 // `size_group_lookup` (common_data.h:61) gives BLOCK_8X32/32X8 group
6870 // 1 and BLOCK_16X64/64X16 group 2, while
6871 // `bsize_to_tx_size_depth_table` (blockd.h:1347) gives them depth
6872 // 3 and 4, i.e. tx categories 2 and 3 -- the diagonal a 2:1 strip
6873 // keeps is genuinely broken here, which is why the shape was refused
6874 // rather than read from the 2:1 row.
6875 (8, 32) => (1, 2),
6876 (16, 64) => (2, 3),
6877 _ => {
6878 return Err(unsupported(
6879 "an intra-coded 16x4/4x16 strip on the inter block path (the 16x16-level 1:4 inter partition is refused before this point)",
6880 ))
6881 }
6882 };
6883 // [`read_intra_mode_rect`]'s own refusal: palette/intrabc syntax is
6884 // consumed for square blocks only, so a strip in a screen-content frame
6885 // would skip symbols the encoder wrote.
6886 if allow_screen_content_tools {
6887 return Err(unsupported(
6888 "a HORZ/VERT intra strip in a screen-content frame (palette syntax \
6889 is consumed for square blocks only)",
6890 ));
6891 }
6892 // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY
6893 // FRAME path already proves for this shape ([`decode_block_rect4`] at the
6894 // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4
6895 // luma/chroma transform tables, the per-unit split walk and the strip's
6896 // own neighbour records). The ONLY difference on an inter frame is the
6897 // mode-info read, which [`INTRA_IN_INTER_MODE`] switches to
6898 // `read_intra_block_mode_info`'s `y_mode[size_group]` plus the `skip`
6899 // this caller already read. `tx_cat` above is the same category those
6900 // readers hardcode (cat 2 in `decode_block_rect4`, cat 3 in
6901 // `decode_block_rect64`), asserted here so a future shape cannot drift.
6902 if bw.max(bh) == 4 * bw.min(bh) {
6903 debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 });
6904 INTRA_IN_INTER_MODE.with(|c| c.set(Some((size_group, skip))));
6905 let res = if bw.max(bh) == 64 {
6906 decode_block_rect64(
6907 dec,
6908 cdfs,
6909 neighbours,
6910 (mi_r / (SUB / MI), mi_c / (SUB / MI)),
6911 bw,
6912 bh,
6913 y,
6914 u,
6915 v,
6916 ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get),
6917 allow_screen_content_tools,
6918 base_q_idx,
6919 TX_SELECT_INTER.with(std::cell::Cell::get),
6920 REDUCED_TX_SET_INTER.with(std::cell::Cell::get),
6921 )
6922 } else {
6923 decode_block_rect4(
6924 dec,
6925 cdfs,
6926 neighbours,
6927 (mi_r, mi_c),
6928 bw,
6929 bh,
6930 None,
6931 y,
6932 u,
6933 v,
6934 ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get),
6935 allow_screen_content_tools,
6936 base_q_idx,
6937 TX_SELECT_INTER.with(std::cell::Cell::get),
6938 )
6939 .map(|_| ())
6940 };
6941 INTRA_IN_INTER_MODE.with(|c| c.set(None));
6942 res?;
6943 let shape = match (bw, bh) {
6944 (64, 16) => 0,
6945 (16, 64) => 1,
6946 (32, 8) => 2,
6947 _ => 3,
6948 };
6949 INTRA_RECT4_IN_INTER_HITS.with(|h| {
6950 let mut v = h.get();
6951 v[shape] += 1;
6952 h.set(v);
6953 });
6954 return Ok(());
6955 }
6956 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
6957 if mode >= 13 {
6958 return Err(unsupported(
6959 "an intra mode this decoder does not code (round 2)",
6960 ));
6961 }
6962 // lane-angleinter (merged on main for the square intra-in-inter arm):
6963 // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the
6964 // directional predictor; this arm refused a nonzero one before the merge.
6965 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
6966 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
6967 } else {
6968 0
6969 };
6970 if angle_delta_y != 0 {
6971 INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.set(c.get() + 1));
6972 }
6973 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
6974 // superblock-level strip reads the no-CFL alphabet -- the same split
6975 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
6976 let cfl_allowed = bw.max(bh) <= 32;
6977 let uv_mode = if cfl_allowed {
6978 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
6979 } else {
6980 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
6981 };
6982 if (9..=12).contains(&uv_mode) {
6983 SMOOTH_UV_HITS.with(|h| h.set(h.get() + 1));
6984 }
6985 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
6986 Some(read_cfl_alphas(dec, cdfs))
6987 } else {
6988 None
6989 };
6990 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
6991 DC_PRED
6992 } else {
6993 uv_mode
6994 };
6995 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
6996 DIRECTIONAL_UV_HITS.with(|h| h.set(h.get() + 1));
6997 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
6998 } else {
6999 0
7000 };
7001 if angle_delta_uv != 0 {
7002 UV_ANGLE_DELTA_HITS.with(|h| h.set(h.get() + 1));
7003 INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|h| h.set(h.get() + 1));
7004 }
7005 // lane-fiinter (merged on main for the square intra-in-inter arm):
7006 // `read_filter_intra_mode_info` is the tail of
7007 // `read_intra_block_mode_info`, after the palette syntax (refused whole
7008 // above for this shape), and `av1_filter_intra_allowed_bsize` admits the
7009 // 2:1 strips with both sides <= 32 -- their own CDF rows
7010 // ([`filter_intra_size_class_rect`]).
7011 let mut filter_intra = None;
7012 if mode == DC_PRED
7013 && ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get)
7014 && let Some(class) = filter_intra_size_class_rect(bw, bh)
7015 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
7016 {
7017 FILTER_INTRA_HITS.with(|h| h.set(h.get() + 1));
7018 INTRA_IN_INTER_FILTER_INTRA_HITS.with(|h| h.set(h.get() + 1));
7019 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
7020 }
7021 // The intra-edge filter type is the NEIGHBOUR's mode (libaom
7022 // `get_filt_type`), luma's off the luma neighbours and chroma's off the
7023 // chroma ones -- [`decode_block_rect`]'s own pair.
7024 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
7025 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
7026 if smooth_neighbor {
7027 SMOOTH_LUMA_HITS.with(|h| h.set(h.get() + 1));
7028 }
7029 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
7030 let depth = if TX_SELECT_INTER.with(std::cell::Cell::get) {
7031 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
7032 match tx_cat {
7033 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
7034 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
7035 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
7036 }
7037 } else {
7038 0
7039 };
7040 if depth != 0 {
7041 TX_DEPTH_HITS.with(|h| h.set(h.get() + 1));
7042 // merge b51719f+lane-intrarect (class merge-cross-product-defect):
7043 // main's 10-bit `split_transform_intra_block` gate reaches this arm
7044 // with a nonzero tx depth, and the split rect-TU walk mis-decodes it
7045 // (2340 luma samples off at seed 51; refusing here restores that gate
7046 // while the depth-0 strip the lane proved keeps decoding). The lane's
7047 // own gate never exercised a split strip.
7048 return Err(unsupported(
7049 "a split (nonzero tx_depth) transform on an intra HORZ/VERT strip in an inter frame",
7050 ));
7051 }
7052 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
7053 let modes = RectStripModes {
7054 skip,
7055 mode,
7056 angle_delta_y,
7057 uv_predict_mode,
7058 angle_delta_uv,
7059 alpha,
7060 filter_intra,
7061 smooth_neighbor,
7062 smooth_neighbor_uv,
7063 // screen-content frames are refused whole above, so this strip can
7064 // carry no palette.
7065 palette_y: None,
7066 palette_uv: None,
7067 };
7068 decode_rect_split(
7069 dec,
7070 cdfs,
7071 neighbours,
7072 (mi_r, mi_c),
7073 bw,
7074 bh,
7075 tx_w,
7076 tx_h,
7077 &modes,
7078 y,
7079 u,
7080 v,
7081 base_q_idx,
7082 REDUCED_TX_SET_INTER.with(std::cell::Cell::get),
7083 )?;
7084 let class = match bw.max(bh) {
7085 64 => 0,
7086 32 => 1,
7087 _ => 2,
7088 };
7089 INTRA_RECT_IN_INTER_HITS.with(|h| {
7090 let mut v = h.get();
7091 v[class] += 1;
7092 h.set(v);
7093 });
7094 Ok(())
7095}
7096
7097/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
7098/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
7099/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
7100/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
7101/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
7102/// has no rectangular-transform coefficient reader, and a chroma plane here
7103/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
7104/// with no depth-based square-tiling escape the way luma's own resolved
7105/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
7106/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
7107#[allow(clippy::too_many_arguments)]
7108fn decode_block_rect(
7109 dec: &mut SymbolDecoder,
7110 cdfs: &mut Cdfs,
7111 neighbours: &mut Neighbours,
7112 at: (usize, usize),
7113 bw: usize,
7114 bh: usize,
7115 y: &mut PlaneBuf,
7116 u: &mut PlaneBuf,
7117 v: &mut PlaneBuf,
7118 enable_filter_intra: bool,
7119 allow_screen_content_tools: bool,
7120 base_q_idx: u8,
7121 tx_select: bool,
7122 reduced_tx_set: bool,
7123) -> Result<()> {
7124 let (r, c) = at;
7125 let (px, py) = (c * SUB, r * SUB);
7126 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
7127 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
7128 let palette_uv_cache = neighbours.palette_uv_cache(at);
7129 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
7130 read_intra_mode_rect(
7131 dec,
7132 cdfs,
7133 nb_above_mode,
7134 nb_left_mode,
7135 true,
7136 true,
7137 bw,
7138 bh,
7139 enable_filter_intra,
7140 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
7141 allow_screen_content_tools,
7142 Some((palette_ctx, &palette_cache)),
7143 &palette_uv_cache,
7144 r * (SUB / MI),
7145 c * (SUB / MI),
7146 )?;
7147 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
7148 if smooth_neighbor {
7149 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
7150 }
7151 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
7152 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
7153 // `uv_mode`, not the luma one.
7154 let smooth_neighbor_uv =
7155 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
7156 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
7157 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
7158 // rectangle just as happily), so a `use_filter_intra` strip at this level
7159 // predicts instead of refusing. The below-16x16 leaf arm
7160 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
7161 if filter_intra.is_some() {
7162 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
7163 }
7164 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
7165 DC_PRED
7166 } else {
7167 uv_mode
7168 };
7169 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
7170 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
7171 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
7172 // one did not, so with `--enable-tx-size-search=0` -- which several gate
7173 // recipes use -- the decoder consumed a symbol the encoder never wrote and
7174 // desynced the tile from that point on. That is why both strips of the
7175 // pinned HORZ quadrant were wrong from their very first pixel, and why our
7176 // range after the read equalled the oracle's range for the whole block.
7177 let depth = if tx_select {
7178 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
7179 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
7180 } else {
7181 0
7182 };
7183 if depth != 0 {
7184 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
7185 // lane-rectsplit r1: a split transform is predicted and reconstructed
7186 // per transform unit, each unit taking its edges from the previous
7187 // unit's reconstruction inside this same strip (spec 5.11.36) --
7188 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
7189 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
7190 if std::env::var_os("EC_SBPART_DUMP64").is_some() {
7191 eprintln!(
7192 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
7193 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
7194 angle_y={angle_delta_y}"
7195 );
7196 }
7197 let modes = RectStripModes {
7198 skip,
7199 mode,
7200 angle_delta_y,
7201 uv_predict_mode,
7202 angle_delta_uv,
7203 alpha,
7204 filter_intra,
7205 smooth_neighbor,
7206 smooth_neighbor_uv,
7207 palette_y: palette_y
7208 .as_ref()
7209 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
7210 palette_uv: palette_uv.as_ref().map(|p| {
7211 (
7212 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
7213 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
7214 )
7215 }),
7216 };
7217 if palette_y.is_some() || palette_uv.is_some() {
7218 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
7219 }
7220 decode_rect_split(
7221 dec,
7222 cdfs,
7223 neighbours,
7224 (mi_r, mi_c),
7225 bw,
7226 bh,
7227 tx_w,
7228 tx_h,
7229 &modes,
7230 y,
7231 u,
7232 v,
7233 base_q_idx,
7234 reduced_tx_set,
7235 )?;
7236 // This early return skips this fn's own tail, so the palette
7237 // neighbour state has to be stamped HERE too: without it a split-tx
7238 // strip left the above/left palette arrays holding a DEAD block's
7239 // colours, and the next block's colour cache
7240 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
7241 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
7242 // and only those pixels were wrong (lane-palette2 r10).
7243 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
7244 neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
7245 let (puv_size, puv_colors) =
7246 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
7247 neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
7248 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
7249 return Ok(());
7250 }
7251 let (tx_w, tx_h) = (bw, bh);
7252 let (cpx, cpy) = (px / 2, py / 2);
7253 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
7254 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
7255 if std::env::var_os("EC_AV1_TRACE").is_some() {
7256 let (rng, _) = dec.debug_state();
7257 eprintln!(
7258 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
7259 skip={} tx={depth} rng={rng}",
7260 skip as i32
7261 );
7262 }
7263 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
7264 // block's prediction is the reconstructed colour-index map, set fresh
7265 // right before each `reconstruct_rect` call below (lane-palette2 r4).
7266 if let Some(ref pyv) = palette_y {
7267 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
7268 set_palette_pred(buf);
7269 }
7270 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
7271 (
7272 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
7273 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
7274 )
7275 });
7276 if skip {
7277 y.reconstruct_rect(
7278 px,
7279 py,
7280 bw,
7281 bh,
7282 mode,
7283 angle_delta_y,
7284 reach,
7285 &vec![0i32; bw * bh],
7286 None,
7287 filter_intra,
7288 smooth_neighbor,
7289 );
7290 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
7291 if let Some((ub, _)) = &palette_uv_bufs {
7292 set_palette_pred(ub.clone());
7293 }
7294 u.reconstruct_rect(
7295 cpx,
7296 cpy,
7297 chroma_w,
7298 chroma_h,
7299 uv_predict_mode,
7300 angle_delta_uv,
7301 reach,
7302 &vec![0i32; chroma_w * chroma_h],
7303 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
7304 None,
7305 smooth_neighbor_uv,
7306 );
7307 if let Some((_, vb)) = &palette_uv_bufs {
7308 set_palette_pred(vb.clone());
7309 }
7310 v.reconstruct_rect(
7311 cpx,
7312 cpy,
7313 chroma_w,
7314 chroma_h,
7315 uv_predict_mode,
7316 angle_delta_uv,
7317 reach,
7318 &vec![0i32; chroma_w * chroma_h],
7319 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
7320 None,
7321 smooth_neighbor_uv,
7322 );
7323 neighbours.record_rect(
7324 at,
7325 bw,
7326 bh,
7327 mode,
7328 uv_predict_mode,
7329 &[
7330 vec![0i32; bw * bh],
7331 vec![0i32; chroma_w * chroma_h],
7332 vec![0i32; chroma_w * chroma_h],
7333 ],
7334 );
7335 } else {
7336 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
7337 // reduces both size pairs to their square-up CDF sets
7338 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
7339 // doc comments); the scan order and 2D context tables are the real
7340 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
7341 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 32 {
7342 (&SCAN_32X16, &SCAN_16X8)
7343 } else {
7344 (&SCAN_16X32, &SCAN_8X16)
7345 };
7346 // lane-rectwire r3: real coefficients desync a pixel-exact gate
7347 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
7348 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
7349 // pixel (not a subtle context-table off-by-one), while the sibling
7350 // non-rect quadrants of the same frame match. Range-ladder bisection
7351 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
7352 // but the intra key-frame path has no traced symbol between the
7353 // partition read and the first coefficient block (mode/skip/tx_depth
7354 // reads are all untraced in libaom's decodeframe.c intra path, unlike
7355 // the inter EC_TRACE_MODE this round added), so a same-length range
7356 // comparison wasn't reachable within budget -- see
7357 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
7358 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
7359 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
7360 // libaom and match). lane-rectwire r4: range-ladder against the
7361 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
7362 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
7363 // both confirmed in sync -- rng=58692 on both sides right after
7364 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
7365 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
7366 // immediately after: ours moves rng 58692 -> 43570, which cannot be
7367 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
7368 // its own tx_size read) unless oracle's tx symbol is a near-certainty
7369 // CDF that barely narrows the range -- i.e. this decoder's
7370 // `tx_size_context_rect` ctx or `cdfs.tx_size_cat2` CDF selection for
7371 // a 32x16/16x32 strip is the first diverging symbol, not the
7372 // coefficient-context math r3 already cleared. Not confirmed byte-
7373 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
7374 // `read_tx_size`'s own rng, not attempted this round -- budget), so
7375 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
7376 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
7377 // it unconditionally where both square paths gate on `tx_select`. With
7378 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
7379 // decoder consumed one that was never there.
7380 {
7381 let around = neighbours.around_rect(at, bw, bh);
7382 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
7383 let (luma_levels, luma_tx_type) = read_coeffs_rect(
7384 dec,
7385 &mut luma_coding,
7386 luma_scan,
7387 bw,
7388 bh,
7389 0,
7390 dc_sign_ctx(around[0].2),
7391 TxType::DctDct,
7392 )?;
7393 if std::env::var_os("EC_AV1_TRACE").is_some() {
7394 let (rng, _) = dec.debug_state();
7395 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
7396 }
7397 let luma_residual = dequant_and_inverse_typed_wh(
7398 &luma_levels,
7399 bw,
7400 bh,
7401 crate::decode::bit_depth(),
7402 block_q_idx(),
7403 plane_q_delta(0).0,
7404 plane_q_delta(0).1,
7405 luma_tx_type,
7406 );
7407 y.reconstruct_rect(
7408 px,
7409 py,
7410 bw,
7411 bh,
7412 mode,
7413 angle_delta_y,
7414 reach,
7415 &luma_residual,
7416 None,
7417 filter_intra,
7418 smooth_neighbor,
7419 );
7420 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
7421 if let Some((ub, _)) = &palette_uv_bufs {
7422 set_palette_pred(ub.clone());
7423 }
7424 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
7425 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
7426 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
7427 let (u_levels, u_tx_type) = read_coeffs_rect(
7428 dec,
7429 &mut u_coding,
7430 chroma_scan,
7431 chroma_w,
7432 chroma_h,
7433 u_skip_ctx,
7434 dc_sign_ctx(around[1].2),
7435 u_default_tx,
7436 )?;
7437 if std::env::var_os("EC_AV1_TRACE").is_some() {
7438 let (rng, _) = dec.debug_state();
7439 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
7440 }
7441 let u_residual = dequant_and_inverse_typed_wh(
7442 &u_levels,
7443 chroma_w,
7444 chroma_h,
7445 crate::decode::bit_depth(),
7446 block_q_idx(),
7447 plane_q_delta(1).0,
7448 plane_q_delta(1).1,
7449 u_tx_type,
7450 );
7451 u.reconstruct_rect(
7452 cpx,
7453 cpy,
7454 chroma_w,
7455 chroma_h,
7456 uv_predict_mode,
7457 angle_delta_uv,
7458 reach,
7459 &u_residual,
7460 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
7461 None,
7462 smooth_neighbor_uv,
7463 );
7464 if let Some((_, vb)) = &palette_uv_bufs {
7465 set_palette_pred(vb.clone());
7466 }
7467 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
7468 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
7469 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
7470 let (v_levels, v_tx_type) = read_coeffs_rect(
7471 dec,
7472 &mut v_coding,
7473 chroma_scan,
7474 chroma_w,
7475 chroma_h,
7476 v_skip_ctx,
7477 dc_sign_ctx(around[2].2),
7478 v_default_tx,
7479 )?;
7480 if std::env::var_os("EC_AV1_TRACE").is_some() {
7481 let (rng, _) = dec.debug_state();
7482 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
7483 }
7484 let v_residual = dequant_and_inverse_typed_wh(
7485 &v_levels,
7486 chroma_w,
7487 chroma_h,
7488 crate::decode::bit_depth(),
7489 block_q_idx(),
7490 plane_q_delta(2).0,
7491 plane_q_delta(2).1,
7492 v_tx_type,
7493 );
7494 v.reconstruct_rect(
7495 cpx,
7496 cpy,
7497 chroma_w,
7498 chroma_h,
7499 uv_predict_mode,
7500 angle_delta_uv,
7501 reach,
7502 &v_residual,
7503 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
7504 None,
7505 smooth_neighbor_uv,
7506 );
7507 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
7508 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
7509 }
7510 }
7511 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
7512 neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
7513 let (puv_size, puv_colors) =
7514 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
7515 neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
7516 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
7517 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
7518 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
7519 if std::env::var_os("EC_AV1_TRACE").is_some() {
7520 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
7521 }
7522 Ok(())
7523}
7524
7525/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
7526/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
7527/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
7528/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
7529/// the second strip of a HORZ/VERT split sits offset by half the 16x16
7530/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
7531/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
7532/// previous strip is directly above (same column, `mi_h` rows up) or
7533/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
7534/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
7535/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
7536/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
7537/// this strip's real position, never the coarse `record_rect` (which the
7538/// caller uses once, after both strips, exactly like the `VERT_B` arm next
7539/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
7540/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
7541/// chroma half (`TxbSet::ChromaRect8x4`), the two size classes one level
7542/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
7543#[allow(clippy::too_many_arguments)]
7544fn decode_leaf_rect(
7545 dec: &mut SymbolDecoder,
7546 cdfs: &mut Cdfs,
7547 neighbours: &mut Neighbours,
7548 outer_at: (usize, usize),
7549 leaf_mi: (usize, usize),
7550 bw: usize,
7551 bh: usize,
7552 prev_leaf: Option<((usize, usize), usize)>,
7553 y: &mut PlaneBuf,
7554 u: &mut PlaneBuf,
7555 v: &mut PlaneBuf,
7556 enable_filter_intra: bool,
7557 allow_screen_content_tools: bool,
7558 base_q_idx: u8,
7559 tx_select: bool,
7560 reduced_tx_set: bool,
7561) -> Result<usize> {
7562 let _ = base_q_idx;
7563 if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() {
7564 eprintln!(
7565 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
7566 dec.debug_state().0
7567 );
7568 }
7569 let (r, c) = outer_at;
7570 let mut above_mode = neighbours.above_mode[c];
7571 let mut left_mode = neighbours.left_mode[r];
7572 let (mi_w, mi_h) = (bw / MI, bh / MI);
7573 if let Some(((pr, pc), pmode)) = prev_leaf {
7574 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
7575 above_mode = pmode;
7576 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
7577 left_mode = pmode;
7578 }
7579 }
7580 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
7581 // cannot hold the modes a split (or a pair of strips) leaves behind, so
7582 // when the map holds the block at exactly this strip's above/left mi it
7583 // is the neighbour libaom's `above_mi`/`left_mi` reads.
7584 // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND
7585 // availability-correct -- four 16x8 strips share one coarse 16x16
7586 // `left_mode` cell too, so the fallback must not stand in for an absent
7587 // tile-edge neighbour.
7588 let (above_mode, left_mode) =
7589 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
7590 let smooth_neighbor =
7591 is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
7592 if smooth_neighbor {
7593 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
7594 }
7595 // The palette-Y mode CDF row is picked by the neighbours' palette use
7596 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
7597 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
7598 // a palette narrows the wrong interval and desyncs the tile even when the
7599 // decoded bit is the same. The cell is the 16px-SUB cell containing the
7600 // leaf (the palette neighbour arrays have no finer granularity).
7601 let pal_at = (leaf_mi.0 / (SUB / MI), leaf_mi.1 / (SUB / MI));
7602 // lane-kf900 r4: the leaf's REAL mi row -- the second leaf of a 16x8 pair
7603 // sits 8 px into the cell, so the cache's superblock-top-row exclusion
7604 // must not be read off the cell (see [`Neighbours::palette_ctx_and_cache_mi`]).
7605 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at, leaf_mi.0);
7606 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at, leaf_mi.0);
7607 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
7608 read_intra_mode_rect(
7609 dec,
7610 cdfs,
7611 above_mode,
7612 left_mode,
7613 true,
7614 true,
7615 bw,
7616 bh,
7617 enable_filter_intra,
7618 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
7619 allow_screen_content_tools,
7620 Some((palette_ctx, &palette_cache)),
7621 &palette_uv_cache,
7622 leaf_mi.0,
7623 leaf_mi.1,
7624 )?;
7625 // lane-kf900 r4: palette prediction on this shape, the same colour-index
7626 // map -> base colours buffer [`decode_block_rect`] hands each
7627 // `reconstruct_rect` through [`set_palette_pred`].
7628 if palette_y.is_some() || palette_uv.is_some() {
7629 RECT4_PALETTE_HITS.with(|c| c.set(c.get() + 1));
7630 }
7631 let palette_y_buf: Option<Vec<u16>> = palette_y
7632 .as_ref()
7633 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
7634 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
7635 (
7636 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
7637 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
7638 )
7639 });
7640 let (pal_y_size, pal_y_colors) =
7641 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
7642 let (pal_uv_size, pal_uv_colors) =
7643 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
7644 // The closing leaf of the pair -- see [`record_strip_palette`].
7645 let pal_last = if bw > bh {
7646 leaf_mi.0 % 4 == 2
7647 } else {
7648 leaf_mi.1 % 4 == 2
7649 };
7650 if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() {
7651 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
7652 }
7653 if filter_intra.is_some() {
7654 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
7655 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
7656 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
7657 // below already makes; this refusal was square-only prose.
7658 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
7659 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.set(c.get() + 1));
7660 }
7661 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
7662 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
7663 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
7664 // a constant `false`.
7665 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
7666 let depth = if tx_select {
7667 let ctx = tx_size_context_rect(neighbours, leaf_mi, bw, bh);
7668 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
7669 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
7670 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
7671 // count (3), different CDF row: a wrong-table read of a real symbol,
7672 // the class that cost lane-rectsplit r1 its 64x32 depth.
7673 // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's
7674 // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and
7675 // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this
7676 // function also decodes) sit at depth 2, so they read
7677 // `tx_size_cdf[1]` -- the same table a 16x16 square block reads --
7678 // while `tx_size_cat2` belongs to the 32-level shapes
7679 // ([`decode_block_rect`]). Both tables carry three symbols, so the
7680 // wrong one decodes a plausible depth from the wrong probabilities:
7681 // the range diverges silently at the first such leaf and every later
7682 // symbol in the tile is read from the wrong place (class
7683 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
7684 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
7685 } else {
7686 0
7687 };
7688 if depth != 0 {
7689 // The same per-transform-unit walk the bigger strips take
7690 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
7691 // depth 2), addressed at this leaf's own mi position.
7692 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
7693 SUB16_SPLIT_HITS.with(|c| c.set(c.get() + 1));
7694 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
7695 let modes = RectStripModes {
7696 skip,
7697 mode,
7698 angle_delta_y,
7699 uv_predict_mode,
7700 angle_delta_uv,
7701 alpha,
7702 filter_intra,
7703 smooth_neighbor,
7704 // lane-rectsplitx r3: the split arm hard-coded `false` here while
7705 // the unsplit arm below passes the real neighbour answer -- chroma
7706 // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type.
7707 smooth_neighbor_uv,
7708 palette_y: palette_y_buf.clone(),
7709 palette_uv: palette_uv_bufs.clone(),
7710 };
7711 if palette_y.is_some() || palette_uv.is_some() {
7712 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
7713 }
7714 decode_rect_split(
7715 dec,
7716 cdfs,
7717 neighbours,
7718 leaf_mi,
7719 bw,
7720 bh,
7721 tx_w,
7722 tx_h,
7723 &modes,
7724 y,
7725 u,
7726 v,
7727 base_q_idx,
7728 reduced_tx_set,
7729 )?;
7730 record_strip_palette(
7731 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
7732 pal_last,
7733 );
7734 return Ok(mode);
7735 }
7736 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
7737 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
7738 let (cpx, cpy) = (px / 2, py / 2);
7739 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
7740 let (luma_levels, u_levels, v_levels);
7741 if skip {
7742 luma_levels = vec![0i32; bw * bh];
7743 u_levels = vec![0i32; chroma_w * chroma_h];
7744 v_levels = vec![0i32; chroma_w * chroma_h];
7745 if let Some(b) = &palette_y_buf {
7746 set_palette_pred(b.clone());
7747 }
7748 y.reconstruct_rect(
7749 px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra,
7750 smooth_neighbor,
7751 );
7752 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
7753 if let Some((ub, _)) = &palette_uv_bufs {
7754 set_palette_pred(ub.clone());
7755 }
7756 u.reconstruct_rect(
7757 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels,
7758 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv,
7759 );
7760 if let Some((_, vb)) = &palette_uv_bufs {
7761 set_palette_pred(vb.clone());
7762 }
7763 v.reconstruct_rect(
7764 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels,
7765 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv,
7766 );
7767 } else {
7768 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
7769 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
7770 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
7771 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
7772 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
7773 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
7774 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 16 {
7775 (&SCAN_16X8, &SCAN_8X4)
7776 } else {
7777 (&SCAN_8X16, &SCAN_4X8)
7778 };
7779 let around = neighbours.around_mi_rect(leaf_mi, bw, bh);
7780 let luma_set = if reduced_tx_set {
7781 TxbSet::LumaRect16x8
7782 } else {
7783 TxbSet::LumaRect16x8Set1
7784 };
7785 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
7786 let (l_levels, luma_tx_type) = read_coeffs_rect(
7787 dec, &mut luma_coding, luma_scan, bw, bh, 0, dc_sign_ctx(around[0].2), TxType::DctDct,
7788 )?;
7789 if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() {
7790 let nz: Vec<(usize, i32)> = l_levels.iter().copied().enumerate().filter(|(_, v)| *v != 0).collect();
7791 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
7792 }
7793 luma_levels = l_levels;
7794 let luma_residual = dequant_and_inverse_typed_wh(
7795 &luma_levels, bw, bh, crate::decode::bit_depth(),
7796 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(0).0, plane_q_delta(0).1, luma_tx_type,
7797 );
7798 if let Some(b) = &palette_y_buf {
7799 set_palette_pred(b.clone());
7800 }
7801 y.reconstruct_rect(
7802 px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra,
7803 smooth_neighbor,
7804 );
7805 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
7806 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
7807 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
7808 let mut u_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
7809 let (u_l, u_tx_type) = read_coeffs_rect(
7810 dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx,
7811 dc_sign_ctx(around[1].2), u_default_tx,
7812 )?;
7813 u_levels = u_l;
7814 let u_residual = dequant_and_inverse_typed_wh(
7815 &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(),
7816 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(1).0, plane_q_delta(1).1, u_tx_type,
7817 );
7818 if let Some((ub, _)) = &palette_uv_bufs {
7819 set_palette_pred(ub.clone());
7820 }
7821 u.reconstruct_rect(
7822 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual,
7823 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv,
7824 );
7825 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
7826 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
7827 let mut v_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
7828 let (v_l, v_tx_type) = read_coeffs_rect(
7829 dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx,
7830 dc_sign_ctx(around[2].2), v_default_tx,
7831 )?;
7832 v_levels = v_l;
7833 let v_residual = dequant_and_inverse_typed_wh(
7834 &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(),
7835 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(2).0, plane_q_delta(2).1, v_tx_type,
7836 );
7837 if let Some((_, vb)) = &palette_uv_bufs {
7838 set_palette_pred(vb.clone());
7839 }
7840 v.reconstruct_rect(
7841 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual,
7842 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv,
7843 );
7844 RECT_LEAF_COEFF_HITS.with(|c| c.set(c.get() + 1));
7845 }
7846 neighbours.record_mi_rect(leaf_mi, bw, bh, &[luma_levels, u_levels, v_levels]);
7847 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
7848 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0);
7849 // The leaf's own palette state (`0` clears, as this site always did
7850 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT
7851 // AXIS only until the pair's closing leaf: the coarse cell holds one
7852 // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the
7853 // real left neighbour leaf 1 reads (lane-kf900 r4).
7854 record_strip_palette(
7855 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
7856 pal_last,
7857 );
7858 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
7859 // rows -- record the whole span, not one cell.
7860 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
7861 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
7862 Ok(mode)
7863}
7864
7865/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
7866/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
7867/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
7868/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
7869/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
7870/// strip's mode so this one's mode context sees its true above/left
7871/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
7872///
7873/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
7874/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
7875/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
7876/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
7877/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
7878/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
7879/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
7880///
7881/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
7882/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
7883/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
7884/// unexamined.
7885#[allow(clippy::too_many_arguments)]
7886fn decode_block_rect4(
7887 dec: &mut SymbolDecoder,
7888 cdfs: &mut Cdfs,
7889 neighbours: &mut Neighbours,
7890 strip_mi: (usize, usize),
7891 bw: usize,
7892 bh: usize,
7893 prev_strip: Option<((usize, usize), usize)>,
7894 y: &mut PlaneBuf,
7895 u: &mut PlaneBuf,
7896 v: &mut PlaneBuf,
7897 enable_filter_intra: bool,
7898 allow_screen_content_tools: bool,
7899 base_q_idx: u8,
7900 tx_select: bool,
7901) -> Result<(usize, usize)> {
7902 let _ = base_q_idx;
7903 let (mi_r, mi_c) = strip_mi;
7904 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
7905 let (mi_w, mi_h) = (bw / MI, bh / MI);
7906 let mut above_mode = neighbours.above_mode[c];
7907 let mut left_mode = neighbours.left_mode[r];
7908 if let Some(((pr, pc), pmode)) = prev_strip {
7909 if pc == mi_c && mi_r == pr + mi_h {
7910 above_mode = pmode;
7911 } else if pr == mi_r && mi_c == pc + mi_w {
7912 left_mode = pmode;
7913 }
7914 }
7915 // lane-rectsplitx r2, ROOT CAUSE of the 1:4 mismatch: mi-exact +
7916 // availability-correct neighbour modes (see
7917 // [`Neighbours::modes_above_left_mi`]). The coarse 16x16 bands alias every
7918 // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell.
7919 let (above_mode, left_mode) =
7920 neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode));
7921 // lane-kf900 r4: this strip's own palette-Y mode ctx and colour cache.
7922 // Passing `None`/`&[]` read `palette_y_mode` off CDF row 0 and every
7923 // `palette_colors_y` cache hit off an EMPTY cache -- right symbol count,
7924 // wrong interval, so a screen-content tile desynced at the first strip
7925 // whose neighbour used a palette (class [[cdf-row-held-constant]]).
7926 let pal_at = (mi_r / (SUB / MI), mi_c / (SUB / MI));
7927 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at, mi_r);
7928 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at, mi_r);
7929 let (
7930 skip,
7931 mode,
7932 angle_delta_y,
7933 uv_mode,
7934 angle_delta_uv,
7935 alpha,
7936 filter_intra,
7937 palette_y,
7938 palette_uv,
7939 ) = read_intra_mode_rect(
7940 dec,
7941 cdfs,
7942 above_mode,
7943 left_mode,
7944 true,
7945 true,
7946 bw,
7947 bh,
7948 enable_filter_intra,
7949 neighbours.skip_txfm_ctx(mi_r, mi_c),
7950 allow_screen_content_tools,
7951 Some((palette_ctx, &palette_cache)),
7952 &palette_uv_cache,
7953 mi_r,
7954 mi_c,
7955 )?;
7956 // lane-kf900 r4: palette prediction on this shape, exactly as
7957 // [`decode_block_rect`] does one aspect ratio up -- the colour-index map
7958 // mapped through the base colours IS the prediction (it reads no edge
7959 // pixels), handed to each `reconstruct_rect` through [`set_palette_pred`].
7960 if palette_y.is_some() || palette_uv.is_some() {
7961 RECT4_PALETTE_HITS.with(|c| c.set(c.get() + 1));
7962 }
7963 let palette_y_buf: Option<Vec<u16>> = palette_y
7964 .as_ref()
7965 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
7966 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
7967 (
7968 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
7969 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
7970 )
7971 });
7972 // `last`: strip 3 of the parent 32x32's HORZ_4 (VERT_4), the only one
7973 // whose colours a block outside the parent sees -- see
7974 // [`record_strip_palette`].
7975 let pal_last = if bw > bh { mi_r % 8 == 6 } else { mi_c % 8 == 6 };
7976 let (pal_y_size, pal_y_colors) =
7977 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
7978 let (pal_uv_size, pal_uv_colors) =
7979 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
7980 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
7981 if smooth_neighbor {
7982 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
7983 }
7984 // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's
7985 // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so
7986 // `r * (SUB / MI)` names a different mi column and the chroma
7987 // edge-filter strength was read from the wrong neighbour (measured:
7988 // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch
7989 // with luma bit-exact).
7990 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
7991 if filter_intra.is_some() {
7992 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
7993 if bw > bh {
7994 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.set(c.get() + 1));
7995 } else {
7996 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.set(c.get() + 1));
7997 }
7998 }
7999 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
8000 DC_PRED
8001 } else {
8002 uv_mode
8003 };
8004 let depth = if tx_select {
8005 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
8006 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
8007 } else {
8008 0
8009 };
8010 if depth != 0 {
8011 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
8012 // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a
8013 // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16
8014 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8;
8015 // both interleave in every real stream.
8016 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
8017 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
8018 // lane-rectsplitx r2: both depths ship together, as the r1 handoff
8019 // predicted -- depth 1 fires FIRST in every attempt that splits at
8020 // all, so a depth-2-only lift could never be gated. The r1 mismatch
8021 // was never the rect unit: it was the neighbour MODE the strip reads
8022 // (see `modes_above_left_mi`).
8023 let which = if depth == 1 {
8024 &RECT4_SPLIT_DEPTH1_HITS
8025 } else {
8026 &RECT4_SPLIT_DEPTH2_HITS
8027 };
8028 which.with(|c| c.set(c.get() + 1));
8029 let modes = RectStripModes {
8030 skip,
8031 mode,
8032 angle_delta_y,
8033 uv_predict_mode,
8034 angle_delta_uv,
8035 alpha,
8036 filter_intra,
8037 smooth_neighbor,
8038 smooth_neighbor_uv,
8039 palette_y: palette_y_buf.clone(),
8040 palette_uv: palette_uv_bufs.clone(),
8041 };
8042 if palette_y.is_some() || palette_uv.is_some() {
8043 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
8044 }
8045 decode_rect_split(
8046 dec,
8047 cdfs,
8048 neighbours,
8049 (mi_r, mi_c),
8050 bw,
8051 bh,
8052 tx_w,
8053 tx_h,
8054 &modes,
8055 y,
8056 u,
8057 v,
8058 base_q_idx,
8059 false,
8060 )?;
8061 record_strip_palette(
8062 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
8063 pal_uv_colors, pal_last,
8064 );
8065 if bw > bh {
8066 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
8067 } else {
8068 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
8069 }
8070 if !skip {
8071 RECT4_COEFF_HITS.with(|c| c.set(c.get() + 1));
8072 }
8073 return Ok((mode, uv_predict_mode));
8074 }
8075 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
8076 // that is 8 px tall, so each strip stamps every cell it touches and the
8077 // LAST strip wins -- which is the right answer for the block below/right
8078 // of the 32x32, the only reader outside it. Written after this strip's
8079 // own context read above, never before.
8080 for cell in 0..bw.div_ceil(SUB) {
8081 neighbours.above_mode[c + cell] = mode;
8082 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
8083 neighbours.above_side[c + cell] = bw;
8084 }
8085 for cell in 0..bh.div_ceil(SUB) {
8086 neighbours.left_mode[r + cell] = mode;
8087 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
8088 neighbours.left_side[r + cell] = bh;
8089 }
8090 // ...and the mi-EXACT maps the coarse cells alias away, exactly as
8091 // [`decode_leaf_rect`] does (the split arm above records these through
8092 // `record_mi_luma_rect`). Without this an unsplit 32x8 strip left
8093 // `sub8_mode_row` holding the previous block, and the next 32x32's
8094 // strips read a stale `kf_y_mode` row (measured: mi(4,8) on the band
8095 // fixture).
8096 neighbours.record_mode_mi(mi_r, mi_c, mi_w, mi_h, mode);
8097 neighbours.record_uv_mode_mi(mi_r, mi_c, mi_w, mi_h, uv_predict_mode);
8098 let (px, py) = (mi_c * MI, mi_r * MI);
8099 let (cpx, cpy) = (px / 2, py / 2);
8100 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
8101 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
8102 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw > bh {
8103 (&SCAN_32X8, &SCAN_16X4)
8104 } else {
8105 (&SCAN_8X32, &SCAN_4X16)
8106 };
8107 let (luma_levels, u_levels, v_levels) = if skip {
8108 (
8109 vec![0i32; bw * bh],
8110 vec![0i32; chroma_w * chroma_h],
8111 vec![0i32; chroma_w * chroma_h],
8112 )
8113 } else {
8114 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
8115 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
8116 let (luma_levels, luma_tx_type) = read_coeffs_rect(
8117 dec,
8118 &mut luma_coding,
8119 luma_scan,
8120 bw,
8121 bh,
8122 0,
8123 dc_sign_ctx(around[0].2),
8124 TxType::DctDct,
8125 )?;
8126 let mut planes = Vec::with_capacity(2);
8127 for plane in 1..3 {
8128 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
8129 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
8130 let mut coding = cdfs.txb(TxbSet::Chroma8, uv_predict_mode);
8131 let (levels, tx_type) = read_coeffs_rect(
8132 dec,
8133 &mut coding,
8134 chroma_scan,
8135 chroma_w,
8136 chroma_h,
8137 skip_ctx,
8138 dc_sign_ctx(around[plane].2),
8139 default_tx,
8140 )?;
8141 planes.push((levels, tx_type));
8142 }
8143 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
8144 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
8145 RECT4_COEFF_HITS.with(|c| c.set(c.get() + 1));
8146 let luma_residual = dequant_and_inverse_typed_wh(
8147 &luma_levels,
8148 bw,
8149 bh,
8150 crate::decode::bit_depth(),
8151 block_q_idx(),
8152 plane_q_delta(0).0,
8153 plane_q_delta(0).1,
8154 luma_tx_type,
8155 );
8156 if let Some(b) = &palette_y_buf {
8157 set_palette_pred(b.clone());
8158 }
8159 y.reconstruct_rect(
8160 px,
8161 py,
8162 bw,
8163 bh,
8164 mode,
8165 angle_delta_y,
8166 reach,
8167 &luma_residual,
8168 None,
8169 filter_intra,
8170 smooth_neighbor,
8171 );
8172 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
8173 for (plane, buf, levels, tx_type) in [
8174 (1usize, &mut *u, &u_levels, u_tx_type),
8175 (2, &mut *v, &v_levels, v_tx_type),
8176 ] {
8177 let residual = dequant_and_inverse_typed_wh(
8178 levels,
8179 chroma_w,
8180 chroma_h,
8181 crate::decode::bit_depth(),
8182 block_q_idx(),
8183 plane_q_delta(plane).0,
8184 plane_q_delta(plane).1,
8185 tx_type,
8186 );
8187 if let Some((ub, vb)) = &palette_uv_bufs {
8188 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() });
8189 }
8190 buf.reconstruct_rect(
8191 cpx,
8192 cpy,
8193 chroma_w,
8194 chroma_h,
8195 uv_predict_mode,
8196 angle_delta_uv,
8197 reach,
8198 &residual,
8199 alpha
8200 .zip(ac.as_deref())
8201 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
8202 None,
8203 smooth_neighbor_uv,
8204 );
8205 }
8206 neighbours.record_mi_rect(
8207 (mi_r, mi_c),
8208 bw,
8209 bh,
8210 &[luma_levels, u_levels, v_levels],
8211 );
8212 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
8213 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0);
8214 record_strip_palette(
8215 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
8216 pal_uv_colors, pal_last,
8217 );
8218 if bw > bh {
8219 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
8220 } else {
8221 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
8222 }
8223 return Ok((mode, uv_predict_mode));
8224 };
8225 if let Some(b) = &palette_y_buf {
8226 set_palette_pred(b.clone());
8227 }
8228 y.reconstruct_rect(
8229 px,
8230 py,
8231 bw,
8232 bh,
8233 mode,
8234 angle_delta_y,
8235 reach,
8236 &luma_levels,
8237 None,
8238 filter_intra,
8239 smooth_neighbor,
8240 );
8241 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
8242 if let Some((ub, _)) = &palette_uv_bufs {
8243 set_palette_pred(ub.clone());
8244 }
8245 u.reconstruct_rect(
8246 cpx,
8247 cpy,
8248 chroma_w,
8249 chroma_h,
8250 uv_predict_mode,
8251 angle_delta_uv,
8252 reach,
8253 &u_levels,
8254 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8255 None,
8256 smooth_neighbor_uv,
8257 );
8258 if let Some((_, vb)) = &palette_uv_bufs {
8259 set_palette_pred(vb.clone());
8260 }
8261 v.reconstruct_rect(
8262 cpx,
8263 cpy,
8264 chroma_w,
8265 chroma_h,
8266 uv_predict_mode,
8267 angle_delta_uv,
8268 reach,
8269 &v_levels,
8270 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8271 None,
8272 smooth_neighbor_uv,
8273 );
8274 neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[luma_levels.to_vec(), u_levels, v_levels]);
8275 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
8276 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0);
8277 record_strip_palette(
8278 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
8279 pal_last,
8280 );
8281 if bw > bh {
8282 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
8283 } else {
8284 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
8285 }
8286 Ok((mode, uv_predict_mode))
8287}
8288
8289/// Decodes the four 16x4 / 4x16 strips of a 16x16-level `PARTITION_HORZ_4` /
8290/// `PARTITION_VERT_4` (lane-r14) -- [`decode_block_rect4`]'s pair one level
8291/// down, and the first shape here whose luma block is a single mi row (or
8292/// column).
8293///
8294/// What is new at this size is CHROMA. `is_chroma_reference`
8295/// (`av1_common_int.h`) is false for a 4:2:0 block one mi tall (wide) on an
8296/// EVEN mi row (column), so strips 0 and 2 read no `uv_mode`/`cfl_alpha`/
8297/// `angle_delta_uv` at all and code no chroma residual; strips 1 and 3 close
8298/// the pair and carry the chroma of the whole 16x8 (8x16) luma pair --
8299/// `setup_pred_plane`'s own `if (subsampling_y && (mi_row & 1) &&
8300/// mi_size_high[bsize] == 1) mi_row -= 1` offset, i.e. an 8x4 (4x8) chroma
8301/// transform at the PAIR's origin, with CfL averaging over the pair's luma.
8302///
8303/// Tables: LUMA `TX_16X4`/`TX_4X16` averages to the 8x8 entropy context
8304/// ((0 + 2 + 1) >> 1 = 1) with 64 coded positions, so its CDF set is
8305/// [`TxbSet::LumaRect16x4`] (`Luma8`'s tables, the `TX_4X4` `tx_type` row);
8306/// scans are [`SCAN_16X4`]/[`SCAN_4X16`]. CHROMA `TX_8X4`/`TX_4X8` is
8307/// [`TxbSet::ChromaRect8x4`] with [`SCAN_8X4`]/[`SCAN_4X8`]. Angle deltas ARE
8308/// coded (`av1_use_angle_delta` compares the BLOCK_SIZES_ALL enum index, and
8309/// BLOCK_16X4 is 17), and so is `use_filter_intra` (both sides <= 32) off this
8310/// shape's own CDF row.
8311///
8312/// A split transform (`tx_depth != 0`, `sub_tx_size_map[TX_16X4] == TX_8X4`)
8313/// refuses by name rather than guess-decode.
8314#[allow(clippy::too_many_arguments)]
8315fn decode_rect4_16(
8316 dec: &mut SymbolDecoder,
8317 cdfs: &mut Cdfs,
8318 neighbours: &mut Neighbours,
8319 at16: (usize, usize),
8320 horz: bool,
8321 y: &mut PlaneBuf,
8322 u: &mut PlaneBuf,
8323 v: &mut PlaneBuf,
8324 enable_filter_intra: bool,
8325 allow_screen_content_tools: bool,
8326 base_q_idx: u8,
8327 tx_select: bool,
8328 reduced_tx_set: bool,
8329) -> Result<()> {
8330 let (r, c) = at16;
8331 let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI));
8332 let (bw, bh) = if horz { (16, 4) } else { (4, 16) };
8333 let (mi_w, mi_h) = (bw / MI, bh / MI);
8334 let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
8335 let chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
8336 let mut prev: Option<((usize, usize), usize)> = None;
8337 let mut last_mode = DC_PRED;
8338 let mut last_uv_mode = DC_PRED;
8339 for i in 0..4usize {
8340 let lmi = if horz {
8341 (mi_row0 + i, mi_col0)
8342 } else {
8343 (mi_row0, mi_col0 + i)
8344 };
8345 let has_chroma = i % 2 == 1;
8346 // `decode_block_rect4`'s own neighbour rule: the coarse 16-px cell
8347 // aliases all four strips onto one entry, so the mi-exact map wins and
8348 // the previous strip stands in on the split axis.
8349 let mut above_mode = neighbours.above_mode[c];
8350 let mut left_mode = neighbours.left_mode[r];
8351 if let Some(((pr, pc), pmode)) = prev {
8352 if pc == lmi.1 && lmi.0 == pr + mi_h {
8353 above_mode = pmode;
8354 } else if pr == lmi.0 && lmi.1 == pc + mi_w {
8355 left_mode = pmode;
8356 }
8357 }
8358 let (above_mode, left_mode) =
8359 neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode));
8360 // lane-kf900 r4: the strip's real palette ctx + colour cache (see
8361 // [`decode_block_rect4`]); `None`/`&[]` here read `palette_y_mode`
8362 // off CDF row 0 and every cache hit off an empty cache.
8363 let (palette_ctx, palette_cache) =
8364 neighbours.palette_ctx_and_cache_mi(at16, lmi.0);
8365 let palette_uv_cache = neighbours.palette_uv_cache_mi(at16, lmi.0);
8366 let (
8367 skip,
8368 mode,
8369 angle_delta_y,
8370 uv_mode,
8371 angle_delta_uv,
8372 alpha,
8373 filter_intra,
8374 palette_y,
8375 palette_uv,
8376 ) = read_intra_mode_rect(
8377 dec,
8378 cdfs,
8379 above_mode,
8380 left_mode,
8381 true,
8382 has_chroma,
8383 bw,
8384 bh,
8385 enable_filter_intra,
8386 neighbours.skip_txfm_ctx(lmi.0, lmi.1),
8387 allow_screen_content_tools,
8388 Some((palette_ctx, &palette_cache)),
8389 &palette_uv_cache,
8390 lmi.0,
8391 lmi.1,
8392 )?;
8393 if palette_y.is_some() || palette_uv.is_some() {
8394 RECT4_PALETTE_HITS.with(|h| h.set(h.get() + 1));
8395 }
8396 // The colour-index map through the base colours IS the prediction.
8397 // Chroma's map is the PAIR's 8x4 (4x8) block, matching the one
8398 // chroma transform this closing strip codes.
8399 let palette_y_buf: Option<Vec<u16>> = palette_y
8400 .as_ref()
8401 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
8402 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
8403 (
8404 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
8405 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
8406 )
8407 });
8408 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
8409 if smooth_neighbor {
8410 SMOOTH_LUMA_HITS.with(|h| h.set(h.get() + 1));
8411 }
8412 if filter_intra.is_some() {
8413 FILTER_INTRA_RECT_HITS.with(|h| h.set(h.get() + 1));
8414 }
8415 // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is
8416 // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the
8417 // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol
8418 // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does.
8419 let depth = if tx_select {
8420 let ctx = tx_size_context_rect(neighbours, lmi, bw, bh);
8421 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
8422 } else {
8423 0
8424 };
8425 if depth != 0 {
8426 TX_DEPTH_HITS.with(|h| h.set(h.get() + 1));
8427 RECT4_16_SPLIT_HITS.with(|h| h.set(h.get() + 1));
8428 }
8429 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
8430 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
8431 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
8432 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode);
8433 if depth != 0 {
8434 // [`decode_rect_split`]'s per-unit walk, inlined because the
8435 // CHROMA of this shape belongs to the strip's 4:2:0 pair, not to
8436 // the strip (that function codes one chroma transform per block).
8437 // depth 1 is the 2:1 rect unit TX_8X4/TX_4X8
8438 // (`sub_tx_size_map[TX_16X4]`), depth 2 the square TX_4X4; each
8439 // unit predicts off the units before it in raster order.
8440 let rect_unit = tx_w != tx_h;
8441 let zero_tu = vec![0i32; tx_w * tx_h];
8442 for tu_row in 0..bh / tx_h {
8443 for tu_col in 0..bw / tx_w {
8444 let tu_mi = (lmi.0 + tu_row * (tx_h / MI), lmi.1 + tu_col * (tx_w / MI));
8445 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
8446 let tu_reach = Reach::of_tu(
8447 bw,
8448 bh,
8449 tu_col * tx_w,
8450 tu_row * tx_h,
8451 tx_w,
8452 tx_h,
8453 reach,
8454 );
8455 if let Some(b) = &palette_y_buf {
8456 let tu_buf: Vec<u16> = (0..tx_h)
8457 .flat_map(|i| {
8458 let base = (tu_row * tx_h + i) * bw + tu_col * tx_w;
8459 b[base..base + tx_w].iter().copied()
8460 })
8461 .collect();
8462 set_palette_pred(tu_buf);
8463 }
8464 if skip {
8465 y.reconstruct_rect(
8466 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &zero_tu,
8467 None, filter_intra, smooth_neighbor,
8468 );
8469 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
8470 } else if rect_unit {
8471 // `get_txsize_entropy_ctx(TX_8X4)` is the 8x8 class with
8472 // 32 coded positions and the `TX_4X4` `tx_type` row:
8473 // exactly [`TxbSet::LumaRect4x8`].
8474 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
8475 let tu_skip_ctx =
8476 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI);
8477 let set = if reduced_tx_set {
8478 TxbSet::LumaRect4x8
8479 } else {
8480 TxbSet::LumaRect4x8Set1
8481 };
8482 let tu_scan: &[u16] = if tx_w > tx_h { &SCAN_8X4 } else { &SCAN_4X8 };
8483 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
8484 let (tu_grid, tu_tx_type) = read_coeffs_rect(
8485 dec,
8486 &mut coding,
8487 tu_scan,
8488 tx_w,
8489 tx_h,
8490 tu_skip_ctx,
8491 dc_sign_ctx(tu_around.2),
8492 TxType::DctDct,
8493 )?;
8494 let residual = dequant_and_inverse_typed_wh(
8495 &tu_grid,
8496 tx_w,
8497 tx_h,
8498 crate::decode::bit_depth(),
8499 block_q_idx(),
8500 plane_q_delta(0).0,
8501 plane_q_delta(0).1,
8502 tu_tx_type,
8503 );
8504 y.reconstruct_rect(
8505 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &residual,
8506 None, filter_intra, smooth_neighbor,
8507 );
8508 if tu_grid.iter().any(|&l| l != 0) {
8509 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));
8510 }
8511 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
8512 } else {
8513 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
8514 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
8515 let tu_grid = read_plane(
8516 dec,
8517 cdfs,
8518 txbset_for(tx_w, reduced_tx_set),
8519 &default_scan(tx_w),
8520 0,
8521 tu_around,
8522 mode,
8523 mode,
8524 angle_delta_y,
8525 tu_reach,
8526 y,
8527 tu_px,
8528 tu_py,
8529 tx_w,
8530 tx_w,
8531 base_q_idx,
8532 None,
8533 filter_intra,
8534 Some(tu_skip_ctx),
8535 smooth_neighbor,
8536 )?;
8537 if tu_grid.iter().any(|&l| l != 0) {
8538 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));
8539 }
8540 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
8541 }
8542 }
8543 }
8544 } else {
8545 let levels = if skip {
8546 let zeros = vec![0i32; bw * bh];
8547 if let Some(b) = &palette_y_buf {
8548 set_palette_pred(b.clone());
8549 }
8550 y.reconstruct_rect(
8551 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
8552 smooth_neighbor,
8553 );
8554 zeros
8555 } else {
8556 // The strip's luma TU *is* the strip (`plane_bsize ==
8557 // txsize_to_bsize[tx_size]`), so `get_txb_ctx` fixes
8558 // `txb_skip_ctx` at 0.
8559 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
8560 let set = if reduced_tx_set {
8561 TxbSet::LumaRect16x4
8562 } else {
8563 TxbSet::LumaRect16x4Set1
8564 };
8565 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
8566 let (levels, tx_type) = read_coeffs_rect(
8567 dec,
8568 &mut coding,
8569 scan,
8570 bw,
8571 bh,
8572 0,
8573 dc_sign_ctx(around.2),
8574 TxType::DctDct,
8575 )?;
8576 let residual = dequant_and_inverse_typed_wh(
8577 &levels,
8578 bw,
8579 bh,
8580 crate::decode::bit_depth(),
8581 block_q_idx(),
8582 plane_q_delta(0).0,
8583 plane_q_delta(0).1,
8584 tx_type,
8585 );
8586 if let Some(b) = &palette_y_buf {
8587 set_palette_pred(b.clone());
8588 }
8589 y.reconstruct_rect(
8590 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
8591 smooth_neighbor,
8592 );
8593 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));
8594 levels
8595 };
8596 neighbours.record_mi_luma_rect(lmi, bw, bh, &levels);
8597 }
8598 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
8599 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0);
8600 // `update_partition_context` writes `partition_context_lookup[
8601 // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on
8602 // the left (mirrored under VERT_4).
8603 for cell in 0..mi_w {
8604 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
8605 *slot = bw;
8606 }
8607 }
8608 for cell in 0..mi_h {
8609 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
8610 *slot = bh;
8611 }
8612 }
8613 if has_chroma {
8614 RECT4_16_CHROMA_HITS.with(|h| h.set(h.get() + 1));
8615 let pair_mi = if horz {
8616 (lmi.0 - 1, lmi.1)
8617 } else {
8618 (lmi.0, lmi.1 - 1)
8619 };
8620 let (pw, ph) = if horz { (16, 8) } else { (8, 16) };
8621 let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI);
8622 let (cpx, cpy) = (ppx / 2, ppy / 2);
8623 let (cw, ch) = (pw / 2, ph / 2);
8624 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
8625 if (V_PRED..=D67_PRED).contains(&uv_predict_mode) {
8626 RECT4_16_CHROMA_DIR_HITS.with(|h| h.set(h.get() + 1));
8627 }
8628 let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height);
8629 // lane-kf1200 r1: the chroma edge-filter type reads the neighbours
8630 // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s
8631 // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/
8632 // `chroma_left_mbmi` from `mi[-((mi_row & ss_y) * stride + (mi_col
8633 // & ss_x))]` (`set_mi_offsets`, av1/common/blockd.h ~1050), i.e.
8634 // the pair's top-left luma mi, never this leaf's odd row/column.
8635 // Reading `lmi` here named the leaf directly above (a non-chroma
8636 // -reference 4-row block, `uv_mode == UV_DC_PRED`) and so lost a
8637 // SMOOTH neighbour: filt_type 0 instead of 1 turned
8638 // `av1_use_intra_edge_upsample` on (blk_wh 12 <= 16) for a
8639 // directional chroma strip, moving 4 samples by 1.
8640 let smooth_neighbor_uv =
8641 neighbours.smooth_uv_neighbour(pair_mi.0, pair_mi.1, r, c);
8642 if smooth_neighbor_uv != neighbours.smooth_uv_neighbour_unsnapped(lmi.0, lmi.1, r, c)
8643 {
8644 RECT4_16_UV_PAIR_FILT_HITS.with(|h| h.set(h.get() + 1));
8645 }
8646 let (u_levels, v_levels) = if skip {
8647 let zeros = vec![0i32; cw * ch];
8648 // libaom `predict_and_reconstruct_intra_block` (decodeframe.c
8649 // ~1000) predicts EVERY plane and only guards the residual on
8650 // `mbmi->skip_txfm`, so a skipped `UV_CFL_PRED` block is still
8651 // DC + alpha * luma-AC. Dropping the CfL term here left a
8652 // chroma-only bounded box on ReelC's key frames.
8653 let ac = alpha.map(|_| cfl_ac_q3_rect(y, ppx, ppy, pw, ph));
8654 if alpha.is_some() {
8655 CHROMA_SKIP_CFL_HITS.with(|h| h.set(h.get() + 1));
8656 }
8657 for (buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] {
8658 if let Some((ub, vb)) = &palette_uv_bufs {
8659 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() });
8660 }
8661 buf.reconstruct_rect(
8662 cpx,
8663 cpy,
8664 cw,
8665 ch,
8666 uv_predict_mode,
8667 angle_delta_uv,
8668 pair_reach,
8669 &zeros,
8670 alpha
8671 .zip(ac.as_deref())
8672 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
8673 None,
8674 smooth_neighbor_uv,
8675 );
8676 }
8677 (zeros.clone(), zeros)
8678 } else {
8679 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
8680 let mut planes = Vec::with_capacity(2);
8681 for plane in 1..3 {
8682 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
8683 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
8684 let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
8685 let (levels, tx_type) = read_coeffs_rect(
8686 dec,
8687 &mut coding,
8688 chroma_scan,
8689 cw,
8690 ch,
8691 skip_ctx,
8692 dc_sign_ctx(around[plane].2),
8693 default_tx,
8694 )?;
8695 planes.push((levels, tx_type));
8696 }
8697 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
8698 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
8699 // CfL averages the luma of the WHOLE pair, the region this one
8700 // chroma transform covers.
8701 let ac = alpha.map(|_| cfl_ac_q3_rect(y, ppx, ppy, pw, ph));
8702 for (plane, buf, levels, tx_type) in [
8703 (1usize, &mut *u, &u_levels, u_tx_type),
8704 (2, &mut *v, &v_levels, v_tx_type),
8705 ] {
8706 let residual = dequant_and_inverse_typed_wh(
8707 levels,
8708 cw,
8709 ch,
8710 crate::decode::bit_depth(),
8711 block_q_idx(),
8712 plane_q_delta(plane).0,
8713 plane_q_delta(plane).1,
8714 tx_type,
8715 );
8716 if let Some((ub, vb)) = &palette_uv_bufs {
8717 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() });
8718 }
8719 buf.reconstruct_rect(
8720 cpx,
8721 cpy,
8722 cw,
8723 ch,
8724 uv_predict_mode,
8725 angle_delta_uv,
8726 pair_reach,
8727 &residual,
8728 alpha
8729 .zip(ac.as_deref())
8730 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
8731 None,
8732 smooth_neighbor_uv,
8733 );
8734 }
8735 (u_levels, v_levels)
8736 };
8737 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, uv_predict_mode);
8738 // The chroma planes' coefficient context, over the PAIR's mi span
8739 // (`decode_leaf_rect8`'s own rule: a subsampled plane's bound is
8740 // the luma one rounded up to its 4x4 unit).
8741 let u_state = neighbour_state(&u_levels);
8742 let v_state = neighbour_state(&v_levels);
8743 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8744 let bound_h = round_up_even(neighbours.mi_rows);
8745 let bound_w = round_up_even(neighbours.mi_cols);
8746 for cell in 0..(ph / MI) {
8747 if pair_mi.0 + cell < bound_h
8748 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
8749 {
8750 slot[1] = u_state;
8751 slot[2] = v_state;
8752 }
8753 }
8754 for cell in 0..(pw / MI) {
8755 if pair_mi.1 + cell < bound_w
8756 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
8757 {
8758 slot[1] = u_state;
8759 slot[2] = v_state;
8760 }
8761 }
8762 last_uv_mode = uv_predict_mode;
8763 }
8764 if horz {
8765 RECT4_16_HORZ_HITS.with(|h| h.set(h.get() + 1));
8766 } else {
8767 RECT4_16_VERT_HITS.with(|h| h.set(h.get() + 1));
8768 }
8769 let (pal_y_size, pal_y_colors) =
8770 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
8771 let (pal_uv_size, pal_uv_colors) =
8772 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
8773 record_strip_palette(
8774 neighbours, at16, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
8775 i == 3,
8776 );
8777 last_mode = mode;
8778 prev = Some((lmi, mode));
8779 }
8780 // The coarse 16-px cell holds one entry for the whole 16x16: the last
8781 // strip is what a block below (right) sees through it, the mi-exact maps
8782 // above answering everything finer.
8783 neighbours.above_mode[c] = last_mode;
8784 neighbours.left_mode[r] = last_mode;
8785 neighbours.above_uv_mode[c] = last_uv_mode;
8786 neighbours.left_uv_mode[r] = last_uv_mode;
8787 neighbours.above_side[c] = bw;
8788 neighbours.left_side[r] = bh;
8789 Ok(())
8790}
8791
8792/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
8793/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
8794/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
8795/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
8796/// cap, so LUMA needs the same corner truncation [`decode_block`] already
8797/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
8798/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
8799/// this function's own charter/report), so both strips read a real 32x32
8800/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
8801/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
8802/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
8803/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
8804/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
8805/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
8806/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
8807/// that function, only the single-transform-unit (`tx_depth == 0`) case is
8808/// supported: a split transform refuses by name rather than guess-decode.
8809#[allow(clippy::too_many_arguments)]
8810fn decode_block_rect64(
8811 dec: &mut SymbolDecoder,
8812 cdfs: &mut Cdfs,
8813 neighbours: &mut Neighbours,
8814 at: (usize, usize),
8815 bw: usize,
8816 bh: usize,
8817 y: &mut PlaneBuf,
8818 u: &mut PlaneBuf,
8819 v: &mut PlaneBuf,
8820 enable_filter_intra: bool,
8821 allow_screen_content_tools: bool,
8822 base_q_idx: u8,
8823 tx_select: bool,
8824 reduced_tx_set: bool,
8825) -> Result<()> {
8826 let (r, c) = at;
8827 let (px, py) = (c * SUB, r * SUB);
8828 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
8829 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
8830 let palette_uv_cache = neighbours.palette_uv_cache(at);
8831 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
8832 read_intra_mode_rect(
8833 dec,
8834 cdfs,
8835 nb_above_mode,
8836 nb_left_mode,
8837 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
8838 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
8839 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
8840 // correct), CFL must never be offered here -- passing `true`
8841 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
8842 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
8843 // from this block's very first symbol (lane-sbpart r3 bisect).
8844 false,
8845 true,
8846 bw,
8847 bh,
8848 enable_filter_intra,
8849 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
8850 allow_screen_content_tools,
8851 Some((palette_ctx, &palette_cache)),
8852 &palette_uv_cache,
8853 r * (SUB / MI),
8854 c * (SUB / MI),
8855 )?;
8856 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
8857 // The luma coefficient path here is the corner-cropped 32x32 real
8858 // transform embedded in a 64x32/32x64 grid ([`decode_block_rect64`]'s
8859 // own doc comment) -- a real (non-skip) palette block's residual
8860 // needs the plain, uncropped rect reader [`decode_block_rect`] already
8861 // has, not this one's truncation. `skip` (no residual at all) is
8862 // still supported below (lane-palette2 r4).
8863 return Err(unsupported(
8864 "a palette block with a real transform on a superblock-level HORZ/VERT \
8865 strip (corner-cropped luma coefficients not ported for palette)",
8866 ));
8867 }
8868 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
8869 if smooth_neighbor {
8870 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
8871 }
8872 let smooth_neighbor_uv =
8873 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
8874 if filter_intra.is_some() {
8875 // `filter_intra_size_class_rect` already returns `None` for both
8876 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
8877 // 32 on both axes), so this symbol is never read at this level --
8878 // kept only as the same defensive refusal [`decode_block_rect`] has.
8879 return Err(unsupported(
8880 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
8881 av1_filter_intra_allowed_bsize caps at 32x32)",
8882 ));
8883 }
8884 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
8885 DC_PRED
8886 } else {
8887 uv_mode
8888 };
8889 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
8890 let depth = if tx_select {
8891 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
8892 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
8893 // counts `sub_tx_size_map` steps from the block's own max rect
8894 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
8895 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
8896 // steps, so this level's category is 3 (the same one a 64x64 square
8897 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
8898 // here was a wrong-table read of a real symbol.
8899 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
8900 } else {
8901 0
8902 };
8903 if depth != 0 {
8904 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
8905 // lane-rectsplit r1/r4: the superblock-level strip splits its
8906 // transform through the very same per-unit path as its 32x32-level
8907 // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64
8908 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
8909 // measured the old square formula mis-tiling exactly that strip).
8910 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
8911 if bw.max(bh) / bw.min(bh) == 4 {
8912 let which = if depth == 1 {
8913 &RECT4_SPLIT_DEPTH1_HITS
8914 } else {
8915 &RECT4_SPLIT_DEPTH2_HITS
8916 };
8917 which.with(|c| c.set(c.get() + 1));
8918 }
8919 if std::env::var_os("EC_SBPART_DUMP64").is_some() {
8920 eprintln!(
8921 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
8922 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
8923 angle_y={angle_delta_y}"
8924 );
8925 }
8926 let modes = RectStripModes {
8927 skip,
8928 mode,
8929 angle_delta_y,
8930 uv_predict_mode,
8931 angle_delta_uv,
8932 alpha,
8933 filter_intra,
8934 smooth_neighbor,
8935 smooth_neighbor_uv,
8936 palette_y: palette_y
8937 .as_ref()
8938 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
8939 palette_uv: palette_uv.as_ref().map(|p| {
8940 (
8941 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
8942 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
8943 )
8944 }),
8945 };
8946 if palette_y.is_some() || palette_uv.is_some() {
8947 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
8948 }
8949 decode_rect_split(
8950 dec,
8951 cdfs,
8952 neighbours,
8953 (mi_r, mi_c),
8954 bw,
8955 bh,
8956 tx_w,
8957 tx_h,
8958 &modes,
8959 y,
8960 u,
8961 v,
8962 base_q_idx,
8963 reduced_tx_set,
8964 )?;
8965 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
8966 // (lane-palette2 r10): this return skips the fn's own tail, so a
8967 // split-tx superblock strip would otherwise leave the above/left
8968 // palette arrays holding a dead block's colours.
8969 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
8970 neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
8971 let (puv_size, puv_colors) =
8972 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
8973 neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
8974 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
8975 return Ok(());
8976 }
8977 let (tx_w, tx_h) = (bw, bh);
8978 let (cpx, cpy) = (px / 2, py / 2);
8979 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
8980 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
8981 if let Some(ref pyv) = palette_y {
8982 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
8983 set_palette_pred(buf);
8984 }
8985 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
8986 (
8987 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
8988 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
8989 )
8990 });
8991 if skip {
8992 y.reconstruct_rect(
8993 px,
8994 py,
8995 bw,
8996 bh,
8997 mode,
8998 angle_delta_y,
8999 reach,
9000 &vec![0i32; bw * bh],
9001 None,
9002 filter_intra,
9003 smooth_neighbor,
9004 );
9005 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
9006 if let Some((ub, _)) = &palette_uv_bufs {
9007 set_palette_pred(ub.clone());
9008 }
9009 u.reconstruct_rect(
9010 cpx,
9011 cpy,
9012 chroma_w,
9013 chroma_h,
9014 uv_predict_mode,
9015 angle_delta_uv,
9016 reach,
9017 &vec![0i32; chroma_w * chroma_h],
9018 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
9019 None,
9020 smooth_neighbor_uv,
9021 );
9022 if let Some((_, vb)) = &palette_uv_bufs {
9023 set_palette_pred(vb.clone());
9024 }
9025 v.reconstruct_rect(
9026 cpx,
9027 cpy,
9028 chroma_w,
9029 chroma_h,
9030 uv_predict_mode,
9031 angle_delta_uv,
9032 reach,
9033 &vec![0i32; chroma_w * chroma_h],
9034 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
9035 None,
9036 smooth_neighbor_uv,
9037 );
9038 neighbours.record_rect(
9039 at,
9040 bw,
9041 bh,
9042 mode,
9043 uv_predict_mode,
9044 &[
9045 vec![0i32; bw * bh],
9046 vec![0i32; chroma_w * chroma_h],
9047 vec![0i32; chroma_w * chroma_h],
9048 ],
9049 );
9050 } else {
9051 let around = neighbours.around_rect(at, bw, bh);
9052 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
9053 // (see this function's own doc comment). A 64-length axis codes only
9054 // its low 32 coefficients, so the corner is `min(bw, 32)` x
9055 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
9056 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
9057 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
9058 let scan32 = default_scan(TX32);
9059 if std::env::var_os("EC_TRACE_COEFF").is_some() {
9060 let (rng, _) = dec.debug_state();
9061 eprintln!("EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}");
9062 }
9063 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
9064 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
9065 read_coeffs(
9066 dec,
9067 &mut luma_coding,
9068 &scan32,
9069 0,
9070 dc_sign_ctx(around[0].2),
9071 TxType::DctDct,
9072 Some((bw, bh)),
9073 )?
9074 } else {
9075 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
9076 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
9077 // (`scan.c`) gives both the very same `default_scan_32x16` /
9078 // `default_scan_16x32` the 2:1 sizes use ("Half of the
9079 // coefficients of tx64 at higher frequencies are set to zeros. So
9080 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
9081 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
9082 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
9083 // 512-position eob group) -- BOTH identical to TX_32X16, so the
9084 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
9085 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
9086 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
9087 // what `base_ctx_rect` computes at (32, 16).
9088 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
9089 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
9090 read_coeffs_rect(
9091 dec,
9092 &mut luma_coding,
9093 luma_scan,
9094 luma_cw,
9095 luma_ch,
9096 0,
9097 dc_sign_ctx(around[0].2),
9098 TxType::DctDct,
9099 )?
9100 };
9101 if std::env::var_os("EC_TRACE_COEFF").is_some() {
9102 let (rng, _) = dec.debug_state();
9103 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
9104 }
9105 let mut luma_levels = vec![0i32; bw * bh];
9106 for row in 0..luma_ch {
9107 luma_levels[row * bw..][..luma_cw]
9108 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
9109 }
9110 {
9111 let cur = block_q_idx();
9112 if cur != i32::from(base_q_idx) {
9113 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
9114 }
9115 if std::env::var_os("EC_AV1_TRACE").is_some() {
9116 eprintln!(
9117 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
9118 );
9119 }
9120 }
9121 let luma_residual = dequant_and_inverse_typed_wh(
9122 &luma_levels,
9123 bw,
9124 bh,
9125 crate::decode::bit_depth(),
9126 block_q_idx(),
9127 plane_q_delta(0).0,
9128 plane_q_delta(0).1,
9129 luma_tx_type,
9130 );
9131 y.reconstruct_rect(
9132 px,
9133 py,
9134 bw,
9135 bh,
9136 mode,
9137 angle_delta_y,
9138 reach,
9139 &luma_residual,
9140 None,
9141 filter_intra,
9142 smooth_neighbor,
9143 );
9144 if std::env::var_os("EC_SBPART_DUMP64").is_some() {
9145 let leftcol: Vec<u16> = if px > 0 {
9146 (py..py + bh).map(|row| y.data[row * y.width + px - 1]).collect()
9147 } else {
9148 vec![]
9149 };
9150 eprintln!(
9151 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
9152 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
9153 luma_corner.iter().any(|&v| v != 0),
9154 &y.data[py * y.width + px..][..bw],
9155 leftcol,
9156 );
9157 }
9158 // CHROMA: a real, untruncated chroma_w x chroma_h transform -- no
9159 // corner crop needed (see doc comment).
9160 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
9161 // The chroma plane is never truncated (both axes <= 32 after
9162 // subsampling). Under a 1:4 strip it is a true 32x8/8x32:
9163 // `get_txsize_entropy_ctx(TX_32X8)` = (TX_8X8 + TX_32X32 + 1) >> 1 =
9164 // TX_16X16 and `txsize_log2_minus4[TX_32X8]` = 4 (256 positions),
9165 // both identical to TX_16X16 -- so [`TxbSet::Chroma16`] is the exact
9166 // set, and only the scan is new (lane-tx64x16).
9167 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (bw, bh) {
9168 (64, 16) => (TxbSet::Chroma16, &SCAN_32X8),
9169 (16, 64) => (TxbSet::Chroma16, &SCAN_8X32),
9170 (64, _) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
9171 _ => (TxbSet::ChromaRect32x16, &SCAN_16X32),
9172 };
9173 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
9174 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
9175 if std::env::var_os("EC_TRACE_COEFF").is_some() {
9176 let (rng, _) = dec.debug_state();
9177 eprintln!("EC_COEFF plane=1 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
9178 }
9179 let (u_levels, u_tx_type) = read_coeffs_rect(
9180 dec,
9181 &mut u_coding,
9182 chroma_scan,
9183 chroma_w,
9184 chroma_h,
9185 u_skip_ctx,
9186 dc_sign_ctx(around[1].2),
9187 TxType::DctDct,
9188 )?;
9189 if std::env::var_os("EC_TRACE_COEFF").is_some() {
9190 let (rng, _) = dec.debug_state();
9191 eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}");
9192 }
9193 {
9194 let cur = block_q_idx();
9195 if cur != i32::from(base_q_idx) {
9196 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
9197 }
9198 if std::env::var_os("EC_AV1_TRACE").is_some() {
9199 eprintln!(
9200 "TRACE rect64_dequant plane=1 base_q_idx={base_q_idx} current_q_idx={cur}"
9201 );
9202 }
9203 }
9204 let u_residual = dequant_and_inverse_typed_wh(
9205 &u_levels,
9206 chroma_w,
9207 chroma_h,
9208 crate::decode::bit_depth(),
9209 block_q_idx(),
9210 plane_q_delta(1).0,
9211 plane_q_delta(1).1,
9212 u_tx_type,
9213 );
9214 u.reconstruct_rect(
9215 cpx,
9216 cpy,
9217 chroma_w,
9218 chroma_h,
9219 uv_predict_mode,
9220 angle_delta_uv,
9221 reach,
9222 &u_residual,
9223 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
9224 None,
9225 smooth_neighbor_uv,
9226 );
9227 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
9228 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
9229 if std::env::var_os("EC_TRACE_COEFF").is_some() {
9230 let (rng, _) = dec.debug_state();
9231 eprintln!("EC_COEFF plane=2 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
9232 }
9233 let (v_levels, v_tx_type) = read_coeffs_rect(
9234 dec,
9235 &mut v_coding,
9236 chroma_scan,
9237 chroma_w,
9238 chroma_h,
9239 v_skip_ctx,
9240 dc_sign_ctx(around[2].2),
9241 TxType::DctDct,
9242 )?;
9243 if std::env::var_os("EC_TRACE_COEFF").is_some() {
9244 let (rng, _) = dec.debug_state();
9245 eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}");
9246 }
9247 {
9248 let cur = block_q_idx();
9249 if cur != i32::from(base_q_idx) {
9250 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
9251 }
9252 if std::env::var_os("EC_AV1_TRACE").is_some() {
9253 eprintln!(
9254 "TRACE rect64_dequant plane=2 base_q_idx={base_q_idx} current_q_idx={cur}"
9255 );
9256 }
9257 }
9258 let v_residual = dequant_and_inverse_typed_wh(
9259 &v_levels,
9260 chroma_w,
9261 chroma_h,
9262 crate::decode::bit_depth(),
9263 block_q_idx(),
9264 plane_q_delta(2).0,
9265 plane_q_delta(2).1,
9266 v_tx_type,
9267 );
9268 v.reconstruct_rect(
9269 cpx,
9270 cpy,
9271 chroma_w,
9272 chroma_h,
9273 uv_predict_mode,
9274 angle_delta_uv,
9275 reach,
9276 &v_residual,
9277 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
9278 None,
9279 smooth_neighbor_uv,
9280 );
9281 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
9282 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
9283 }
9284 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
9285 neighbours.record_palette_y_rect(at, bw, bh, py_size, py_colors);
9286 let (puv_size, puv_colors) =
9287 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
9288 neighbours.record_palette_uv_rect(at, bw, bh, puv_size, puv_colors);
9289 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
9290 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
9291 SB_RECT_HITS.with(|c| c.set(c.get() + 1));
9292 match (bw, bh) {
9293 (64, 16) => SB_RECT4_HORZ_HITS.with(|c| c.set(c.get() + 1)),
9294 (16, 64) => SB_RECT4_VERT_HITS.with(|c| c.set(c.get() + 1)),
9295 _ => {}
9296 }
9297 if std::env::var_os("EC_AV1_TRACE").is_some() {
9298 let (rng, _) = dec.debug_state();
9299 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
9300 }
9301 Ok(())
9302}
9303
9304/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
9305/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
9306/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
9307/// it lands away from zero, for gate tests to prove a real stream fired one.
9308fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
9309 let symbol = dec.symbol(cdf);
9310 if symbol != ANGLE_DELTA_ZERO {
9311 ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
9312 }
9313 symbol as i32 - ANGLE_DELTA_ZERO as i32
9314}
9315
9316#[allow(clippy::too_many_arguments)]
9317fn read_intra_mode(
9318 dec: &mut SymbolDecoder,
9319 cdfs: &mut Cdfs,
9320 above_mode: usize,
9321 left_mode: usize,
9322 cfl: bool,
9323 side: usize,
9324 enable_filter_intra: bool,
9325 skip_ctx: usize,
9326 allow_screen_content_tools: bool,
9327 allow_intrabc: bool,
9328 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
9329 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
9330 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
9331 // `None` at the excluded call sites (the 8x8-leaf path), which still read
9332 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
9333 // decoder reads either way -- but refuse by name the moment it fires,
9334 // exactly the old behaviour.
9335 palette: Option<(usize, &[u16])>,
9336 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
9337 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
9338 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
9339 // `use_palette_y`, not a neighbour lookup).
9340 palette_uv_cache: &[u16],
9341 mi_r: usize,
9342 mi_c: usize,
9343) -> Result<(
9344 bool,
9345 usize,
9346 i32,
9347 usize,
9348 i32,
9349 Option<(i32, i32)>,
9350 Option<usize>,
9351 Option<PaletteY>,
9352 Option<PaletteUv>,
9353)> {
9354 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
9355 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
9356 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
9357 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
9358 // line against the instrumented aomdec, not just `tell()`.
9359 let ec_istep = std::env::var_os("EC_TRACE_MODE_STEP").is_some();
9360 if ec_istep {
9361 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
9362 // (decodemv.c:818), printed at the same point: before the first
9363 // mode-info symbol of the block, so a cross-decoder range ladder can
9364 // be keyed on the BLOCK, not just on the symbol sequence.
9365 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}", dec.debug_state().0);
9366 }
9367 macro_rules! istep {
9368 ($name:literal, $val:expr) => {
9369 if ec_istep {
9370 let (rng, _) = dec.debug_state();
9371 eprintln!(
9372 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
9373 $name, $val
9374 );
9375 }
9376 };
9377 }
9378 // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single
9379 // point every square caller routes through (see `read_intra_mode_rect`).
9380 let cfl = if cfl && side > 32 {
9381 NOCFL_UV_MODE_HITS.with(|c| c.set(c.get() + 1));
9382 false
9383 } else {
9384 cfl
9385 };
9386 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
9387 // `skip` when `SegIdPreSkip`, and after it otherwise.
9388 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
9389 if seg_id_pre_skip() {
9390 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);
9391 }
9392 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
9393 if trace {
9394 eprintln!("TRACE skip value={} rng={}", skip as i32, dec.debug_state().0);
9395 }
9396 istep!("skip", skip as i32);
9397 if !seg_id_pre_skip() {
9398 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);
9399 }
9400 // spec order (see the comment below on `read_intrabc_info`): `skip`,
9401 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
9402 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
9403 istep!("cdef", 0);
9404 // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not
9405 // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole
9406 // superblock and skips `delta_q` exactly like a 64 one under a 64 root.
9407 let whole_sb = side == sb_mi_cur() as usize * 4;
9408 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, whole_sb, skip);
9409 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, whole_sb, skip);
9410 istep!("dq", 0);
9411 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
9412 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
9413 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
9414 // intra frame whose header set `allow_intrabc`. Actual intra block copy
9415 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
9416 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
9417 // draws the line at consuming this one flag symbol and refusing by name
9418 // when it fires, so the arithmetic decoder still resyncs for a stream
9419 // that merely allows (but never uses) intrabc.
9420 if allow_intrabc {
9421 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
9422 if trace {
9423 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
9424 }
9425 if use_intrabc {
9426 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, side);
9427 if trace {
9428 eprintln!("TRACE intrabc dv={dv:?}");
9429 }
9430 INTRABC_DV.with(|c| c.set(Some(dv)));
9431 INTRABC_HITS.with(|c| c.set(c.get() + 1));
9432 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
9433 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
9434 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
9435 // `DC_PRED` (which is also what the neighbour mode contexts and
9436 // the loop filter then see).
9437 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
9438 }
9439 }
9440 let above_ctx = INTRA_MODE_CTX[above_mode];
9441 let left_ctx = INTRA_MODE_CTX[left_mode];
9442 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
9443 if trace {
9444 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
9445 }
9446 istep!("mode", mode as i32);
9447 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
9448 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
9449 if trace {
9450 eprintln!(
9451 "TRACE angle_delta value={}",
9452 delta + ANGLE_DELTA_ZERO as i32
9453 );
9454 }
9455 delta
9456 } else {
9457 0
9458 };
9459 istep!("angle_y", angle_delta_y);
9460 // lane-sb128c r3 (class sweep): `is_cfl_allowed` on the luma bsize, decided
9461 // here so every `decode_block` caller (64x64 and 128x128 roots included)
9462 // picks the right alphabet -- see [`read_intra_mode_rect`]'s twin.
9463 let cfl = cfl && side <= 32;
9464 let uv_mode = if cfl {
9465 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
9466 } else {
9467 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
9468 };
9469 if trace {
9470 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}", dec.debug_state().0);
9471 }
9472 istep!("uv_mode", uv_mode as i32);
9473 let alpha = if cfl && uv_mode == UV_CFL_PRED {
9474 Some(read_cfl_alphas(dec, cdfs))
9475 } else {
9476 None
9477 };
9478 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
9479 // from this lane's directional chroma: a corner block with neither
9480 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
9481 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
9482 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
9483 // bug in that fallback this lane's own scope does not cover. Keep it
9484 // refused here rather than ship a silently-wrong decode.
9485 if (9..=12).contains(&uv_mode) {
9486 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
9487 }
9488 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
9489 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
9490 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
9491 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
9492 // the `else` branch below and never reads one either way.
9493 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
9494 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
9495 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
9496 } else {
9497 0
9498 };
9499 istep!("angle_uv", angle_delta_uv);
9500 if angle_delta_uv != 0 {
9501 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
9502 }
9503 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
9504 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
9505 // gated by `av1_allow_palette` (blockd.h -- size bound only,
9506 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
9507 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
9508 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
9509 // read the same CDF row whenever every neighbour really is non-palette).
9510 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
9511 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
9512 // neighbour lookup at all), so it is exact even at the excluded call
9513 // sites once Y decodes real syntax there too.
9514 //
9515 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
9516 // inline from `read_palette_mode_info` -- it runs later, from
9517 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
9518 // after the WHOLE mode-info read for the block, including UV palette
9519 // mode_info (`read_palette_mode_info`'s own second half, right below)
9520 // and `read_filter_intra_mode_info`. So this branch now only reads
9521 // mode/size/colours for both planes (deferring the two colour-index-map
9522 // decodes to after `filter_intra`, below) -- r6's range trace pinned
9523 // this exact ordering bug (`compare-range-not-tell`: ranges matched
9524 // bit-for-bit through the Y colours, diverged only at the old inline
9525 // `decode_color_index_map` call).
9526 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
9527 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
9528 if allow_screen_content_tools
9529 && let Some(bsize_ctx) = palette_bsize_ctx(side)
9530 {
9531 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
9532 if mode == DC_PRED {
9533 if trace {
9534 let (rng, _) = dec.debug_state();
9535 eprintln!(
9536 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
9537 );
9538 }
9539 }
9540 let use_palette_y =
9541 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
9542 if mode == DC_PRED && trace {
9543 let (rng, _) = dec.debug_state();
9544 eprintln!("TRACE palette_y_mode value={} rng={rng}", use_palette_y as i32);
9545 }
9546 if use_palette_y {
9547 if palette.is_none() {
9548 return Err(unsupported(
9549 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
9550 ));
9551 }
9552 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
9553 if trace {
9554 let (rng, _) = dec.debug_state();
9555 eprintln!("TRACE palette_y_size n={n} rng={rng}");
9556 }
9557 let colors = read_palette_colors_y(dec, n, cache);
9558 if trace {
9559 let (rng, _) = dec.debug_state();
9560 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
9561 }
9562 palette_y_pending = Some((n, colors));
9563 }
9564 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
9565 // unconditionally at this bit position whenever `uv_mode ==
9566 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
9567 // scope always reconstructs chroma alongside luma (`decode_block`
9568 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
9569 // is always true here and does not need threading in.
9570 let palette_uv_mode_ctx = usize::from(use_palette_y);
9571 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
9572 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
9573 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache);
9574 palette_uv_pending = Some((n, u_colors, v_colors));
9575 }
9576 }
9577 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
9578 // `use_filter_intra` symbol this decoder never read at all until
9579 // lane-av1real r10 -- silently skipping it left every bit past a
9580 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
9581 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
9582 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
9583 // symbol's bits were never consumed).
9584 let mut filter_intra = None;
9585 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
9586 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
9587 // `use_filter_intra` symbol for a Y-palette block, and reading one here
9588 // desynced every screen-content stream from the first palette block on
9589 // (it surfaced as a bogus "partition below 8x8" refusal further down the
9590 // tile).
9591 if mode == DC_PRED
9592 && enable_filter_intra
9593 && palette_y_pending.is_none()
9594 && let Some(class) = filter_intra_size_class(side)
9595 {
9596 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
9597 if trace {
9598 eprintln!(
9599 "TRACE use_filter_intra side={side} rng={} value={}", dec.debug_state().0,
9600 use_filter_intra as i32
9601 );
9602 }
9603 istep!("use_filter_intra", use_filter_intra as i32);
9604 if use_filter_intra {
9605 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
9606 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
9607 if trace {
9608 eprintln!("TRACE filter_intra_mode value={fi_mode}");
9609 }
9610 istep!("filter_intra_mode", fi_mode as i32);
9611 filter_intra = Some(fi_mode);
9612 }
9613 }
9614 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
9615 // shared U/V map) -- the same order libaom's own loop visits them in.
9616 let palette_y = palette_y_pending.map(|(n, colors)| {
9617 let map = decode_color_index_map(dec, cdfs, n, side, false);
9618 PALETTE_HITS.with(|c| c.set(c.get() + 1));
9619 if trace {
9620 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
9621 }
9622 PaletteY { size: n, colors, map }
9623 });
9624 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
9625 let map = decode_color_index_map(dec, cdfs, n, side / 2, true);
9626 PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
9627 if trace {
9628 eprintln!(
9629 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
9630 &u_colors[..n],
9631 &v_colors[..n]
9632 );
9633 }
9634 PaletteUv { size: n, u_colors, v_colors, map }
9635 });
9636 Ok((
9637 skip,
9638 mode,
9639 angle_delta_y,
9640 uv_mode,
9641 angle_delta_uv,
9642 alpha,
9643 filter_intra,
9644 palette_y,
9645 palette_uv,
9646 ))
9647}
9648
9649/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
9650/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
9651/// intra modes.
9652const UV_CFL_PRED: usize = 13;
9653
9654/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
9655/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
9656/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
9657/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
9658/// joint sign the same way. Returns each plane's final signed `alpha_q3`
9659/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
9660fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
9661 CFL_BLOCK_HITS.with(|c| c.set(c.get() + 1));
9662 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
9663 let sign_u = ((joint_sign + 1) * 11) >> 5;
9664 let sign_v = (joint_sign + 1) - 3 * sign_u;
9665 let alpha_u = if sign_u == 0 {
9666 0
9667 } else {
9668 let ctx_u = (joint_sign + 1 - 3) as usize;
9669 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
9670 if sign_u == 2 { mag } else { -mag }
9671 };
9672 let alpha_v = if sign_v == 0 {
9673 0
9674 } else {
9675 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
9676 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
9677 if sign_v == 2 { mag } else { -mag }
9678 };
9679 (alpha_u, alpha_v)
9680}
9681
9682/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
9683/// the reconstructed luma samples under a `side`-square block, subsampled
9684/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
9685/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
9686/// to give the AC values [`cfl_scaled`] scales by alpha.
9687fn cfl_ac_q3(y: &PlaneBuf, px: usize, py: usize, side: usize) -> Vec<i32> {
9688 let cside = side / 2;
9689 let mut ac = vec![0i32; cside * cside];
9690 let mut sum = 0i32;
9691 for cy in 0..cside {
9692 for cx in 0..cside {
9693 let (lx, ly) = (px + cx * 2, py + cy * 2);
9694 let q3 = (i32::from(y.data[ly * y.width + lx])
9695 + i32::from(y.data[ly * y.width + lx + 1])
9696 + i32::from(y.data[(ly + 1) * y.width + lx])
9697 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
9698 << 1;
9699 ac[cy * cside + cx] = q3;
9700 sum += q3;
9701 }
9702 }
9703 let num_pel = (cside * cside) as i32;
9704 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
9705 ac.iter_mut().for_each(|v| *v -= avg);
9706 ac
9707}
9708
9709/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
9710/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
9711/// ties away from zero on the shifted-out sign).
9712fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
9713 let v = alpha_q3 * ac_q3;
9714 if v >= 0 {
9715 (v + 32) >> 6
9716 } else {
9717 -((-v + 32) >> 6)
9718 }
9719}
9720
9721/// One plane's reconstruction buffer, `width * height` samples, and the
9722/// prediction/residual reads and writes into it — the decode-side twin of
9723/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
9724/// (own-edge and reach clamps both), passing what it gathers straight to
9725/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
9726/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
9727/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
9728/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of
9729/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) --
9730/// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE).
9731fn dump_stage16(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf, fw: usize, fh: usize) {
9732 use std::io::Write;
9733 // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by
9734 // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed
9735 // `.f0` name kept only the LAST frame, so a mid-sequence divergence could
9736 // not be read out at all.
9737 if let Ok(path) = std::env::var(var)
9738 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
9739 {
9740 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))] {
9741 for row in 0..h {
9742 let mut bytes = Vec::with_capacity(w * 2);
9743 for &s in &p.data[row * p.width..][..w] {
9744 bytes.extend_from_slice(&s.to_le_bytes());
9745 }
9746 let _ = f.write_all(&bytes);
9747 }
9748 }
9749 }
9750}
9751
9752/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a
9753/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so
9754/// every frame overwrote the previous one and only the LAST frame survived,
9755/// which silently defeats any per-frame filter-stage bisection.
9756fn dump_stage_idx(var: &str) -> usize {
9757 use std::collections::HashMap;
9758 use std::sync::{Mutex, OnceLock};
9759 static IDX: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new();
9760 let mut m = IDX.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap();
9761 let e = m.entry(var.to_string()).or_insert(0);
9762 let i = *e;
9763 *e += 1;
9764 i
9765}
9766
9767fn dump_stage(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf) {
9768 use std::io::Write;
9769 if let Ok(path) = std::env::var(var)
9770 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
9771 {
9772 for p in [y, u, v] {
9773 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
9774 let _ = f.write_all(&narrow);
9775 }
9776 }
9777}
9778
9779#[derive(Clone)]
9780struct PlaneBuf {
9781 data: Vec<u16>,
9782 width: usize,
9783 height: usize,
9784 /// The frame's true, decodable extent in this plane's own units — past
9785 /// this, samples are the padded coding surface's invented tail, never a
9786 /// real decoder's edge or reach reads.
9787 true_width: usize,
9788 true_height: usize,
9789 /// This plane's own tile's top-left pixel origin (spec: intra prediction
9790 /// never reaches across a tile boundary even though an earlier-decoded
9791 /// tile's real pixels sit right there in the shared buffer) — set via
9792 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
9793 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
9794 /// is threaded (the two-tile column-split stage 1 fixture's tile always
9795 /// ends at the frame's own right/bottom edge); a non-last tile's own
9796 /// right/bottom reach bound is still open, tracked in the report.
9797 tile_x0: usize,
9798 tile_y0: usize,
9799 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
9800 /// (exclusive) -- a non-last tile column/row's own reach must stop at
9801 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
9802 /// full padded extent) for the single-tile/last-tile case, matching the
9803 /// old unclipped behaviour exactly.
9804 tile_x1: usize,
9805 tile_y1: usize,
9806}
9807
9808/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
9809/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
9810/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
9811/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
9812/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
9813/// `ALTREF2`/`ALTREF`).
9814type RefSlots<'a> = [Option<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)>; 8];
9815
9816impl PlaneBuf {
9817 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
9818 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
9819 /// are already in this plane's own units (luma pixels for `y`, chroma
9820 /// pixels — halved — for `u`/`v`).
9821 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
9822 self.tile_x0 = x0;
9823 self.tile_y0 = y0;
9824 self.tile_x1 = x1;
9825 self.tile_y1 = y1;
9826 }
9827
9828 fn edges(
9829 &self,
9830 x: usize,
9831 y: usize,
9832 side: usize,
9833 reach: Reach,
9834 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
9835 let own_across = x + side.min(self.true_width.saturating_sub(x));
9836 let across = if reach.above_right {
9837 own_across + side.min(self.true_width.saturating_sub(own_across))
9838 } else {
9839 own_across
9840 }
9841 .min(self.width)
9842 .min(self.tile_x1);
9843 let own_down = y + side.min(self.true_height.saturating_sub(y));
9844 let down = if reach.below_left {
9845 own_down + side.min(self.true_height.saturating_sub(own_down))
9846 } else {
9847 own_down
9848 }
9849 .min(self.height)
9850 .min(self.tile_y1);
9851 let above = (y > self.tile_y0 && across > x)
9852 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
9853 let left = (x > self.tile_x0 && down > y).then(|| {
9854 (y..down)
9855 .map(|row| self.data[row * self.width + x - 1])
9856 .collect::<Vec<_>>()
9857 });
9858 let corner =
9859 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
9860 (above, left, corner)
9861 }
9862
9863 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
9864 /// the above/left reach each extend by their OWN axis (`bw` across,
9865 /// `bh` down), not one shared `side`.
9866 fn edges_rect(
9867 &self,
9868 x: usize,
9869 y: usize,
9870 bw: usize,
9871 bh: usize,
9872 reach: Reach,
9873 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
9874 let own_across = x + bw.min(self.true_width.saturating_sub(x));
9875 let across = if reach.above_right {
9876 own_across + bw.min(self.true_width.saturating_sub(own_across))
9877 } else {
9878 own_across
9879 }
9880 .min(self.width)
9881 .min(self.tile_x1);
9882 let own_down = y + bh.min(self.true_height.saturating_sub(y));
9883 let down = if reach.below_left {
9884 own_down + bh.min(self.true_height.saturating_sub(own_down))
9885 } else {
9886 own_down
9887 }
9888 .min(self.height)
9889 .min(self.tile_y1);
9890 let above = (y > self.tile_y0 && across > x)
9891 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
9892 let left = (x > self.tile_x0 && down > y).then(|| {
9893 (y..down)
9894 .map(|row| self.data[row * self.width + x - 1])
9895 .collect::<Vec<_>>()
9896 });
9897 let corner =
9898 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
9899 if matches!((bw, bh), (16, 8) | (8, 16)) {
9900 RECT_STRIP_PRED_HITS.with(|h| h.set(h.get() + 1));
9901 if across > own_across || down > own_down {
9902 RECT_STRIP_REACH_HITS.with(|h| h.set(h.get() + 1));
9903 }
9904 }
9905 (above, left, corner)
9906 }
9907
9908 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
9909 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
9910 /// already-rect-capable `(bw, bh)` pair.
9911 #[allow(clippy::too_many_arguments)]
9912 #[track_caller]
9913 fn reconstruct_rect(
9914 &mut self,
9915 x: usize,
9916 y: usize,
9917 bw: usize,
9918 bh: usize,
9919 mode: usize,
9920 angle_delta: i32,
9921 reach: Reach,
9922 residual: &[i32],
9923 cfl: Option<(i32, &[i32])>,
9924 filter_intra: Option<usize>,
9925 smooth_neighbor: bool,
9926 ) {
9927 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
9928 // (lane-palette2 r4): a palette block's prediction is the
9929 // reconstructed colour-index map, needing no edge pixels at all.
9930 let prediction = if let Some(buf) = take_palette_pred() {
9931 buf
9932 } else {
9933 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
9934 if std::env::var_os("EC_DEBUG_EDGES").is_some() {
9935 eprintln!(
9936 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
9937 above.as_ref().map(|a| (a.len(), a[0])),
9938 left.as_ref().map(|l| l.len()),
9939 left.as_ref().map(|l| l[0]),
9940 self.tile_x0, self.tile_y0, self.true_width, self.true_height
9941 );
9942 }
9943 let mut prediction = vec![0u16; bw * bh];
9944 if let Some(fi_mode) = filter_intra {
9945 crate::intra::predict_filter_intra(
9946 fi_mode,
9947 above.as_deref(),
9948 left.as_deref(),
9949 corner,
9950 bw,
9951 bh,
9952 &mut prediction,
9953 );
9954 } else {
9955 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
9956 predict(
9957 mode as u8,
9958 angle_delta,
9959 above.as_deref(),
9960 left.as_deref(),
9961 corner,
9962 bw,
9963 bh,
9964 enable_edge_filter,
9965 smooth_neighbor,
9966 &mut prediction,
9967 );
9968 }
9969 prediction
9970 };
9971 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
9972 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
9973 if std::env::var_os("EC_PRED").is_some() {
9974 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
9975 let row0: Vec<u16> = prediction[..bw.min(8)].to_vec();
9976 let col0: Vec<u16> = (0..bh.min(8)).map(|r| prediction[r * bw]).collect();
9977 eprintln!(
9978 "@{} OUR_PRED x={x} y={y} bw={bw} bh={bh} mode={mode} ad={angle_delta} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller()
9979 );
9980 }
9981 for row in 0..bh {
9982 for col in 0..bw {
9983 let idx = row * bw + col;
9984 let mut base = i32::from(prediction[idx]);
9985 if let Some((alpha_q3, ac_q3)) = cfl {
9986 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max());
9987 }
9988 let sample = (base + residual[idx]).clamp(0, sample_max()) as u16;
9989 self.data[(y + row) * self.width + x + col] = sample;
9990 }
9991 }
9992 }
9993
9994 /// Predicts under `mode` then adds `residual` (side*side, raster),
9995 /// writing the clamped reconstruction back into the plane at `(x, y)`.
9996 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
9997 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
9998 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
9999 /// order (cfl.c).
10000 #[track_caller]
10001 fn reconstruct(
10002 &mut self,
10003 x: usize,
10004 y: usize,
10005 side: usize,
10006 mode: usize,
10007 angle_delta: i32,
10008 reach: Reach,
10009 residual: &[i32],
10010 cfl: Option<(i32, &[i32])>,
10011 filter_intra: Option<usize>,
10012 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
10013 // libaom `get_filt_type`): true when the block's above OR left
10014 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
10015 // Callers pass their own plane's neighbour-mode check
10016 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
10017 // callers until a smooth/paeth `uv_mode` can reach this call at all
10018 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
10019 // keeps `false` exact for chroma without this fn needing to know why.
10020 smooth_neighbor: bool,
10021 ) {
10022 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
10023 // takes priority over `predict()`/`predict_filter_intra` entirely --
10024 // palette prediction needs no edge pixels at all.
10025 let prediction = if let Some(buf) = take_palette_pred() {
10026 buf
10027 } else {
10028 let (above, left, corner) = self.edges(x, y, side, reach);
10029 let mut prediction = vec![0u16; side * side];
10030 if let Some(fi_mode) = filter_intra {
10031 crate::intra::predict_filter_intra(
10032 fi_mode,
10033 above.as_deref(),
10034 left.as_deref(),
10035 corner,
10036 side,
10037 side,
10038 &mut prediction,
10039 );
10040 } else {
10041 // `enable_intra_edge_filter` is the sequence header's own flag
10042 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
10043 // call, never per-block) -- threading it through every
10044 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
10045 // dozen sites for a value that never changes mid-decode, so it
10046 // rides a thread-local instead (this decoder is single-threaded
10047 // per stream).
10048 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
10049 predict(
10050 mode as u8,
10051 angle_delta,
10052 above.as_deref(),
10053 left.as_deref(),
10054 corner,
10055 side,
10056 side,
10057 enable_edge_filter,
10058 smooth_neighbor,
10059 &mut prediction,
10060 );
10061 }
10062 prediction
10063 };
10064 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
10065 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
10066 if std::env::var_os("EC_PRED").is_some() {
10067 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
10068 let row0: Vec<u16> = prediction[..side.min(8)].to_vec();
10069 let col0: Vec<u16> = (0..side.min(8)).map(|r| prediction[r * side]).collect();
10070 eprintln!(
10071 "@{} OUR_PRED x={x} y={y} side={side} side={side} mode={mode} ad={angle_delta} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller()
10072 );
10073 }
10074 for row in 0..side {
10075 for col in 0..side {
10076 let idx = row * side + col;
10077 let mut base = i32::from(prediction[idx]);
10078 if let Some((alpha_q3, ac_q3)) = cfl {
10079 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max());
10080 }
10081 let sample = (base + residual[idx]).clamp(0, sample_max()) as u16;
10082 self.data[(y + row) * self.width + x + col] = sample;
10083 }
10084 }
10085 }
10086}
10087
10088/// Reads one plane's transform block, reconstructs it into `plane` at
10089/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
10090#[allow(clippy::too_many_arguments)]
10091fn read_plane(
10092 dec: &mut SymbolDecoder,
10093 cdfs: &mut Cdfs,
10094 set: TxbSet,
10095 scan: &[u16],
10096 plane_idx: usize,
10097 around: (bool, bool, i32),
10098 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
10099 // it for every plane's `txb` lookup (it is what an intra transform type's
10100 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
10101 tx_mode: usize,
10102 predict_mode: usize,
10103 angle_delta: i32,
10104 reach: Reach,
10105 plane: &mut PlaneBuf,
10106 x: usize,
10107 y: usize,
10108 side: usize,
10109 tx_side: usize,
10110 base_q_idx: u8,
10111 cfl: Option<(i32, &[i32])>,
10112 filter_intra: Option<usize>,
10113 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
10114 // smaller than its own block (spec `get_txb_ctx_general`'s
10115 // `plane_bsize != tx_size` branch), carrying the already-looked-up
10116 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
10117 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
10118 // formula below.
10119 luma_skip_ctx: Option<usize>,
10120 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
10121 smooth_neighbor: bool,
10122) -> Result<Vec<i32>> {
10123 let skip_ctx = if plane_idx == 0 {
10124 luma_skip_ctx.unwrap_or(0)
10125 } else {
10126 // libaom `get_txb_ctx`: a chroma unit's context is
10127 // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the
10128 // plane block is bigger than the transform. Our chroma tables hold the
10129 // offset-7 rows first, so the caller adds 3 for the bigger-block case
10130 // (only a 128x128 block's TX_32X32 chroma units, lane-sb128b r3).
10131 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
10132 };
10133 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
10134 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
10135 // not by the block's ordinary `mode` (which is always DC_PRED whenever
10136 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
10137 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
10138 // filter-intra in AV1).
10139 let tx_mode = if plane_idx == 0 { fi_tx_row(tx_mode, filter_intra) } else { tx_mode };
10140 let mut coding = cdfs.txb(set, tx_mode);
10141 // Luma's `default_tx_type` is only a fallback for the sizes whose
10142 // `TxbSet` carries no symbol at all (32-point and up), which the spec
10143 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
10144 // *never* its own coded symbol (`coding.tx_type` is always `None` for
10145 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
10146 // the plane's own predicted mode (`default_intra_tx_type`) -- except
10147 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
10148 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
10149 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
10150 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
10151 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
10152 // narrows there — only `Chroma32` and up do).
10153 let default_tx_type = if plane_idx == 0 || side >= 32 {
10154 TxType::DctDct
10155 } else {
10156 default_intra_tx_type(predict_mode as u8)
10157 };
10158 let (grid, tx_type) = read_coeffs(
10159 dec,
10160 &mut coding,
10161 scan,
10162 skip_ctx,
10163 dc_sign_ctx(around.2),
10164 default_tx_type,
10165 None,
10166 )?;
10167 note_chroma_class1(plane_idx, tx_type);
10168 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
10169 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
10170 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
10171 // guard also assumes.
10172 let levels = if tx_side == side {
10173 grid
10174 } else {
10175 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
10176 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
10177 // keyed by that true size, not the coded corner's -- so the corner
10178 // goes into the top-left of a `side`-sized grid, not the reverse.
10179 let mut full = vec![0i32; side * side];
10180 for row in 0..tx_side {
10181 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
10182 }
10183 full
10184 };
10185 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
10186 let residual = dequant_and_inverse_typed(&levels, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type);
10187 if std::env::var_os("EC_AV1_TRACE").is_some() {
10188 eprintln!(
10189 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={levels:?} residual={residual:?}",
10190 );
10191 }
10192 plane.reconstruct(
10193 x,
10194 y,
10195 side,
10196 predict_mode,
10197 angle_delta,
10198 reach,
10199 &residual,
10200 cfl,
10201 filter_intra,
10202 smooth_neighbor,
10203 );
10204 Ok(if tx_side == side {
10205 residual_grid_placeholder(&levels, side)
10206 } else {
10207 levels
10208 })
10209}
10210
10211/// `record`'s neighbour state only reads whether *the coded grid* (not the
10212/// residual) has nonzero entries, so the levels this function already built
10213/// are what it wants back; this helper exists only to name that clearly at
10214/// the one call site where `tx_side == side`.
10215fn residual_grid_placeholder(levels: &[i32], _tx_side: usize) -> Vec<i32> {
10216 levels.to_vec()
10217}
10218
10219/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
10220/// three planes, reconstructing them into `y`/`u`/`v` and updating
10221/// `neighbours`.
10222#[allow(clippy::too_many_arguments)]
10223fn decode_block(
10224 dec: &mut SymbolDecoder,
10225 cdfs: &mut Cdfs,
10226 neighbours: &mut Neighbours,
10227 at: (usize, usize),
10228 side: usize,
10229 luma_set: TxbSet,
10230 chroma_set: TxbSet,
10231 luma_tx: usize,
10232 chroma_tx: usize,
10233 scans: (&[u16], &[u16]),
10234 cfl: bool,
10235 y: &mut PlaneBuf,
10236 u: &mut PlaneBuf,
10237 v: &mut PlaneBuf,
10238 base_q_idx: u8,
10239 enable_filter_intra: bool,
10240 allow_screen_content_tools: bool,
10241 allow_intrabc: bool,
10242 scan32: &[u16],
10243 scan16: &[u16],
10244 scan8: &[u16],
10245 scan4: &[u16],
10246 tx_select: bool,
10247 reduced_tx_set: bool,
10248) -> Result<()> {
10249 let (r, c) = at;
10250 let (px, py) = (c * SUB, r * SUB);
10251 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
10252 let palette_uv_cache = neighbours.palette_uv_cache(at);
10253 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
10254 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
10255 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
10256 read_intra_mode(
10257 dec,
10258 cdfs,
10259 nb_above_mode,
10260 nb_left_mode,
10261 cfl,
10262 side,
10263 enable_filter_intra,
10264 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
10265 allow_screen_content_tools,
10266 allow_intrabc,
10267 Some((palette_ctx, &palette_cache)),
10268 &palette_uv_cache,
10269 r * (SUB / MI),
10270 c * (SUB / MI),
10271 )?;
10272 if at_tile_left && palette_y.is_some() {
10273 PALETTE_TILE_LEFT_HITS.with(|c| c.set(c.get() + 1));
10274 }
10275 let intrabc_dv = INTRABC_DV.with(|c| c.take());
10276 // libaom `parse_decode_block`: an intrabc block is `inter_block_tx`, so
10277 // under `TX_MODE_SELECT` its transform size comes from the inter var-tx
10278 // partition tree (`read_var_tx_size`), a syntax element this decoder has
10279 // nowhere -- reading the intra `tx_depth` symbol instead would desync.
10280 if intrabc_dv.is_some() && tx_select && !skip {
10281 return Err(unsupported(
10282 "an intrabc block under TxMode::Select (its transform size is coded by the inter var-tx partition tree, which this decoder never reads)",
10283 ));
10284 }
10285 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
10286 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
10287 // actual chroma-from-luma correlation, same as this decoder always did.
10288 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
10289 DC_PRED
10290 } else {
10291 uv_mode
10292 };
10293 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
10294 if smooth_neighbor {
10295 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
10296 }
10297 let smooth_neighbor_uv =
10298 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
10299 if std::env::var_os("EC_AV1_TRACE").is_some() {
10300 eprintln!(
10301 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
10302 angle_delta_uv={angle_delta_uv}"
10303 );
10304 }
10305 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
10306 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
10307 // block, skipped or not. `logical_tx` is what the loop filter's edge
10308 // lookup and the next block's own `tx_size_context` want (the *nominal*
10309 // transform size -- 64 even for the 64x64 corner-scanned case, spec
10310 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
10311 // which only differs from it at that one corner case.
10312 let (logical_tx, coeff_tx_side) = if tx_select {
10313 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, None);
10314 (resolved, if resolved == 64 { 32 } else { resolved })
10315 } else {
10316 // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is
10317 // TX_64X64, so a 128x128 block is always FOUR luma transform units
10318 // even with `tx_select` off -- the TU loop below, never the
10319 // single-unit path.
10320 (side.min(64), luma_tx)
10321 };
10322 if tx_select && logical_tx < side && uv_mode != DC_PRED {
10323 SQ_CHROMA_TX_HITS.with(|c| c.set(c.get() + 1));
10324 }
10325 let luma_set = if tx_select {
10326 txbset_for(logical_tx, reduced_tx_set)
10327 } else {
10328 luma_set
10329 };
10330 let luma_set = if intrabc_dv.is_some() {
10331 txbset_for_inter(logical_tx, reduced_tx_set)
10332 } else {
10333 luma_set
10334 };
10335 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
10336 let reach = Reach::of(side, px, py, y.width, y.height);
10337 let (cpx, cpy) = (px / 2, py / 2);
10338 let chroma_side = side / 2;
10339 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
10340 // frame's own pre-loop-filter reconstruction (all loop filters are off
10341 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
10342 // block vector, with the BILINEAR kernel libaom forces for intrabc --
10343 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
10344 // odd, which is exactly what the bilinear taps then interpolate.
10345 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
10346 let mut yb = vec![0u16; side * side];
10347 mc::predict_with_filter(
10348 &y.data, y.width, y.true_width, y.true_height,
10349 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
10350 side, side, mc::InterpFilterKind::Bilinear, &mut yb,
10351 );
10352 let mut ub = vec![0u16; chroma_side * chroma_side];
10353 mc::predict_with_filter(
10354 &u.data, u.width, u.true_width, u.true_height,
10355 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
10356 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut ub,
10357 );
10358 let mut vb = vec![0u16; chroma_side * chroma_side];
10359 mc::predict_with_filter(
10360 &v.data, v.width, v.true_width, v.true_height,
10361 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
10362 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut vb,
10363 );
10364 (yb, ub, vb)
10365 });
10366 if let Some((yb, _, _)) = &intrabc_bufs {
10367 set_palette_pred(yb.clone());
10368 }
10369 // A palette-Y block's own prediction is the reconstructed colour-index
10370 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
10371 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
10372 // parameter through this function's dozen `y.reconstruct`/`read_plane`
10373 // sites. A split luma transform (`tx_select && logical_tx != side`)
10374 // would need the map sliced per-TU -- untested against a real
10375 // `--enable-palette=1` stream this round, so refuse by name rather than
10376 // guess at the slicing (charter's own named-acceptable fallback).
10377 let palette_y_buf: Option<Vec<u16>> = palette_y.as_ref().map(|py| {
10378 py.map
10379 .iter()
10380 .map(|&idx| py.colors[idx as usize])
10381 .collect()
10382 });
10383 // With one luma transform unit the whole `side`x`side` map is the
10384 // prediction; with several (`logical_tx != side`) each unit takes its own
10385 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
10386 // below (lane-palette2 r7) -- setting the full-block buffer here would be
10387 // taken by the FIRST unit and indexed at the wrong stride.
10388 if let Some(buf) = &palette_y_buf
10389 && logical_tx == side
10390 {
10391 set_palette_pred(buf.clone());
10392 }
10393 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
10394 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
10395 // plane's own `reconstruct`/`read_plane` call below (never both planes at
10396 // once), since Y's own set-then-take already emptied the slot by the time
10397 // either of these run.
10398 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
10399 (
10400 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
10401 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
10402 )
10403 });
10404 // The chroma half of the intrabc prediction rides the same per-plane
10405 // override slot the UV-palette buffers do (set fresh before each plane's
10406 // own `reconstruct`/`read_plane` call below).
10407 let palette_uv_bufs = match &intrabc_bufs {
10408 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
10409 None => palette_uv_bufs,
10410 };
10411 if skip {
10412 // A skipped block codes no residual syntax at all (spec 5.11.34):
10413 // straight prediction, on every plane.
10414 //
10415 // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it
10416 // is skipped (only an INTER skip forces the largest transform), and
10417 // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts
10418 // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units
10419 // already written left/above of it inside this same block. Predicting
10420 // the whole `side`x`side` at once gives a different (uniformly off by
10421 // ~1) answer, which is exactly the residue this lane was chasing.
10422 // The palette/intrabc override path keeps the single-call shape (its
10423 // per-TU windowing is the non-skip loop's own `palette_y_buf` slice,
10424 // untested for skip and unreachable in these streams).
10425 // lane-sb128b r2: a 128x128 block's transform is TX_64X64 even with
10426 // `tx_select` off (`max_txsize_rect_lookup[BLOCK_128X128]`), so the
10427 // per-unit prediction is keyed on the transform being smaller than
10428 // the block, not on the tx-depth syntax. The counter keeps lane-hgkf's
10429 // narrower meaning (a READ split tx depth).
10430 let split_tx_skip =
10431 logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none();
10432 if split_tx_skip {
10433 if tx_select {
10434 SKIP_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
10435 }
10436 let n_axis = side / logical_tx;
10437 for tu_row in 0..n_axis {
10438 for tu_col in 0..n_axis {
10439 let tu_px = px + tu_col * logical_tx;
10440 let tu_py = py + tu_row * logical_tx;
10441 if tu_px >= y.true_width || tu_py >= y.true_height {
10442 continue;
10443 }
10444 let tu_reach = tu_reach(
10445 side,
10446 side,
10447 tu_col * logical_tx,
10448 tu_row * logical_tx,
10449 logical_tx,
10450 reach,
10451 px,
10452 py,
10453 y.width,
10454 y.height,
10455 );
10456 y.reconstruct(
10457 tu_px,
10458 tu_py,
10459 logical_tx,
10460 mode,
10461 angle_delta_y,
10462 tu_reach,
10463 &vec![0i32; logical_tx * logical_tx],
10464 None,
10465 filter_intra,
10466 smooth_neighbor,
10467 );
10468 }
10469 }
10470 } else {
10471 y.reconstruct(
10472 px,
10473 py,
10474 side,
10475 mode,
10476 angle_delta_y,
10477 reach,
10478 &vec![0i32; side * side],
10479 None,
10480 filter_intra,
10481 smooth_neighbor,
10482 );
10483 }
10484 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
10485 let cn = (chroma_side / chroma_tx).max(1);
10486 for cu_row in 0..cn {
10487 for cu_col in 0..cn {
10488 let luma_span = chroma_tx * 2;
10489 let cu_r = if cn == 1 {
10490 reach
10491 } else {
10492 tu_reach(
10493 side, side,
10494 cu_col * luma_span, cu_row * luma_span, luma_span,
10495 reach, px, py, y.width, y.height,
10496 )
10497 };
10498 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
10499 if let Some((ub, _)) = &palette_uv_bufs {
10500 set_palette_pred(ub.clone());
10501 }
10502 u.reconstruct(
10503 cu_x,
10504 cu_y,
10505 chroma_tx,
10506 uv_predict_mode,
10507 angle_delta_uv,
10508 cu_r,
10509 &vec![0i32; chroma_tx * chroma_tx],
10510 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
10511 None,
10512 smooth_neighbor_uv,
10513 );
10514 if let Some((_, vb)) = &palette_uv_bufs {
10515 set_palette_pred(vb.clone());
10516 }
10517 v.reconstruct(
10518 cu_x,
10519 cu_y,
10520 chroma_tx,
10521 uv_predict_mode,
10522 angle_delta_uv,
10523 cu_r,
10524 &vec![0i32; chroma_tx * chroma_tx],
10525 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
10526 None,
10527 smooth_neighbor_uv,
10528 );
10529 }
10530 }
10531 let luma_grid = vec![0i32; side * side];
10532 let u_grid = vec![0i32; chroma_side * chroma_side];
10533 let v_grid = vec![0i32; chroma_side * chroma_side];
10534 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
10535 } else if logical_tx == side {
10536 // lane-sb128b r1: the test used to be `!tx_select || logical_tx == side`.
10537 // Without `tx_select` `logical_tx` IS `side` at every size <= 64, so
10538 // that arm was redundant -- and wrong at 128, where
10539 // `max_txsize_rect_lookup` caps the block's transform at 64 and the
10540 // block is four units whether or not `tx_select` is on.
10541 // A single luma transform unit -- the old path, unchanged (including
10542 // the 64x64 corner case, `logical_tx == side == 64` with
10543 // `coeff_tx_side == 32`).
10544 let around = neighbours.around(at, side);
10545 let luma_grid = read_plane(
10546 dec,
10547 cdfs,
10548 luma_set,
10549 luma_scan,
10550 0,
10551 around[0],
10552 mode,
10553 mode,
10554 angle_delta_y,
10555 reach,
10556 y,
10557 px,
10558 py,
10559 side,
10560 coeff_tx_side,
10561 base_q_idx,
10562 None,
10563 filter_intra,
10564 None,
10565 smooth_neighbor,
10566 )?;
10567 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
10568 if let Some((ub, _)) = &palette_uv_bufs {
10569 set_palette_pred(ub.clone());
10570 }
10571 let u_grid = read_plane(
10572 dec,
10573 cdfs,
10574 chroma_set,
10575 scans.1,
10576 1,
10577 around[1],
10578 mode,
10579 uv_predict_mode,
10580 angle_delta_uv,
10581 reach,
10582 u,
10583 cpx,
10584 cpy,
10585 chroma_side,
10586 chroma_tx,
10587 base_q_idx,
10588 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
10589 None,
10590 None,
10591 smooth_neighbor_uv,
10592 )?;
10593 if std::env::var_os("EC_AV1_TRACE").is_some() {
10594 eprintln!(
10595 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
10596 &u.data[cpy * u.width + cpx..][..chroma_side]
10597 );
10598 }
10599 if let Some((_, vb)) = &palette_uv_bufs {
10600 set_palette_pred(vb.clone());
10601 }
10602 let v_grid = read_plane(
10603 dec,
10604 cdfs,
10605 chroma_set,
10606 scans.1,
10607 2,
10608 around[2],
10609 mode,
10610 uv_predict_mode,
10611 angle_delta_uv,
10612 reach,
10613 v,
10614 cpx,
10615 cpy,
10616 chroma_side,
10617 chroma_tx,
10618 base_q_idx,
10619 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
10620 None,
10621 None,
10622 smooth_neighbor_uv,
10623 )?;
10624 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
10625 } else {
10626 // Several luma transform units, raster order (spec
10627 // `transform_block`'s loop): the block's resolved transform is
10628 // genuinely smaller than its own side, so each tile of it predicts
10629 // and codes independently, its own context read fresh off whatever
10630 // the earlier tiles in this same block already wrote -- the same
10631 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
10632 let n_axis = side / logical_tx;
10633 let cn = (chroma_side / chroma_tx).max(1);
10634 // libaom's transform-block loop is over 64x64 luma "mu" chunks
10635 // (`decode_token_recon_block`: `mu_blocks_wide/high` =
10636 // `mi_size_wide[BLOCK_64X64]`), and it codes EVERY PLANE of a chunk
10637 // before moving to the next one. Below 128 a block is a single chunk,
10638 // so this is byte-for-byte the all-luma-then-all-chroma order that has
10639 // always run; at 128 the four quadrants interleave Y,U,V per quadrant
10640 // and reading all four luma units first desyncs the tile at the second
10641 // one (lane-sb128b r3, measured against aomdec's `EC_TRACE_COEFF`).
10642 let nchunk = (side / 64).max(1);
10643 // `cn > 1` means the uv plane block is larger than the uv transform,
10644 // which moves libaom's chroma `txb_skip_ctx` offset from 7 to 10.
10645 let chroma_ctx_offset = if cn > 1 { Some(3) } else { None };
10646 let tpc = (n_axis / nchunk).max(1);
10647 let cpc = (cn / nchunk).max(1);
10648 let mut last_grids = [Vec::new(), Vec::new()];
10649 let mut units: Vec<((usize, usize), usize, Vec<i32>, Vec<i32>)> = Vec::new();
10650 for ch_row in 0..nchunk {
10651 for ch_col in 0..nchunk {
10652 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
10653 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
10654 let tu_mi = (
10655 mi_r + tu_row * (logical_tx / MI),
10656 mi_c + tu_col * (logical_tx / MI),
10657 );
10658 let tu_px = px + tu_col * logical_tx;
10659 let tu_py = py + tu_row * logical_tx;
10660 // Same libaom clip as `decode_rect_split`'s loop above; a
10661 // square block only hangs off the frame when the frame's mi
10662 // dimensions are odd at the block's own level.
10663 if tu_px >= y.true_width || tu_py >= y.true_height {
10664 continue;
10665 }
10666 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
10667 // A transform unit inside a block is NOT a block at that
10668 // position (lane-palette2 r12): `Reach::of` granted the
10669 // top-right 8x8 unit of a 16x16 D203 block bottom-left
10670 // pixels libaom refuses outright (`col_off > 0`), which is
10671 // the diagonal wedge seed 46 reconstructed wrong.
10672 let tu_reach = tu_reach(
10673 side,
10674 side,
10675 tu_col * logical_tx,
10676 tu_row * logical_tx,
10677 logical_tx,
10678 reach,
10679 px,
10680 py,
10681 y.width,
10682 y.height,
10683 );
10684 // This transform unit's own bsize (`logical_tx`) is smaller
10685 // than the block it sits in (`side`), so `txb_skip_ctx` is
10686 // the neighbour-magnitude table, not the lone-TU 0 (spec
10687 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
10688 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
10689 if let Some(buf) = &palette_y_buf {
10690 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
10691 let mut window = vec![0u16; logical_tx * logical_tx];
10692 for row in 0..logical_tx {
10693 let src = (tu_row * logical_tx + row) * side + tu_col * logical_tx;
10694 window[row * logical_tx..][..logical_tx]
10695 .copy_from_slice(&buf[src..][..logical_tx]);
10696 }
10697 set_palette_pred(window);
10698 }
10699 let tu_grid = read_plane(
10700 dec,
10701 cdfs,
10702 luma_set,
10703 luma_scan,
10704 0,
10705 tu_around,
10706 mode,
10707 mode,
10708 angle_delta_y,
10709 tu_reach,
10710 y,
10711 tu_px,
10712 tu_py,
10713 logical_tx,
10714 // The unit's own COEFFICIENT grid, half its side at
10715 // TX_64X64 (a 64-point transform codes nothing past 32);
10716 // identical to `logical_tx` at every smaller size
10717 // (lane-sb128b r1).
10718 coeff_tx_side,
10719 base_q_idx,
10720 None,
10721 filter_intra,
10722 Some(tu_skip_ctx),
10723 smooth_neighbor,
10724 )?;
10725 if std::env::var_os("EC_AV1_TRACE").is_some() {
10726 eprintln!(
10727 "TRACE tu_bitpos mi=({},{}) tell={}",
10728 tu_mi.0,
10729 tu_mi.1,
10730 dec.debug_bitpos()
10731 );
10732 }
10733 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
10734 }
10735 }
10736 // CfL is only allowed up to 32x32, i.e. only at `nchunk == 1`, where
10737 // this still runs after every luma unit of the block.
10738 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
10739 // The block's uv plane block is `chroma_side` across but its uv
10740 // transform is `chroma_tx` (`av1_get_max_uv_txsize` =
10741 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[uv_plane_bsize])`):
10742 // identical at every size up to 64x64, but a 128x128 block's 64x64 uv
10743 // plane block adjusts TX_64X64 down to TX_32X32, so each plane is
10744 // FOUR units (lane-sb128b r2) -- one per mu chunk.
10745 for cu_row in ch_row * cpc..(ch_row + 1) * cpc {
10746 for cu_col in ch_col * cpc..(ch_col + 1) * cpc {
10747 // The chroma context arrays are indexed in LUMA mi, so this
10748 // unit's anchor is its own luma quadrant: `chroma_tx` chroma
10749 // pixels span `2 * chroma_tx` luma ones.
10750 let luma_span = chroma_tx * 2;
10751 let cu_mi = (
10752 mi_r + cu_row * (luma_span / MI),
10753 mi_c + cu_col * (luma_span / MI),
10754 );
10755 let cu_around = neighbours.around_mi(cu_mi, luma_span);
10756 let cu_reach = if cn == 1 {
10757 reach
10758 } else {
10759 tu_reach(
10760 side, side,
10761 cu_col * luma_span, cu_row * luma_span, luma_span,
10762 reach, px, py, y.width, y.height,
10763 )
10764 };
10765 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
10766 if let Some((ub, _)) = &palette_uv_bufs {
10767 set_palette_pred(ub.clone());
10768 }
10769 let u_grid = read_plane(
10770 dec, cdfs, chroma_set, scans.1, 1, cu_around[1], mode,
10771 uv_predict_mode, angle_delta_uv, cu_reach, u, cu_x, cu_y,
10772 chroma_tx, chroma_tx, base_q_idx,
10773 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
10774 None, chroma_ctx_offset, smooth_neighbor_uv,
10775 )?;
10776 if let Some((_, vb)) = &palette_uv_bufs {
10777 set_palette_pred(vb.clone());
10778 }
10779 let v_grid = read_plane(
10780 dec, cdfs, chroma_set, scans.1, 2, cu_around[2], mode,
10781 uv_predict_mode, angle_delta_uv, cu_reach, v, cu_x, cu_y,
10782 chroma_tx, chroma_tx, base_q_idx,
10783 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
10784 None, chroma_ctx_offset, smooth_neighbor_uv,
10785 )?;
10786 if cn > 1 {
10787 CHROMA_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
10788 // Immediately, so the NEXT unit of this same block reads
10789 // this one's coefficient context (libaom's chroma
10790 // `txb_skip_ctx` for the second quadrant is 11, i.e. base
10791 // 1 from this left neighbour -- measured against aomdec).
10792 // The same writes are replayed after `record_split_luma`
10793 // below, which would otherwise clobber them whole-block.
10794 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 1, &u_grid);
10795 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 2, &v_grid);
10796 units.push((cu_mi, luma_span, u_grid.clone(), v_grid.clone()));
10797 }
10798 last_grids = [u_grid, v_grid];
10799 }
10800 }
10801 }
10802 }
10803 // Mode/side bookkeeping plus, at `cn == 1`, the whole-plane chroma
10804 // context write; at `cn > 1` the per-unit writes above are what the
10805 // next block reads, so they run after this (last writer wins).
10806 neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&last_grids[0], &last_grids[1]]);
10807 for (cu_mi, luma_span, u_grid, v_grid) in &units {
10808 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 1, u_grid);
10809 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 2, v_grid);
10810 }
10811 }
10812 // Unconditional, `size == 0` for a non-palette block: clears any stale
10813 // neighbour palette state the same way [`Neighbours::record`] always
10814 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
10815 // (the split-luma-TU branch above always refuses before reaching here
10816 // when `palette_y` is `Some`, so it is never live for that branch).
10817 let (py_size, py_colors) = palette_y
10818 .as_ref()
10819 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
10820 neighbours.record_palette_y(at, side, py_size, py_colors);
10821 let (puv_size, puv_colors) = palette_uv
10822 .as_ref()
10823 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
10824 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
10825 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
10826 neighbours.fill_lf_grid(
10827 (r * (SUB / MI), c * (SUB / MI)),
10828 side / MI,
10829 logical_tx as u8,
10830 0,
10831 );
10832 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv);
10833 Ok(())
10834}
10835
10836/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
10837/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
10838/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
10839/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
10840/// just-decoded mode, not the enclosing slot's stale one, is the true
10841/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
10842/// units, which is what its coefficient context (finer than [`SUB`]) is read
10843/// at. Returns the mode this leaf decoded, for the caller's own
10844/// `prev_leaf`/final mode-writeback bookkeeping.
10845#[allow(clippy::too_many_arguments)]
10846/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
10847/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
10848/// `above_mode[col]`, and its true above neighbour is the mi directly above
10849/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
10850/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
10851/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
10852/// (bottom-right) into both, as this path did, is right only when all four
10853/// leaves happen to share a mode. `done` may be short at the true frame edge
10854/// (the straddle caller filters positions off the frame), so each side falls
10855/// back to the last leaf actually decoded.
10856fn write_back_split_modes(
10857 neighbours: &mut Neighbours,
10858 done: &[((usize, usize), usize)],
10859 parent_mi: (usize, usize),
10860 slot: (usize, usize),
10861) {
10862 let (sr, sc) = slot;
10863 let Some(&(_, last)) = done.last() else {
10864 return;
10865 };
10866 let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m);
10867 neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last);
10868 neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last);
10869}
10870
10871fn decode_leaf8(
10872 dec: &mut SymbolDecoder,
10873 cdfs: &mut Cdfs,
10874 neighbours: &mut Neighbours,
10875 outer_at: (usize, usize),
10876 leaf_mi: (usize, usize),
10877 scans: (&[u16], &[u16]),
10878 prev_leaf: Option<((usize, usize), usize)>,
10879 y: &mut PlaneBuf,
10880 u: &mut PlaneBuf,
10881 v: &mut PlaneBuf,
10882 base_q_idx: u8,
10883 enable_filter_intra: bool,
10884 allow_screen_content_tools: bool,
10885 allow_intrabc: bool,
10886 tx_select: bool,
10887 reduced_tx_set: bool,
10888) -> Result<usize> {
10889 let (r, c) = outer_at;
10890 // lane-modectx r1: the group's own availability-correct fallback pair, not
10891 // the raw coarse bands (which leak across a tile edge -- see
10892 // `modes_above_left`).
10893 let (mut above_mode, mut left_mode) = neighbours.modes_above_left(r, c);
10894 if let Some(((pr, pc), pmode)) = prev_leaf {
10895 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
10896 above_mode = pmode;
10897 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
10898 left_mode = pmode;
10899 }
10900 }
10901 // The mi-exact neighbour wins over both the coarse 16x16 slot and
10902 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
10903 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
10904 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
10905 // lane-rectsplitx r2 swept this arm into
10906 // [`Neighbours::modes_above_left_mi`]: the mi-exact map ALSO has to answer
10907 // "no neighbour" at a tile edge, where the coarse cell holds the block
10908 // above/left of it inside the same 16x16.
10909 let (above_mode, left_mode) =
10910 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
10911 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
10912 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
10913 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
10914 // this leaf's `smooth_neighbor` is built from -- passing `false` here
10915 // filtered a directional chroma block's edge at the wrong strength
10916 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
10917 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
10918 // with the coarse [`SUB`] slot as the fallback when no block recorded
10919 // that exact mi cell.
10920 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
10921 if smooth_neighbor {
10922 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
10923 }
10924 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
10925 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
10926 // `decode_block` caller at 16x16 and up.
10927 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, _palette_y, _palette_uv) =
10928 read_intra_mode(
10929 dec,
10930 cdfs,
10931 above_mode,
10932 left_mode,
10933 true,
10934 8,
10935 enable_filter_intra,
10936 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
10937 allow_screen_content_tools,
10938 allow_intrabc,
10939 None,
10940 &[],
10941 leaf_mi.0,
10942 leaf_mi.1,
10943 )?;
10944 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
10945 DC_PRED
10946 } else {
10947 uv_mode
10948 };
10949 neighbours.above_uv_mode[c] = uv_predict_mode;
10950 neighbours.left_uv_mode[r] = uv_predict_mode;
10951 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
10952 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
10953 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
10954 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
10955 // transform units, same raster-order per-TU pattern `decode_block`'s
10956 // multi-TU branch runs).
10957 let resolved = if tx_select {
10958 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, None)
10959 } else {
10960 8
10961 };
10962 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
10963 let reach = Reach::of(8, px, py, y.width, y.height);
10964 let (cpx, cpy) = (px / 2, py / 2);
10965 let (luma_grid, u_grid, v_grid);
10966 if skip {
10967 // lane-hgkf r2 (same shape as `decode_block`'s own skip branch): an
10968 // 8x8 leaf whose `tx_depth` resolved to TX_4X4 predicts FOUR 4x4
10969 // transform units, each off the units already written left/above of
10970 // it inside this same leaf -- an intra block's transform size is read
10971 // whether or not it is skipped, and spec 7.11.2 predicts per unit.
10972 if resolved == 4 {
10973 SKIP_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
10974 for tu_row in 0..2 {
10975 for tu_col in 0..2 {
10976 let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4);
10977 if tu_px >= y.true_width || tu_py >= y.true_height {
10978 continue;
10979 }
10980 let tu_reach = tu_reach(
10981 8,
10982 8,
10983 tu_col * 4,
10984 tu_row * 4,
10985 4,
10986 reach,
10987 px,
10988 py,
10989 y.width,
10990 y.height,
10991 );
10992 y.reconstruct(
10993 tu_px,
10994 tu_py,
10995 4,
10996 mode,
10997 angle_delta_y,
10998 tu_reach,
10999 &vec![0i32; 16],
11000 None,
11001 filter_intra,
11002 smooth_neighbor,
11003 );
11004 }
11005 }
11006 } else {
11007 y.reconstruct(
11008 px,
11009 py,
11010 8,
11011 mode,
11012 angle_delta_y,
11013 reach,
11014 &vec![0i32; 64],
11015 None,
11016 filter_intra,
11017 smooth_neighbor,
11018 );
11019 }
11020 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
11021 u.reconstruct(
11022 cpx,
11023 cpy,
11024 4,
11025 uv_predict_mode,
11026 angle_delta_uv,
11027 reach,
11028 &vec![0i32; 16],
11029 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
11030 None,
11031 smooth_neighbor_uv,
11032 );
11033 v.reconstruct(
11034 cpx,
11035 cpy,
11036 4,
11037 uv_predict_mode,
11038 angle_delta_uv,
11039 reach,
11040 &vec![0i32; 16],
11041 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
11042 None,
11043 smooth_neighbor_uv,
11044 );
11045 luma_grid = vec![0i32; 64];
11046 u_grid = vec![0i32; 16];
11047 v_grid = vec![0i32; 16];
11048 } else if resolved != 4 {
11049 let around = neighbours.around_mi(leaf_mi, 8);
11050 luma_grid = read_plane(
11051 dec,
11052 cdfs,
11053 if reduced_tx_set {
11054 TxbSet::Luma8
11055 } else {
11056 TxbSet::Luma8Set1
11057 },
11058 scans.0,
11059 0,
11060 around[0],
11061 mode,
11062 mode,
11063 angle_delta_y,
11064 reach,
11065 y,
11066 px,
11067 py,
11068 8,
11069 TX8,
11070 base_q_idx,
11071 None,
11072 filter_intra,
11073 None,
11074 smooth_neighbor,
11075 )?;
11076 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
11077 u_grid = read_plane(
11078 dec,
11079 cdfs,
11080 TxbSet::Chroma4,
11081 scans.1,
11082 1,
11083 around[1],
11084 mode,
11085 uv_predict_mode,
11086 angle_delta_uv,
11087 reach,
11088 u,
11089 cpx,
11090 cpy,
11091 4,
11092 TX4,
11093 base_q_idx,
11094 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
11095 None,
11096 None,
11097 smooth_neighbor_uv,
11098 )?;
11099 v_grid = read_plane(
11100 dec,
11101 cdfs,
11102 TxbSet::Chroma4,
11103 scans.1,
11104 2,
11105 around[2],
11106 mode,
11107 uv_predict_mode,
11108 angle_delta_uv,
11109 reach,
11110 v,
11111 cpx,
11112 cpy,
11113 4,
11114 TX4,
11115 base_q_idx,
11116 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
11117 None,
11118 None,
11119 smooth_neighbor_uv,
11120 )?;
11121 } else {
11122 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
11123 // grid of 4x4 transform units, each predicted from the leaf's own
11124 // 8x8 `mode` and reading its own fresh context off the earlier
11125 // units in this same leaf (the same per-TU pattern `decode_block`'s
11126 // multi-TU branch runs at bigger blocks).
11127 luma_grid = vec![0i32; 64];
11128 for tu_row in 0..2 {
11129 for tu_col in 0..2 {
11130 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
11131 let tu_px = px + tu_col * 4;
11132 let tu_py = py + tu_row * 4;
11133 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
11134 if crate::encode::Reach::in_vert_ab() {
11135 VERT_AB_TX4_HITS.with(|c| c.set(c.get() + 1));
11136 }
11137 let tu_reach = tu_reach(
11138 8,
11139 8,
11140 tu_col * 4,
11141 tu_row * 4,
11142 4,
11143 reach,
11144 px,
11145 py,
11146 y.width,
11147 y.height,
11148 );
11149 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
11150 let tu_grid = read_plane(
11151 dec,
11152 cdfs,
11153 if reduced_tx_set {
11154 TxbSet::Luma4
11155 } else {
11156 TxbSet::Luma4Set1
11157 },
11158 scans.1,
11159 0,
11160 tu_around,
11161 mode,
11162 mode,
11163 angle_delta_y,
11164 tu_reach,
11165 y,
11166 tu_px,
11167 tu_py,
11168 4,
11169 4,
11170 base_q_idx,
11171 None,
11172 filter_intra,
11173 Some(tu_skip_ctx),
11174 smooth_neighbor,
11175 )?;
11176 if std::env::var_os("EC_AV1_TRACE").is_some() {
11177 eprintln!(
11178 "TRACE tu_bitpos mi=({},{}) tell={}",
11179 tu_mi.0,
11180 tu_mi.1,
11181 dec.debug_bitpos()
11182 );
11183 }
11184 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
11185 }
11186 }
11187 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
11188 let chroma_around = neighbours.around_mi(leaf_mi, 8);
11189 u_grid = read_plane(
11190 dec,
11191 cdfs,
11192 TxbSet::Chroma4,
11193 scans.1,
11194 1,
11195 chroma_around[1],
11196 mode,
11197 uv_predict_mode,
11198 angle_delta_uv,
11199 reach,
11200 u,
11201 cpx,
11202 cpy,
11203 4,
11204 TX4,
11205 base_q_idx,
11206 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
11207 None,
11208 None,
11209 smooth_neighbor_uv,
11210 )?;
11211 v_grid = read_plane(
11212 dec,
11213 cdfs,
11214 TxbSet::Chroma4,
11215 scans.1,
11216 2,
11217 chroma_around[2],
11218 mode,
11219 uv_predict_mode,
11220 angle_delta_uv,
11221 reach,
11222 v,
11223 cpx,
11224 cpy,
11225 4,
11226 TX4,
11227 base_q_idx,
11228 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
11229 None,
11230 None,
11231 smooth_neighbor_uv,
11232 )?;
11233 // `record_split_luma` expects a `record`-style `(r, c)` position in
11234 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
11235 // already in mi units, so calling it here double-scaled the
11236 // position. Plane 0 is already correct per-TU from the
11237 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
11238 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
11239 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
11240 // leaf's own 8x8 side over `MI`).
11241 let side_mi = 2;
11242 for cell in 0..side_mi {
11243 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
11244 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
11245 }
11246 let round_up_even = |n: usize| n.div_ceil(2) * 2;
11247 let bound_h = round_up_even(neighbours.mi_rows);
11248 let bound_w = round_up_even(neighbours.mi_cols);
11249 let u_state = neighbour_state(&u_grid);
11250 let v_state = neighbour_state(&v_grid);
11251 for cell in 0..side_mi {
11252 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
11253 neighbours.left[leaf_mi.0 + cell][1] = u_state;
11254 neighbours.left[leaf_mi.0 + cell][2] = v_state;
11255 }
11256 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
11257 neighbours.above[leaf_mi.1 + cell][1] = u_state;
11258 neighbours.above[leaf_mi.1 + cell][2] = v_state;
11259 }
11260 }
11261 // Non-palette 8x8 leaf (this path never reads a palette): clear the
11262 // above/left palette state over its own cell so the next block's ctx and
11263 // colour cache do not read a previous block's palette (lane-palette2 r8).
11264 {
11265 let pal_at = (leaf_mi.0 / (SUB / MI), leaf_mi.1 / (SUB / MI));
11266 neighbours.record_palette_y_rect(pal_at, 8, 8, 0, [0u16; 8]);
11267 neighbours.record_palette_uv_rect(pal_at, 8, 8, 0, [0u16; 8]);
11268 }
11269 neighbours.fill_skip_grid(leaf_mi, 2, skip);
11270 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0);
11271 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
11272 return Ok(mode);
11273 }
11274 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
11275 // Non-palette 8x8 leaf (this path never reads a palette): clear the
11276 // above/left palette state over its own cell so the next block's ctx and
11277 // colour cache do not read a previous block's palette (lane-palette2 r8).
11278 {
11279 let pal_at = (leaf_mi.0 / (SUB / MI), leaf_mi.1 / (SUB / MI));
11280 neighbours.record_palette_y_rect(pal_at, 8, 8, 0, [0u16; 8]);
11281 neighbours.record_palette_uv_rect(pal_at, 8, 8, 0, [0u16; 8]);
11282 }
11283 INTER8_SKIP_BAND_HITS.with(|c| c.set(c.get() + 1));
11284 neighbours.fill_skip_grid(leaf_mi, 2, skip);
11285 // lane-kf900 r1: the leaf's own RESOLVED transform size, never the literal
11286 // block side. libaom calls `set_txfm_ctxs(mbmi->tx_size, ..., skip_txfm &&
11287 // is_inter_block(mbmi), xd)` (decodemv.c) -- for an INTRA block that skip
11288 // term is always 0, so a skipped 8x8 leaf whose `tx_depth` resolved to
11289 // TX_4X4 still publishes 4 to the next block's `get_tx_size_context`
11290 // (pred_common.h:342). Writing 8 here made the 8x16 strip below the leaf
11291 // read `tx_size_cat1` row 2 where libaom reads row 1 -- same alphabet,
11292 // wrong CDF row, so the msac range diverged mid-frame with no refusal
11293 // (class `wrong-alphabet-same-value`; the ReelB key frame at
11294 // -ss 900, first bad luma sample row 186 col 1803).
11295 neighbours.fill_lf_grid(leaf_mi, 2, resolved as u8, 0);
11296 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
11297 Ok(mode)
11298}
11299
11300/// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf
11301/// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8`
11302/// bottom, where no partition symbol is read at all -- `decode_block` runs
11303/// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec
11304/// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always
11305/// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference`
11306/// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf
11307/// of the 2x2 4x4 group carries chroma syntax at all.
11308#[allow(clippy::too_many_arguments)]
11309fn read_intra_mode_sub8(
11310 dec: &mut SymbolDecoder,
11311 cdfs: &mut Cdfs,
11312 above_mode: usize,
11313 left_mode: usize,
11314 has_chroma: bool,
11315 enable_filter_intra: bool,
11316 // [`filter_intra_size_class_rect`] for the LEAF's own shape: 0 for a
11317 // `BLOCK_4X4` split leaf, 8/9 for a 4x8/8x4 rect leaf. Reading the flag
11318 // from the wrong row is the same VALUE with a different interval, so it
11319 // desyncs a block or two later, not here (class `wrong-alphabet-same-value`).
11320 fi_class: usize,
11321 skip_ctx: usize,
11322 allow_intrabc: bool,
11323 mi_r: usize,
11324 mi_c: usize,
11325) -> Result<(bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option<usize>)> {
11326 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
11327 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
11328 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sub8 rng={}", dec.debug_state().0);
11329 }
11330 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
11331 if trace {
11332 eprintln!("TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}", skip as i32, dec.debug_state().0);
11333 }
11334 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
11335 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip);
11336 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip);
11337 if allow_intrabc {
11338 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
11339 if use_intrabc {
11340 return Err(unsupported(
11341 "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)",
11342 ));
11343 }
11344 }
11345 let above_ctx = INTRA_MODE_CTX[above_mode];
11346 let left_ctx = INTRA_MODE_CTX[left_mode];
11347 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
11348 if trace {
11349 eprintln!("TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
11350 }
11351 // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/
11352 // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`,
11353 // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta
11354 // symbol. Reading one consumed a symbol the encoder never wrote and
11355 // desynced the tile at the very next element.
11356 let angle_delta_y = 0;
11357 let chroma = if has_chroma {
11358 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
11359 if trace {
11360 eprintln!("TRACE sub8 uv_mode value={uv_mode} rng={}", dec.debug_state().0);
11361 }
11362 if (9..=12).contains(&uv_mode) {
11363 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
11364 }
11365 let alpha = if uv_mode == UV_CFL_PRED {
11366 Some(read_cfl_alphas(dec, cdfs))
11367 } else {
11368 None
11369 };
11370 if (V_PRED..=D67_PRED).contains(&uv_mode) {
11371 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
11372 }
11373 // See the luma comment above: no angle delta below 8x8.
11374 let angle_delta_uv = 0;
11375 Some((uv_mode, angle_delta_uv, alpha))
11376 } else {
11377 None
11378 };
11379 let mut filter_intra = None;
11380 if mode == DC_PRED && enable_filter_intra {
11381 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0;
11382 if trace {
11383 eprintln!("TRACE sub8 use_filter_intra value={}", use_filter_intra as i32);
11384 }
11385 if use_filter_intra {
11386 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
11387 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
11388 filter_intra = Some(fi_mode);
11389 }
11390 }
11391 Ok((skip, mode, angle_delta_y, chroma, filter_intra))
11392}
11393
11394/// Decodes a `PARTITION_SPLIT` of one 8x8 block into four `BLOCK_4X4` leaves
11395/// (spec `decode_partition`'s recursion bottom), sharing [`decode_leaf8`]'s
11396/// own signature so its caller's `prev_leaf`/`above_mode`/`left_mode`
11397/// bookkeeping needs no change. Each leaf reads its own luma mode info,
11398/// neighboured off the *previously decoded leaf in this same group* on
11399/// whichever axis is adjacent (mirroring [`decode_leaf8`]'s own `prev_leaf`
11400/// pattern, one level deeper); chroma is read and reconstructed exactly
11401/// once, on the last (bottom-right) leaf, at the whole 8x8 group's own 4x4
11402/// chroma unit -- [`read_intra_mode_sub8`]'s doc has the `is_chroma_reference`
11403/// derivation.
11404#[allow(clippy::too_many_arguments)]
11405fn decode_leaf_split4(
11406 dec: &mut SymbolDecoder,
11407 cdfs: &mut Cdfs,
11408 neighbours: &mut Neighbours,
11409 outer_at: (usize, usize),
11410 leaf_mi: (usize, usize),
11411 scan4: &[u16],
11412 prev_leaf: Option<((usize, usize), usize)>,
11413 y: &mut PlaneBuf,
11414 u: &mut PlaneBuf,
11415 v: &mut PlaneBuf,
11416 base_q_idx: u8,
11417 enable_filter_intra: bool,
11418 allow_intrabc: bool,
11419 reduced_tx_set: bool,
11420 // Returns `(below_mode, right_mode)`: the mode a neighbour BELOW this 8x8
11421 // group sees (its bottom-left 4x4, libaom reads mi(row-1, col)) and the
11422 // one a neighbour to its RIGHT sees (its top-right 4x4, mi(row, col-1)).
11423) -> Result<(usize, usize)> {
11424 SUB8_SPLIT_HITS.with(|c| c.set(c.get() + 1));
11425 let (r, c) = outer_at;
11426 let mut above_mode = neighbours.above_mode[c];
11427 let mut left_mode = neighbours.left_mode[r];
11428 if let Some(((pr, pc), pmode)) = prev_leaf {
11429 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
11430 above_mode = pmode;
11431 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
11432 left_mode = pmode;
11433 }
11434 }
11435 // See `decode_leaf8`'s own `smooth_neighbor_uv`: the chroma edge-filter
11436 // type is the chroma neighbours' `uv_mode`, mi-exact where recorded.
11437 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
11438 let mut leaf_modes = [0usize; 4];
11439 let mut leaf_skips = [false; 4];
11440 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
11441 for i in 0..4usize {
11442 let (dr, dc) = (i / 2, i % 2);
11443 let lmi = (leaf_mi.0 + dr, leaf_mi.1 + dc);
11444 // Neighbour modes at real mi granularity: inside the group the
11445 // sibling leaf, outside it the split-leaf map when the adjacent mi
11446 // was itself a 4x4 leaf, else the coarse 16x16 slot (see
11447 // `sub8_mode_col`'s doc).
11448 let leaf_above = if dr == 0 {
11449 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
11450 } else {
11451 leaf_modes[i - 2]
11452 };
11453 let leaf_left = if dc == 0 {
11454 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
11455 } else {
11456 leaf_modes[i - 1]
11457 };
11458 let has_chroma = i == 3;
11459 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
11460 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
11461 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
11462 filter_intra_size_class(4).expect("BLOCK_4X4 has its own filter_intra row"),
11463 skip_ctx, allow_intrabc, lmi.0, lmi.1,
11464 )?;
11465 leaf_modes[i] = mode;
11466 leaf_skips[i] = skip;
11467 neighbours.record_mode_mi(lmi.0, lmi.1, 1, 1, mode);
11468 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
11469 if smooth_neighbor {
11470 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
11471 }
11472 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
11473 let reach = Reach::of(4, px, py, y.width, y.height);
11474 if skip {
11475 y.reconstruct(px, py, 4, mode, angle_delta_y, reach, &vec![0i32; 16], None, filter_intra, smooth_neighbor);
11476 neighbours.record_mi_luma(lmi, 4, &vec![0i32; 16]);
11477 } else {
11478 let tu_around = neighbours.around_mi(lmi, 4)[0];
11479 // A `BLOCK_4X4` leaf's luma TU *is* the whole block, so libaom's
11480 // `get_txb_ctx` takes its `plane_bsize == txsize_to_bsize[tx_size]`
11481 // branch: `txb_skip_ctx = 0`, never the neighbour-magnitude table
11482 // (`txb_common.h:400`). Reading the table here decoded `all_zero`
11483 // off the wrong CDF on the very first leaf and desynced the tile.
11484 let tu_grid = read_plane(
11485 dec,
11486 cdfs,
11487 if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 },
11488 scan4,
11489 0,
11490 tu_around,
11491 mode,
11492 mode,
11493 angle_delta_y,
11494 reach,
11495 y,
11496 px,
11497 py,
11498 4,
11499 4,
11500 base_q_idx,
11501 None,
11502 filter_intra,
11503 None,
11504 smooth_neighbor,
11505 )?;
11506 neighbours.record_mi_luma(lmi, 4, &tu_grid);
11507 }
11508 neighbours.fill_skip_grid(lmi, 1, skip);
11509 neighbours.fill_lf_grid(lmi, 1, 4, 0);
11510 if has_chroma {
11511 last_uv = chroma;
11512 }
11513 }
11514 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
11515 let (cpx, cpy) = (gpx / 2, gpy / 2);
11516 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height);
11517 let (uv_mode, angle_delta_uv, alpha) =
11518 last_uv.expect("i==3 always sets has_chroma, so chroma is always Some");
11519 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
11520 neighbours.above_uv_mode[c] = uv_predict_mode;
11521 neighbours.left_uv_mode[r] = uv_predict_mode;
11522 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
11523 let (u_grid, v_grid): (Vec<i32>, Vec<i32>) = if leaf_skips[3] {
11524 // A skipped chroma block still gets its CfL contribution: libaom's
11525 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
11526 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
11527 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
11528 // added -- `skip_txfm` only drops the residual, never the alpha.
11529 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
11530 // merge keeps one fix and feeds both lanes' counters so neither of
11531 // their gates goes vacuous.
11532 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
11533 if alpha.is_some() {
11534 CHROMA_SKIP_CFL_HITS.with(|h| h.set(h.get() + 1));
11535 SKIP_CFL_HITS.with(|c| c.set(c.get() + 1));
11536 }
11537 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);
11538 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);
11539 (vec![0i32; 16], vec![0i32; 16])
11540 } else {
11541 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
11542 let chroma_around = neighbours.around_mi(leaf_mi, 8);
11543 let ug = read_plane(
11544 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
11545 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
11546 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv,
11547 )?;
11548 let vg = read_plane(
11549 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
11550 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
11551 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv,
11552 )?;
11553 (ug, vg)
11554 };
11555 // Chroma neighbour bookkeeping for the whole 8x8 group -- mirrors
11556 // [`decode_leaf8`]'s own tx4-chroma section (`record_split_luma`'s
11557 // rescaling is wrong for an already-mi-unit position, so this inlines
11558 // its tail directly at `leaf_mi`, side_mi=2), EXCEPT for the partition
11559 // context value itself. Unlike `decode_leaf8`'s TX4 branch (still one
11560 // `BLOCK_8X8`, `PARTITION_NONE`, transform depth only), this group is
11561 // genuinely four `BLOCK_4X4` blocks (`PARTITION_SPLIT` at the 8x8
11562 // level, libaom `decode_partition`'s `bsize2`/`subsize` recursion
11563 // bottom). libaom's `update_ext_partition_context` writes
11564 // `partition_context_lookup[subsize]` at the 8x8 slot -- `{30,30}` for
11565 // `BLOCK_8X8` (bit0=0, what `decode_leaf8` already reproduces via
11566 // side_mi=8) but `{31,31}` for `BLOCK_4X4` (bit0=1) here, and
11567 // `partition_ctx_mi`'s `left_side_mi[mi_r]*2 <= side` needs
11568 // `left_side_mi <= 4` to read that bit as 1. Leaving this at 8 (this
11569 // round's bug) makes the very next sibling 8x8's `partition_w8` read
11570 // with the wrong context and desync immediately.
11571 let side_mi = 2;
11572 for cell in 0..side_mi {
11573 neighbours.left_side_mi[leaf_mi.0 + cell] = 4;
11574 neighbours.above_side_mi[leaf_mi.1 + cell] = 4;
11575 }
11576 let round_up_even = |n: usize| n.div_ceil(2) * 2;
11577 let bound_h = round_up_even(neighbours.mi_rows);
11578 let bound_w = round_up_even(neighbours.mi_cols);
11579 let u_state = neighbour_state(&u_grid);
11580 let v_state = neighbour_state(&v_grid);
11581 for cell in 0..side_mi {
11582 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
11583 neighbours.left[leaf_mi.0 + cell][1] = u_state;
11584 neighbours.left[leaf_mi.0 + cell][2] = v_state;
11585 }
11586 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
11587 neighbours.above[leaf_mi.1 + cell][1] = u_state;
11588 neighbours.above[leaf_mi.1 + cell][2] = v_state;
11589 }
11590 }
11591 Ok((leaf_modes[2], leaf_modes[1]))
11592}
11593
11594/// Decodes a `PARTITION_VERT`/`PARTITION_HORZ` of one 8x8 block into two
11595/// `BLOCK_4X8`/`BLOCK_8X4` leaves (lane-tx4x8), the last partition shape
11596/// below 8x8 this decoder refused. Mirrors [`decode_leaf_split4`] element for
11597/// element -- same mode reads ([`read_intra_mode_sub8`]: no angle delta, no
11598/// tx-depth symbol below 8x8), same "chroma once, on the last sub-block, at
11599/// the whole 8x8 group's 4x4 unit" rule (`is_chroma_reference` is false for
11600/// every sub-block one mi wide or high but the last) -- differing only where
11601/// the shape does:
11602///
11603/// * the transform is a true `TX_4X8`/`TX_8X4`
11604/// ([`dequant_and_inverse_typed_wh`], whose `abs(rect_type) == 1` scale and
11605/// `av1_inv_txfm_shift_ls` row already cover this size pair);
11606/// * the CDF set is [`TxbSet::LumaRect4x8`] (`get_txsize_entropy_ctx` squares
11607/// up to `TX_8X8`) with a 32-position `eob_pt` and the `TX_4X4` `tx_type`
11608/// row -- see that variant's doc comment;
11609/// * the scan is [`SCAN_4X8`]/[`SCAN_8X4`], or their `mrow`/`mcol` siblings
11610/// ([`class_scan_table_wh`]) when the coded `tx_type` is `V_DCT`/`H_DCT`;
11611/// * `Reach` comes from libaom's own `has_tr_4x8`/`has_bl_8x4` rows
11612/// ([`Reach::of_rect`]);
11613/// * `update_partition_context` writes `partition_context_lookup[BLOCK_4X8]`
11614/// = `{31, 30}` (width 4 above, height 8 left), not the `{31, 31}` a
11615/// `BLOCK_4X4` split writes.
11616///
11617/// Filter intra on one of these leaves is decoded (lane-fi8 r1): the flag is
11618/// read from `BLOCK_4X8`/`BLOCK_8X4`'s own `cdf::FILTER_INTRA` row (classes
11619/// 8/9, NOT `BLOCK_4X4`'s), the predictor is [`crate::intra::predict_filter_intra`]
11620/// over the leaf's true `bw`x`bh` -- per 4x4 transform unit, with that unit's
11621/// own edge, when `tx_depth` splits it -- and the coded `tx_type` row is
11622/// [`fi_tx_row`]'s `fimode_to_intradir`, not the block's raw `DC_PRED`.
11623#[allow(clippy::too_many_arguments)]
11624fn decode_leaf_rect8(
11625 dec: &mut SymbolDecoder,
11626 cdfs: &mut Cdfs,
11627 neighbours: &mut Neighbours,
11628 outer_at: (usize, usize),
11629 leaf_mi: (usize, usize),
11630 vert: bool,
11631 scan4: &[u16],
11632 y: &mut PlaneBuf,
11633 u: &mut PlaneBuf,
11634 v: &mut PlaneBuf,
11635 base_q_idx: u8,
11636 enable_filter_intra: bool,
11637 allow_intrabc: bool,
11638 tx_select: bool,
11639 reduced_tx_set: bool,
11640) -> Result<(usize, usize)> {
11641 let (r, c) = outer_at;
11642 // lane-modectx r1: availability-correct fallback pair (see
11643 // `modes_above_left`), not the raw coarse bands.
11644 let (above_mode, left_mode) = neighbours.modes_above_left(r, c);
11645 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
11646 let (bw, bh) = if vert { (4, 8) } else { (8, 4) };
11647 let (w_mi, h_mi) = (bw / MI, bh / MI);
11648 let scan: &[u16] = if vert { &SCAN_4X8 } else { &SCAN_8X4 };
11649 let mut leaf_modes = [0usize; 2];
11650 let mut leaf_skips = [false; 2];
11651 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
11652 for i in 0..2usize {
11653 let lmi = if vert {
11654 (leaf_mi.0, leaf_mi.1 + i)
11655 } else {
11656 (leaf_mi.0 + i, leaf_mi.1)
11657 };
11658 // Inside the pair the sibling is the neighbour on the split axis;
11659 // outside it the mi-granular map, else the coarse 16x16 slot.
11660 let leaf_above = if !vert && i == 1 {
11661 leaf_modes[0]
11662 } else {
11663 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
11664 };
11665 let leaf_left = if vert && i == 1 {
11666 leaf_modes[0]
11667 } else {
11668 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
11669 };
11670 let has_chroma = i == 1;
11671 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
11672 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
11673 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
11674 filter_intra_size_class_rect(bw, bh)
11675 .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize"),
11676 skip_ctx, allow_intrabc, lmi.0, lmi.1,
11677 )?;
11678 if filter_intra.is_some() {
11679 // lane-fi8 r1: `predict_filter_intra` walks its 4x2 patches over
11680 // a true `bw`x`bh` block, so a 4x8/8x4 leaf predicts through the
11681 // same `reconstruct_rect`/`reconstruct` calls below -- and under
11682 // a split transform, per 4x4 unit with that unit's own edge,
11683 // which is exactly what the depth-1 loop already does.
11684 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
11685 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.set(c.get() + 1));
11686 }
11687 // `TxMode::Select`'s `tx_depth` (spec 5.11.16) exists at a 4x8/8x4
11688 // leaf too, and is read for every intra block, skipped or not. Its
11689 // category is libaom's `bsize_to_tx_size_cat(BLOCK_4X8) == 0` --
11690 // `sub_tx_size_map[TX_4X8] == TX_4X4` is a single step, so it is the
11691 // same 2-symbol `tx_size_cat0` an 8x8 uses, not the 3-symbol
11692 // `tx_size_cat2` the 32x16 strips read -- with the rect context
11693 // (`get_tx_size_context`'s `max_tx_wide`/`max_tx_high` = bw/bh).
11694 // Missing this read consumed one symbol fewer than the encoder wrote
11695 // and desynced the tile at the very first rect leaf (class
11696 // `symbol-consumption-gap`).
11697 let depth = if tx_select {
11698 let ctx = tx_size_context_rect(neighbours, lmi, bw, bh);
11699 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
11700 } else {
11701 0
11702 };
11703 if depth != 0 {
11704 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
11705 RECT8_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
11706 }
11707 leaf_modes[i] = mode;
11708 leaf_skips[i] = skip;
11709 neighbours.record_mode_mi(lmi.0, lmi.1, w_mi, h_mi, mode);
11710 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
11711 if smooth_neighbor {
11712 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
11713 }
11714 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
11715 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
11716 // `sub_tx_size_map[TX_4X8] == TX_4X4`: depth 1 splits the leaf into
11717 // two 4x4 transform units along its long axis, each predicted from
11718 // the previous unit's reconstruction and reading its own `txb_skip`
11719 // context -- `decode_leaf8`'s own depth-1 loop, two units instead of
11720 // four. The per-TU path writes its own neighbour state, so the
11721 // block-level write below is skipped for it.
11722 let split = depth != 0;
11723 if split {
11724 let mut done = 0usize;
11725 for tu in 0..2usize {
11726 let tu_mi = if vert {
11727 (lmi.0 + tu, lmi.1)
11728 } else {
11729 (lmi.0, lmi.1 + tu)
11730 };
11731 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);
11732 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
11733 // Same per-TU rule as every other split-transform site
11734 // (lane-palette2 r12): a transform unit inside a block is not
11735 // a block at that position, so its reach comes from the
11736 // block's own row, offset by the unit's position.
11737 let tu_reach = tu_reach(
11738 bw,
11739 bh,
11740 tu_px - px,
11741 tu_py - py,
11742 4,
11743 reach,
11744 px,
11745 py,
11746 y.width,
11747 y.height,
11748 );
11749 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
11750 if skip {
11751 // A skipped leaf still predicts per transform unit: the
11752 // second 4x4 takes its above/left edge from the first
11753 // one's reconstruction, which is NOT what a single 4x8
11754 // prediction of the same mode produces.
11755 let zeros = vec![0i32; 16];
11756 y.reconstruct(
11757 tu_px, tu_py, 4, mode, angle_delta_y, tu_reach, &zeros, None,
11758 filter_intra, smooth_neighbor,
11759 );
11760 neighbours.record_mi_luma(tu_mi, 4, &zeros);
11761 continue;
11762 }
11763 let tu_grid = read_plane(
11764 dec,
11765 cdfs,
11766 if reduced_tx_set {
11767 TxbSet::Luma4
11768 } else {
11769 TxbSet::Luma4Set1
11770 },
11771 scan4,
11772 0,
11773 tu_around,
11774 mode,
11775 mode,
11776 angle_delta_y,
11777 tu_reach,
11778 y,
11779 tu_px,
11780 tu_py,
11781 4,
11782 TX4,
11783 base_q_idx,
11784 None,
11785 filter_intra,
11786 Some(tu_skip_ctx),
11787 smooth_neighbor,
11788 )?;
11789 if tu_grid.iter().any(|&l| l != 0) {
11790 done += 1;
11791 }
11792 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
11793 }
11794 if done > 0 {
11795 if vert {
11796 TX4X8_CODED_HITS.with(|h| h.set(h.get() + 1));
11797 } else {
11798 TX8X4_CODED_HITS.with(|h| h.set(h.get() + 1));
11799 }
11800 }
11801 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
11802 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, 4, 4, 0);
11803 if has_chroma {
11804 last_uv = chroma;
11805 }
11806 continue;
11807 }
11808 let grid = if skip {
11809 let zeros = vec![0i32; bw * bh];
11810 y.reconstruct_rect(
11811 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
11812 smooth_neighbor,
11813 );
11814 zeros
11815 } else {
11816 // `plane_bsize == txsize_to_bsize[tx_size]` here too (the leaf's
11817 // luma TU *is* the leaf), so `get_txb_ctx` fixes `txb_skip_ctx`
11818 // at 0 -- see `decode_leaf_split4`'s own note.
11819 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
11820 let set = if reduced_tx_set {
11821 TxbSet::LumaRect4x8
11822 } else {
11823 TxbSet::LumaRect4x8Set1
11824 };
11825 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
11826 let (levels, tx_type) = read_coeffs_rect(
11827 dec,
11828 &mut coding,
11829 scan,
11830 bw,
11831 bh,
11832 0,
11833 dc_sign_ctx(around.2),
11834 TxType::DctDct,
11835 )?;
11836 if levels.iter().any(|&l| l != 0) {
11837 if vert {
11838 TX4X8_CODED_HITS.with(|h| h.set(h.get() + 1));
11839 } else {
11840 TX8X4_CODED_HITS.with(|h| h.set(h.get() + 1));
11841 }
11842 }
11843 let residual = dequant_and_inverse_typed_wh(
11844 &levels,
11845 bw,
11846 bh,
11847 crate::decode::bit_depth(),
11848 CURRENT_Q_IDX.with(|q| q.get()),
11849 plane_q_delta(0).0,
11850 plane_q_delta(0).1,
11851 tx_type,
11852 );
11853 y.reconstruct_rect(
11854 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
11855 smooth_neighbor,
11856 );
11857 levels
11858 };
11859 // Plane 0's per-TU coefficient context over this leaf's own mi span
11860 // (`record_mi_luma`'s rect twin -- the chroma planes are written once
11861 // for the whole 8x8 group below).
11862 let state = neighbour_state(&grid);
11863 for cell in 0..h_mi {
11864 if lmi.0 + cell < neighbours.mi_rows {
11865 neighbours.left[lmi.0 + cell][0] = state;
11866 }
11867 }
11868 for cell in 0..w_mi {
11869 if lmi.1 + cell < neighbours.mi_cols {
11870 neighbours.above[lmi.1 + cell][0] = state;
11871 }
11872 }
11873 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
11874 let (tx_w, tx_h) = if split { (4, 4) } else { (bw as u8, bh as u8) };
11875 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, tx_w, tx_h, 0);
11876 if has_chroma {
11877 last_uv = chroma;
11878 }
11879 }
11880 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
11881 let (cpx, cpy) = (gpx / 2, gpy / 2);
11882 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height);
11883 let (uv_mode, angle_delta_uv, alpha) =
11884 last_uv.expect("i==1 always sets has_chroma, so chroma is always Some");
11885 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
11886 neighbours.above_uv_mode[c] = uv_predict_mode;
11887 neighbours.left_uv_mode[r] = uv_predict_mode;
11888 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
11889 let (u_grid, v_grid): (Vec<i32>, Vec<i32>) = if leaf_skips[1] {
11890 // A skipped chroma block still gets its CfL contribution: libaom's
11891 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
11892 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
11893 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
11894 // added -- `skip_txfm` only drops the residual, never the alpha.
11895 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
11896 // merge keeps one fix and feeds both lanes' counters so neither of
11897 // their gates goes vacuous.
11898 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
11899 if alpha.is_some() {
11900 CHROMA_SKIP_CFL_HITS.with(|h| h.set(h.get() + 1));
11901 SKIP_CFL_HITS.with(|c| c.set(c.get() + 1));
11902 }
11903 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);
11904 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);
11905 (vec![0i32; 16], vec![0i32; 16])
11906 } else {
11907 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
11908 let chroma_around = neighbours.around_mi(leaf_mi, 8);
11909 let ug = read_plane(
11910 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
11911 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
11912 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv,
11913 )?;
11914 let vg = read_plane(
11915 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
11916 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
11917 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv,
11918 )?;
11919 (ug, vg)
11920 };
11921 // `update_partition_context` at the 8x8 level writes
11922 // `partition_context_lookup[subsize]` over the whole 8x8 span: BLOCK_4X8
11923 // is `{31, 30}` (bit0 set on the above half only), BLOCK_8X4 `{30, 31}`
11924 // -- the mirror of `decode_leaf_split4`'s `{31, 31}`, which
11925 // `partition_ctx_mi` reads back off these side values.
11926 for cell in 0..2 {
11927 neighbours.above_side_mi[leaf_mi.1 + cell] = bw;
11928 neighbours.left_side_mi[leaf_mi.0 + cell] = bh;
11929 }
11930 let round_up_even = |n: usize| n.div_ceil(2) * 2;
11931 let bound_h = round_up_even(neighbours.mi_rows);
11932 let bound_w = round_up_even(neighbours.mi_cols);
11933 let u_state = neighbour_state(&u_grid);
11934 let v_state = neighbour_state(&v_grid);
11935 for cell in 0..2usize {
11936 if cell < 2usize.min(bound_h.saturating_sub(leaf_mi.0)) {
11937 neighbours.left[leaf_mi.0 + cell][1] = u_state;
11938 neighbours.left[leaf_mi.0 + cell][2] = v_state;
11939 }
11940 if cell < 2usize.min(bound_w.saturating_sub(leaf_mi.1)) {
11941 neighbours.above[leaf_mi.1 + cell][1] = u_state;
11942 neighbours.above[leaf_mi.1 + cell][2] = v_state;
11943 }
11944 }
11945 // `(below_mode, right_mode)`: the sub-block a neighbour below sees is the
11946 // bottom one (the second under HORZ, the left one under VERT), the one a
11947 // neighbour to the right sees is the top-right (the second under VERT).
11948 Ok(if vert {
11949 (leaf_modes[0], leaf_modes[1])
11950 } else {
11951 (leaf_modes[1], leaf_modes[0])
11952 })
11953}
11954
11955/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
11956/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
11957/// (mod 8) reuse the same table.
11958const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
11959 [(-1, 1), (-2, 2)],
11960 [(0, 1), (-1, 2)],
11961 [(0, 1), (0, 2)],
11962 [(0, 1), (1, 2)],
11963 [(1, 1), (2, 2)],
11964 [(1, 0), (2, 1)],
11965 [(1, 0), (2, 0)],
11966 [(1, 0), (2, -1)],
11967];
11968/// A neighbour tap outside the frame's true extent -- `constrain` reads this
11969/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
11970const CDEF_VERY_LARGE: i32 = 0x4000;
11971const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
11972const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
11973
11974fn cdef_msb(x: i32) -> i32 {
11975 31 - x.leading_zeros() as i32
11976}
11977
11978/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
11979/// centre sample a filter tap is allowed to contribute.
11980fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
11981 if threshold == 0 {
11982 return 0;
11983 }
11984 let shift = (damping - cdef_msb(threshold)).max(0);
11985 diff.signum() * (threshold - (diff.abs() >> shift)).clamp(0, diff.abs())
11986}
11987
11988/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
11989/// direction of an 8x8 luma window and the variance gap between it and its
11990/// orthogonal, `sample(row, col)` reading that window's own pixels.
11991fn cdef_find_dir(coeff_shift: i32, sample: impl Fn(usize, usize) -> i32) -> (usize, i32) {
11992 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
11993 let mut partial = [[0i64; 15]; 8];
11994 for i in 0..8i64 {
11995 for j in 0..8i64 {
11996 // libaom `cdef_find_dir_c`: normalise to an 8-bit sample before
11997 // accumulating, same as `constrain`'s threshold shift below.
11998 let x = i64::from(sample(i as usize, j as usize) >> coeff_shift) - 128;
11999 partial[0][(i + j) as usize] += x;
12000 partial[1][(i + j / 2) as usize] += x;
12001 partial[2][i as usize] += x;
12002 partial[3][(3 + i - j / 2) as usize] += x;
12003 partial[4][(7 + i - j) as usize] += x;
12004 partial[5][(3 - i / 2 + j) as usize] += x;
12005 partial[6][j as usize] += x;
12006 partial[7][(i / 2 + j) as usize] += x;
12007 }
12008 }
12009 let mut cost = [0i64; 8];
12010 for i in 0..8usize {
12011 cost[2] += partial[2][i] * partial[2][i];
12012 cost[6] += partial[6][i] * partial[6][i];
12013 }
12014 cost[2] *= DIV_TABLE[8];
12015 cost[6] *= DIV_TABLE[8];
12016 for i in 0..7usize {
12017 cost[0] += (partial[0][i] * partial[0][i] + partial[0][14 - i] * partial[0][14 - i])
12018 * DIV_TABLE[i + 1];
12019 cost[4] += (partial[4][i] * partial[4][i] + partial[4][14 - i] * partial[4][14 - i])
12020 * DIV_TABLE[i + 1];
12021 }
12022 cost[0] += partial[0][7] * partial[0][7] * DIV_TABLE[8];
12023 cost[4] += partial[4][7] * partial[4][7] * DIV_TABLE[8];
12024 for i in (1..8).step_by(2) {
12025 for j in 0..5usize {
12026 cost[i] += partial[i][3 + j] * partial[i][3 + j];
12027 }
12028 cost[i] *= DIV_TABLE[8];
12029 for j in 0..3usize {
12030 cost[i] += (partial[i][j] * partial[i][j] + partial[i][10 - j] * partial[i][10 - j])
12031 * DIV_TABLE[2 * j + 2];
12032 }
12033 }
12034 let mut best_cost = 0i64;
12035 let mut best_dir = 0usize;
12036 for (i, &c) in cost.iter().enumerate() {
12037 if c > best_cost {
12038 best_cost = c;
12039 best_dir = i;
12040 }
12041 }
12042 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
12043 (best_dir, var as i32)
12044}
12045
12046/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
12047/// (high variance gap) gets more deringing than a flat or non-directional
12048/// one, only ever applied to the luma primary strength.
12049fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
12050 if var == 0 {
12051 return 0;
12052 }
12053 let i = if var >> 6 != 0 {
12054 cdef_msb(var >> 6).min(12)
12055 } else {
12056 0
12057 };
12058 (strength * (4 + i) + 8) >> 4
12059}
12060
12061/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
12062/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
12063/// previously-filtered neighbour must never feed this block's own sum).
12064#[allow(clippy::too_many_arguments)]
12065fn cdef_filter_block(
12066 sample: impl Fn(i32, i32) -> i32,
12067 dst: &mut PlaneBuf,
12068 ox: usize,
12069 oy: usize,
12070 bw: usize,
12071 bh: usize,
12072 pri_strength: i32,
12073 sec_strength: i32,
12074 dir: usize,
12075 pri_damping: i32,
12076 sec_damping: i32,
12077 enable_primary: bool,
12078 enable_secondary: bool,
12079 coeff_shift: i32,
12080) {
12081 let clipping_required = enable_primary && enable_secondary;
12082 // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >>
12083 // coeff_shift) & 1]` -- `pri_strength` (and its `adjust_strength`
12084 // derivative) carries the bit-depth shift, so the tap-set parity bit
12085 // must be read back above that shift, not off the raw low bit.
12086 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
12087 for i in 0..bh {
12088 for j in 0..bw {
12089 let x = sample(i as i32, j as i32);
12090 let mut sum = 0i32;
12091 let mut max = x;
12092 let mut min = x;
12093 for k in 0..2usize {
12094 if enable_primary {
12095 let (tr, tc) = CDEF_DIRECTIONS[dir][k];
12096 let p0 = sample(i as i32 + tr, j as i32 + tc);
12097 let p1 = sample(i as i32 - tr, j as i32 - tc);
12098 sum += pri_taps[k] * cdef_constrain(p0 - x, pri_strength, pri_damping);
12099 sum += pri_taps[k] * cdef_constrain(p1 - x, pri_strength, pri_damping);
12100 if clipping_required {
12101 if p0 != CDEF_VERY_LARGE {
12102 max = max.max(p0);
12103 }
12104 if p1 != CDEF_VERY_LARGE {
12105 max = max.max(p1);
12106 }
12107 min = min.min(p0).min(p1);
12108 }
12109 }
12110 if enable_secondary {
12111 let (tr0, tc0) = CDEF_DIRECTIONS[(dir + 2) & 7][k];
12112 let (tr1, tc1) = CDEF_DIRECTIONS[(dir + 6) & 7][k];
12113 let s0 = sample(i as i32 + tr0, j as i32 + tc0);
12114 let s1 = sample(i as i32 - tr0, j as i32 - tc0);
12115 let s2 = sample(i as i32 + tr1, j as i32 + tc1);
12116 let s3 = sample(i as i32 - tr1, j as i32 - tc1);
12117 if clipping_required {
12118 for s in [s0, s1, s2, s3] {
12119 if s != CDEF_VERY_LARGE {
12120 max = max.max(s);
12121 }
12122 }
12123 min = min.min(s0).min(s1).min(s2).min(s3);
12124 }
12125 sum += CDEF_SEC_TAPS[k]
12126 * (cdef_constrain(s0 - x, sec_strength, sec_damping)
12127 + cdef_constrain(s1 - x, sec_strength, sec_damping)
12128 + cdef_constrain(s2 - x, sec_strength, sec_damping)
12129 + cdef_constrain(s3 - x, sec_strength, sec_damping));
12130 }
12131 }
12132 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
12133 if clipping_required {
12134 y = y.clamp(min, max);
12135 }
12136 dst.data[(oy + i) * dst.width + (ox + j)] = y.clamp(0, sample_max()) as u16;
12137 }
12138 }
12139}
12140
12141/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
12142/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
12143/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
12144/// every block's level comes from [`LoopFilterParams::level`] plus the
12145/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
12146/// `get_filter_level`, precomputed per-block here rather than cached in a
12147/// table the way libaom's `av1_loop_filter_frame_init` does).
12148///
12149/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
12150/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
12151fn apply_deblock(
12152 y: &mut PlaneBuf,
12153 u: &mut PlaneBuf,
12154 v: &mut PlaneBuf,
12155 lf: &LoopFilterParams,
12156 n: &Neighbours,
12157 frame_width: usize,
12158 frame_height: usize,
12159) {
12160 // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel
12161 // mismatch between the raw reconstruction and post-filter output.
12162 if std::env::var_os("EC_AV1_DEBUG_SKIP_DEBLOCK").is_some() {
12163 return;
12164 }
12165 // lane-mergefix r4 debug rung: frame-level loop filter parameters.
12166 if std::env::var_os("EC_LFPARAMS").is_some() {
12167 eprintln!(
12168 "EC_LFPARAMS level={:?} sharpness={} delta_enabled={} delta_update={} ref_deltas={:?} mode_deltas={:?}",
12169 lf.level, lf.sharpness, lf.delta_enabled, lf.delta_update, lf.ref_deltas, lf.mode_deltas
12170 );
12171 }
12172 if lf.level[0] != 0 || lf.level[1] != 0 {
12173 deblock_plane(y, 0, lf, n, frame_width, frame_height);
12174 }
12175 if lf.level[2] != 0 {
12176 deblock_plane(u, 1, lf, n, frame_width, frame_height);
12177 }
12178 if lf.level[3] != 0 {
12179 deblock_plane(v, 2, lf, n, frame_width, frame_height);
12180 }
12181}
12182
12183/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
12184/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
12185/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
12186/// mi unit under this decoder's assumed 4:2:0 subsampling).
12187fn plane_to_mi(chroma: bool, coord: usize) -> usize {
12188 if chroma { coord / 2 } else { coord / 4 }
12189}
12190
12191/// This plane's own transform width in pixels at the covering block, spec
12192/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
12193/// width directly; chroma halves it (this decoder's UV transform is always
12194/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
12195/// under 4:2:0 and a block that never splits its own transform).
12196fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
12197 let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid };
12198 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
12199}
12200
12201/// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
12202/// edges step and gate by transform height, which differs from width only
12203/// on rect partition strips.
12204fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
12205 let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid };
12206 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
12207}
12208
12209/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
12210/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
12211/// present only when its neighbour exists inside the true frame -- whether
12212/// the block immediately above (at this block's own leftmost mi column) or
12213/// to the left (at its own topmost mi row) coded a transform at least as wide
12214/// as `own_side`.
12215fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
12216 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side;
12217 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side;
12218 usize::from(above) + usize::from(left)
12219}
12220
12221/// `get_tx_size_context` as libaom actually writes it (`pred_common.h:342`),
12222/// for a block inside an INTER frame: the two `TXFM_CONTEXT` arrays
12223/// ([`Neighbours::above_txfm`]/[`Neighbours::left_txfm`], which only the
12224/// inter path maintains), except that an *inter* neighbour contributes its
12225/// own BLOCK size rather than its transform size -- the two differ the moment
12226/// a neighbour's var-tx tree splits. [`tx_size_context`]'s deblock-grid
12227/// approximation coincides with this only while every neighbour codes one
12228/// whole-block transform, which is exactly what `TxMode::Select` ends.
12229fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
12230 let has_above = mi_r > n.tile_row0_mi;
12231 let has_left = mi_c > n.tile_col0_mi;
12232 let mut above = usize::from(n.above_txfm[mi_c]) >= side;
12233 let mut left = usize::from(n.left_txfm[mi_r]) >= side;
12234 // lane-mergefix: `above_inter`/`left_inter` are written per mi
12235 // (`record_inter_rect_mi`), NOT per [`SUB`] cell -- reading them at
12236 // `mi_c / (SUB / MI)` asked a block two mi rows/columns away whether it
12237 // was inter, so a var-tx-split inter neighbour contributed its (smaller)
12238 // transform size instead of its block size and the `tx_depth` CDF row
12239 // came out one too low.
12240 if has_above && n.above_inter[mi_c] {
12241 above = n.above_side_mi[mi_c] >= side;
12242 }
12243 if has_left && n.left_inter[mi_r] {
12244 left = n.left_side_mi[mi_r] >= side;
12245 }
12246 match (has_above, has_left) {
12247 (true, true) => usize::from(above) + usize::from(left),
12248 (true, false) => usize::from(above),
12249 (false, true) => usize::from(left),
12250 (false, false) => 0,
12251 }
12252}
12253
12254/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
12255/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
12256/// the transform's own side in pixels (`side >> depth`) -- this decoder's
12257/// four square categories (8/16/32/64) each halve at most twice, matching
12258/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
12259fn read_tx_size(
12260 dec: &mut SymbolDecoder,
12261 cdfs: &mut Cdfs,
12262 n: &Neighbours,
12263 at_mi: (usize, usize),
12264 side: usize,
12265 // lane-txselect: `get_tx_size_context`'s real context, for the callers
12266 // that have one -- see [`tx_size_context_txfm`]. `None` keeps the
12267 // key-frame path's own deblock-grid approximation.
12268 ctx_override: Option<usize>,
12269) -> usize {
12270 // `max_txsize_rect_lookup[bsize]` (libaom `read_selected_tx_size` /
12271 // `get_tx_size_context`): a block wider than 64 still tops out at
12272 // TX_64X64, so BLOCK_128X128 reads BLOCK_64X64's own category (its depth
12273 // chain 64->32->16->8->4 is the same four steps) and resolves against 64,
12274 // never against its own 128 side (lane-sb128b r1).
12275 let max_tx = side.min(64);
12276 let ctx = ctx_override.unwrap_or_else(|| tx_size_context(n, at_mi, max_tx));
12277 let depth = match max_tx {
12278 8 => {
12279 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
12280 }
12281 16 => {
12282 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
12283 }
12284 32 => {
12285 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
12286 }
12287 64 => {
12288 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
12289 }
12290 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64/128"),
12291 };
12292 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
12293 let (rng, _) = dec.debug_state();
12294 let (mi_r, mi_c) = at_mi;
12295 eprintln!(
12296 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={depth} ctx={ctx} rng={rng}"
12297 );
12298 }
12299 if depth != 0 {
12300 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
12301 }
12302 max_tx >> depth
12303}
12304
12305/// `txfm_partition_context` (libaom `av1_common_int.h`): an inter block's
12306/// `txfm_split` context -- a category from the block's own largest square
12307/// transform and whether this unit already sits below it, times three, plus
12308/// the two neighbour terms (whether the transform last written above/left of
12309/// this unit is narrower/shorter than the unit itself).
12310fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize {
12311 txfm_partition_ctx_rect(above_px, left_px, blk_max_px, tx_px, tx_px)
12312}
12313
12314/// [`txfm_partition_ctx`] for a *rectangular* transform (lane-inter4 r2):
12315/// libaom's `txfm_partition_context` compares the above context against
12316/// `tx_size_wide` and the left one against `tx_size_high`, and takes its
12317/// category from `txsize_sqr_up_map[tx_size]` -- all three collapse to one
12318/// side for a square transform, which is why the square form above is a
12319/// special case of this one.
12320fn txfm_partition_ctx_rect(
12321 above_px: u8,
12322 left_px: u8,
12323 blk_max_px: usize,
12324 tx_w: usize,
12325 tx_h: usize,
12326) -> usize {
12327 let above = usize::from(usize::from(above_px) < tx_w);
12328 let left = usize::from(usize::from(left_px) < tx_h);
12329 let tx_px = tx_w.max(tx_h);
12330 // `get_sqr_tx_size(max(block_size_wide, block_size_high))`, capped at the
12331 // largest transform (`TX_64X64`); `TX_4X4`..`TX_64X64` index as
12332 // `log2(px) - 2`.
12333 let max_tx = blk_max_px.min(64);
12334 let max_idx = max_tx.trailing_zeros() as usize - 2;
12335 let category = usize::from(tx_px != max_tx && max_tx > 8) + (4 - max_idx) * 2;
12336 category * 3 + above + left
12337}
12338
12339/// `txfm_partition_update` (libaom `av1_common_int.h`): once a var-tx unit
12340/// resolves, every mi cell its *parent* unit (`txb_px`) spans records the
12341/// resolved transform's own size.
12342fn txfm_partition_update(
12343 n: &mut Neighbours,
12344 at_mi: (usize, usize),
12345 tx_px: usize,
12346 txb_px: usize,
12347) {
12348 txfm_partition_update_rect(n, at_mi, (tx_px, tx_px), (txb_px, txb_px));
12349}
12350
12351/// [`txfm_partition_update`] for a rectangular transform (lane-inter4 r2):
12352/// the left column records `tx_size_high` over the parent's own height and
12353/// the above row records `tx_size_wide` over its width.
12354fn txfm_partition_update_rect(
12355 n: &mut Neighbours,
12356 (mi_r, mi_c): (usize, usize),
12357 (tx_w, tx_h): (usize, usize),
12358 (txb_w, txb_h): (usize, usize),
12359) {
12360 for i in 0..txb_h / MI {
12361 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
12362 *cell = tx_h as u8;
12363 }
12364 }
12365 for i in 0..txb_w / MI {
12366 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
12367 *cell = tx_w as u8;
12368 }
12369 }
12370}
12371
12372/// `set_txfm_ctxs` (libaom `av1_common_int.h`): the non-var-tx write of the
12373/// same contexts -- a skipped *inter* block records its own block size rather
12374/// than its transform size.
12375fn set_txfm_ctxs(
12376 n: &mut Neighbours,
12377 (mi_r, mi_c): (usize, usize),
12378 tx_px: usize,
12379 w_mi: usize,
12380 h_mi: usize,
12381 skip_inter: bool,
12382) {
12383 let bw = if skip_inter { w_mi * MI } else { tx_px };
12384 let bh = if skip_inter { h_mi * MI } else { tx_px };
12385 for i in 0..w_mi {
12386 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
12387 *cell = bw as u8;
12388 }
12389 }
12390 for i in 0..h_mi {
12391 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
12392 *cell = bh as u8;
12393 }
12394 }
12395}
12396
12397/// The value libaom initialises both transform contexts to -- NOT zero:
12398/// `av1_zero_above_context` memsets the txfm row to
12399/// `tx_size_wide[TX_SIZES_LARGEST]` and `av1_zero_left_context` does the same
12400/// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64
12401/// pixels, so an unwritten neighbour reads as the *widest* possible
12402/// transform, not the narrowest.
12403const TXFM_CTX_INIT: u8 = 64;
12404
12405/// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most
12406/// twice below its own largest transform.
12407const MAX_VARTX_DEPTH: usize = 2;
12408
12409/// libaom `sub_tx_size_map[TX_SIZES_ALL]` (`common_data.c`): the transform
12410/// one `txfm_split` step below `tx_size`. RECTANGULAR for the 1:4 shapes
12411/// (`[TX_64X16] == TX_32X16`, `[TX_16X64] == TX_16X32`) and for the 4:1
12412/// small ones, square everywhere else.
12413fn sub_tx_size_map(tx_w: usize, tx_h: usize) -> (usize, usize) {
12414 match (tx_w, tx_h) {
12415 (4, 4) => (4, 4),
12416 (8, 8) => (4, 4),
12417 (16, 16) => (8, 8),
12418 (32, 32) => (16, 16),
12419 (64, 64) => (32, 32),
12420 (4, 8) | (8, 4) => (4, 4),
12421 (8, 16) | (16, 8) => (8, 8),
12422 (16, 32) | (32, 16) => (16, 16),
12423 (32, 64) | (64, 32) => (32, 32),
12424 (4, 16) => (4, 8),
12425 (16, 4) => (8, 4),
12426 (8, 32) => (8, 16),
12427 (32, 8) => (16, 8),
12428 (16, 64) => (16, 32),
12429 (64, 16) => (32, 16),
12430 _ => unreachable!("not a TX_SIZES_ALL shape: {tx_w}x{tx_h}"),
12431 }
12432}
12433
12434#[test]
12435fn sub_tx_size_map_matches_libaom() {
12436 // libaom `common_data.c` `sub_tx_size_map`, in TX_SIZES_ALL order.
12437 const TABLE: [((usize, usize), (usize, usize)); 19] = [
12438 ((4, 4), (4, 4)), ((8, 8), (4, 4)), ((16, 16), (8, 8)), ((32, 32), (16, 16)),
12439 ((64, 64), (32, 32)), ((4, 8), (4, 4)), ((8, 4), (4, 4)), ((8, 16), (8, 8)),
12440 ((16, 8), (8, 8)), ((16, 32), (16, 16)), ((32, 16), (16, 16)), ((32, 64), (32, 32)),
12441 ((64, 32), (32, 32)), ((4, 16), (4, 8)), ((16, 4), (8, 4)), ((8, 32), (8, 16)),
12442 ((32, 8), (16, 8)), ((16, 64), (16, 32)), ((64, 16), (32, 16)),
12443 ];
12444 for (tx, want) in TABLE {
12445 assert_eq!(sub_tx_size_map(tx.0, tx.1), want, "sub_tx_size_map({tx:?})");
12446 }
12447}
12448
12449/// `read_var_tx_size` (spec 5.11.17, libaom `decodeframe.c`
12450/// `read_tx_size_vartx`): the recursive `txfm_split` tree of one
12451/// max-transform-sized unit of an inter block, collecting the resolved leaf
12452/// transform units into `out` as `(row offset, col offset, side)` in mi units
12453/// -- exactly the order `decode_reconstruct_tx` later reads their
12454/// coefficients in. `blk_row`/`blk_col` are mi offsets inside the block;
12455/// `max_w_mi`/`max_h_mi` clip it to the true frame edge (`max_block_wide`/
12456/// `max_block_high`).
12457#[allow(clippy::too_many_arguments)]
12458fn read_var_tx_size(
12459 dec: &mut SymbolDecoder,
12460 cdfs: &mut Cdfs,
12461 n: &mut Neighbours,
12462 at_mi: (usize, usize),
12463 blk_max_px: usize,
12464 (max_w_mi, max_h_mi): (usize, usize),
12465 (tx_w, tx_h): (usize, usize),
12466 depth: usize,
12467 blk_row: usize,
12468 blk_col: usize,
12469 out: &mut Vec<(usize, usize, usize, usize)>,
12470) {
12471 if blk_row >= max_h_mi || blk_col >= max_w_mi {
12472 return;
12473 }
12474 let unit = (at_mi.0 + blk_row, at_mi.1 + blk_col);
12475 if depth == MAX_VARTX_DEPTH {
12476 out.push((blk_row, blk_col, tx_w, tx_h));
12477 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
12478 return;
12479 }
12480 let ctx = txfm_partition_ctx_rect(
12481 n.above_txfm[unit.1],
12482 n.left_txfm[unit.0],
12483 blk_max_px,
12484 tx_w,
12485 tx_h,
12486 );
12487 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
12488 TXFM_SPLIT_READS.with(|c| c.set(c.get() + 1));
12489 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
12490 let (rng, _) = dec.debug_state();
12491 eprintln!(
12492 "EC_ISTEP mi_row={} mi_col={} name=txfm_split val={} ctx={ctx} rng={rng}",
12493 unit.0,
12494 unit.1,
12495 u8::from(split)
12496 );
12497 }
12498 if !split {
12499 out.push((blk_row, blk_col, tx_w, tx_h));
12500 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
12501 return;
12502 }
12503 TXFM_SPLIT_HITS.with(|c| c.set(c.get() + 1));
12504 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
12505 if (sub_w, sub_h) == (4, 4) {
12506 // libaom's `sub_txs == TX_4X4` early return: every mi cell of the
12507 // unit is marked 4x4 (raster order) without recursing.
12508 for row in 0..tx_h / MI {
12509 for col in 0..tx_w / MI {
12510 if blk_row + row < max_h_mi && blk_col + col < max_w_mi {
12511 out.push((blk_row + row, blk_col + col, 4, 4));
12512 }
12513 }
12514 }
12515 txfm_partition_update_rect(n, unit, (4, 4), (tx_w, tx_h));
12516 return;
12517 }
12518 for row in (0..tx_h / MI).step_by(sub_h / MI) {
12519 for col in (0..tx_w / MI).step_by(sub_w / MI) {
12520 read_var_tx_size(
12521 dec,
12522 cdfs,
12523 n,
12524 at_mi,
12525 blk_max_px,
12526 (max_w_mi, max_h_mi),
12527 (sub_w, sub_h),
12528 depth + 1,
12529 blk_row + row,
12530 blk_col + col,
12531 out,
12532 );
12533 }
12534 }
12535}
12536
12537/// `read_block_tx_size` (libaom `decodeframe.c` `parse_decode_block`'s tx
12538/// branch): every block of a `TxMode::Select` inter frame codes its transform
12539/// size right after its own mode info -- an inter non-skip block through the
12540/// recursive var-tx tree ([`read_var_tx_size`], whose leaf list this returns),
12541/// every other block through the intra `tx_depth` symbol (a skipped inter
12542/// block codes no symbol at all) plus a `set_txfm_ctxs` write. Returns the
12543/// block's own resolved transform side and the leaf list, the latter only
12544/// when the tree resolved to more than one transform unit.
12545#[allow(clippy::too_many_arguments)]
12546fn read_block_tx_size(
12547 dec: &mut SymbolDecoder,
12548 cdfs: &mut Cdfs,
12549 n: &mut Neighbours,
12550 at_mi: (usize, usize),
12551 side: usize,
12552 (mi_cols, mi_rows): (usize, usize),
12553 is_inter: bool,
12554 skip: bool,
12555) -> Result<(usize, Option<Vec<(usize, usize, usize, usize)>>)> {
12556 if !TX_SELECT_INTER.with(std::cell::Cell::get) {
12557 // lane-sb128c r1: `max_txsize_rect_lookup[BLOCK_128X128]` is TX_64X64,
12558 // so a 128x128 inter block is FOUR luma units even with `tx_mode ==
12559 // TX_MODE_LARGEST` -- the same leaf shape the var-tx tree hands back.
12560 // lane-sb128c r3: intra too -- an INTRA 128x128 block under
12561 // `TX_MODE_LARGEST` also resolves to TX_64X64, i.e. four luma units.
12562 if side > 64 {
12563 let step = 64 / MI;
12564 let mut leaves = Vec::new();
12565 for row in (0..side / MI).step_by(step) {
12566 for col in (0..side / MI).step_by(step) {
12567 leaves.push((row, col, 64, 64));
12568 }
12569 }
12570 return Ok((64, Some(leaves)));
12571 }
12572 return Ok((side, None));
12573 }
12574 let side_mi = side / MI;
12575 if is_inter && !skip {
12576 let max_tx = side.min(64);
12577 let max_w_mi = side_mi.min(mi_cols.saturating_sub(at_mi.1));
12578 let max_h_mi = side_mi.min(mi_rows.saturating_sub(at_mi.0));
12579 let mut leaves = Vec::new();
12580 let step = max_tx / MI;
12581 for row in (0..side_mi).step_by(step) {
12582 for col in (0..side_mi).step_by(step) {
12583 read_var_tx_size(
12584 dec,
12585 cdfs,
12586 n,
12587 at_mi,
12588 side,
12589 (max_w_mi, max_h_mi),
12590 (max_tx, max_tx),
12591 0,
12592 row,
12593 col,
12594 &mut leaves,
12595 );
12596 }
12597 }
12598 let single = leaves.len() == 1 && leaves[0].2 == side && leaves[0].3 == side;
12599 // lane-sb128c r6: below the 128 root the ceiling is main's TX_32X32
12600 // ([`inter_txbset_for`] has no 64-point *inter* table set); a 128x128
12601 // block's own var-tx tree legitimately bottoms out at TX_64X64 leaves,
12602 // which the mu-chunk reader above codes as their 32x32 coded corner.
12603 let leaf_ceiling = if side > 64 { 64 } else { 32 };
12604 if !single && leaves.iter().any(|leaf| leaf.2.max(leaf.3) > leaf_ceiling) {
12605 // Only a block wider than a superblock's own 64x64 max transform
12606 // reaches here; this crate has no 64-point *inter* coefficient
12607 // table set ([`inter_txbset_for`] stops at 32).
12608 return Err(unsupported(
12609 "an inter var-tx tree with a leaf transform larger than 32x32",
12610 ));
12611 }
12612 let resolved = leaves.last().map_or(side, |l| l.2);
12613 return Ok((resolved, (!single).then_some(leaves)));
12614 }
12615 let tx = if is_inter {
12616 side.min(64)
12617 } else {
12618 read_tx_size(
12619 dec,
12620 cdfs,
12621 n,
12622 at_mi,
12623 side,
12624 // lane-sb128c r3: `get_tx_size_context` compares the neighbour txfm
12625 // contexts against `tx_size_wide[max_txsize_rect_lookup[bsize]]`,
12626 // which is 64 for BLOCK_128X128 -- never the block's own 128 side.
12627 Some(tx_size_context_txfm(n, at_mi, side.min(64))),
12628 )
12629 };
12630 set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter);
12631 if !is_inter && tx != side {
12632 // lane-intrainter r1: an intra block inside an inter frame whose
12633 // `tx_depth` split its luma transform codes exactly the key-frame
12634 // split path's transform units (`decode_block`'s multi-TU loop),
12635 // raster order over the block. Handed back in the same leaf shape the
12636 // inter var-tx tree uses, so the caller's per-TU luma loop, the
12637 // `record_split_luma` neighbour write-back and the per-TU deblock
12638 // edges are the ones it already runs for a var-tx inter block. A
12639 // caller that has no per-TU intra loop (the 8x8 leaf) refuses on
12640 // seeing `Some` here.
12641 let step = tx / MI;
12642 let mut leaves = Vec::new();
12643 for row in (0..side_mi).step_by(step) {
12644 for col in (0..side_mi).step_by(step) {
12645 leaves.push((row, col, tx, tx));
12646 }
12647 }
12648 INTRA_IN_INTER_SPLIT_TX_HITS.with(|c| {
12649 let mut h = c.get();
12650 h[(side.trailing_zeros() as usize).saturating_sub(3).min(3)] += 1;
12651 c.set(h);
12652 });
12653 return Ok((tx, Some(leaves)));
12654 }
12655 Ok((tx, None))
12656}
12657
12658/// lane-inter4 r2: the shapes whose *rectangular inter* residual this
12659/// decoder codes -- a 2:1 strip whose own max rect transform
12660/// (`max_txsize_rect_lookup[BLOCK_32X16] == TX_32X16`) has both a
12661/// coefficient table set ([`TxbSet::LumaRect32x16Inter`], 512-coefficient
12662/// `eob_pt`) and a `tx_type` alphabet here. 64x32/64x16 strips would need a
12663/// 64-point rect transform, and 16x8/8x16 needs
12664/// `default_inter_ext_tx_cdf[2][TX_8X8]` (the 12-symbol
12665/// `DTT9_IDTX_1DDCT` row at `tx_size_sqr == TX_8X8`, only reachable through a
12666/// rect transform), neither of which exists yet -- both stay refused by name.
12667fn rect_inter_residual_supported(w: usize, h: usize) -> bool {
12668 matches!(
12669 (w, h),
12670 // 2:1 strips whose transform is coded in full (lane-inter4).
12671 (32, 16) | (16, 32) | (16, 8) | (8, 16)
12672 // lane-inter16ab r2: the 16x16-level 1:4 strips. TX_16X4/TX_4X16
12673 // codes all 64 of its positions, and its chroma pair is an 8x4 /
12674 // 4x8 unit (`ss_size_lookup[BLOCK_16X4]` = BLOCK_8X4).
12675 | (16, 4) | (4, 16)
12676 // lane-r14 r2: strips with a 64-px axis. `av1_get_max_eob` codes
12677 // only the low 32 coefficients of a 64-length axis, so these read
12678 // exactly the truncated corner the INTRA superblock-strip path
12679 // already reads (`read_intra_mode_rect`), through
12680 // `av1_get_adjusted_tx_size`'s CDF set. Their `tx_size_sqr_up` is
12681 // `TX_64X64`, so `av1_get_ext_tx_set_type` is `DCT_ONLY` and no
12682 // `tx_type` symbol is coded at all.
12683 | (64, 32) | (32, 64) | (64, 16) | (16, 64)
12684 // lane-inter16ab r4: `sub_tx_size_map[TX_16X4] == TX_8X4`, so a
12685 // split-transform 16x4/4x16 strip has RECTANGULAR 8x4/4x8 leaves.
12686 // Only reachable as a var-tx LEAF -- an 8x4/4x8 inter BLOCK is
12687 // refused earlier ("an inter partition below 8x8").
12688 | (8, 4) | (4, 8)
12689 )
12690}
12691
12692/// The luma coefficient/`tx_type` table set of a whole-block rectangular
12693/// INTER transform unit (lane-inter4 r3). `av1_get_ext_tx_set_type` splits
12694/// the two shapes: a 32x16/16x32 unit has `tx_size_sqr_up == TX_32X32`, so
12695/// it reads the 2-symbol `EXT_TX_SET_DCT_IDTX` set regardless of
12696/// `reduced_tx_set`; a 16x8/8x16 unit has `tx_size_sqr_up == TX_16X16` and
12697/// `tx_size_sqr == TX_8X8`, so it reads `EXT_TX_SET_DCT_IDTX` when reduced
12698/// and the 16-symbol `EXT_TX_SET_ALL16` otherwise -- both at the *8x8* CDF
12699/// row (`txsize_sqr_map`), never the 16x16 one.
12700fn rect_inter_luma_set(w: usize, h: usize) -> Result<TxbSet> {
12701 Ok(match (w, h) {
12702 (32, 16) | (16, 32) => TxbSet::LumaRect32x16Inter,
12703 // lane-inter16ab r4: the 8x4/4x8 split leaf of a 16x4/4x16 strip.
12704 // `av1_get_ext_tx_set_type` (blockd.h:1097) at `tx_size_sqr_up ==
12705 // TX_8X8`, `tx_size_sqr == TX_4X4`, inter: DCT_IDTX when reduced,
12706 // ALL16 otherwise -- both at the TX_4X4 row.
12707 (8, 4) | (4, 8) => {
12708 if REDUCED_TX_SET_INTER.with(std::cell::Cell::get) {
12709 TxbSet::LumaRect8x4Inter
12710 } else {
12711 TxbSet::LumaRect8x4Inter1
12712 }
12713 }
12714 (16, 4) | (4, 16) => {
12715 if REDUCED_TX_SET_INTER.with(std::cell::Cell::get) {
12716 TxbSet::LumaRect16x4Inter
12717 } else {
12718 TxbSet::LumaRect16x4Inter1
12719 }
12720 }
12721 (16, 8) | (8, 16) => {
12722 if REDUCED_TX_SET_INTER.with(std::cell::Cell::get) {
12723 TxbSet::LumaRect16x8Inter
12724 } else {
12725 TxbSet::LumaRect16x8InterSet1
12726 }
12727 }
12728 // lane-r14 r2: `av1_get_adjusted_tx_size` maps TX_64X32/TX_32X64 to
12729 // TX_32X32 and TX_64X16/TX_16X64 to TX_32X16/TX_16X32, and
12730 // `get_txsize_entropy_ctx`/`txsize_log2_minus4` agree with the
12731 // adjusted size, so the existing sets are bit-exact. Neither carries a
12732 // `tx_type` table (DCT_ONLY above), so the intra/inter split is moot.
12733 (64, 32) | (32, 64) => TxbSet::Luma64,
12734 (64, 16) | (16, 64) => TxbSet::LumaRect32x16,
12735 _ => {
12736 return Err(unsupported(
12737 "a rectangular inter luma transform unit whose shape has no coefficient table set here",
12738 ));
12739 }
12740 })
12741}
12742
12743/// The chroma table set of the same block's single rectangular chroma unit
12744/// (`av1_get_max_uv_txsize`): 16x8/8x16 under a 32x16/16x32 strip, 8x4/4x8
12745/// under a 16x8/8x16 one. Neither codes a `tx_type` symbol -- both inherit
12746/// the luma unit's.
12747fn rect_inter_chroma_set(w: usize, h: usize) -> Result<TxbSet> {
12748 Ok(match (w, h) {
12749 (16, 8) | (8, 16) => TxbSet::ChromaRect16x8,
12750 (8, 4) | (4, 8) => TxbSet::ChromaRect8x4,
12751 // lane-r14 r2: chroma of a 64-axis strip -- 32x16/16x32 under a
12752 // 64x32/32x64 one, 32x8/8x32 under a 64x16/16x64 one. Neither chroma
12753 // unit has a 64-px axis, so both are coded in full; `Chroma16` is the
12754 // exact set for TX_32X8/TX_8X32 (`get_txsize_entropy_ctx` = TX_16X16,
12755 // `txsize_log2_minus4` = 4), same as the intra strip path uses.
12756 (32, 16) | (16, 32) => TxbSet::ChromaRect32x16,
12757 (32, 8) | (8, 32) => TxbSet::Chroma16,
12758 _ => {
12759 return Err(unsupported(
12760 "a rectangular inter chroma transform unit whose shape has no coefficient table set here",
12761 ));
12762 }
12763 })
12764}
12765
12766/// libaom `size_group_lookup[bsize]` for the block shapes this decoder's
12767/// inter path reaches, from the block's TRUE footprint rather than the
12768/// square `side` corner-cut: 8x8/8x16/16x8 -> 1, 16x16/16x32/32x16 -> 2,
12769/// everything 32 and above -> 3.
12770fn size_group_wh(w: usize, h: usize) -> usize {
12771 // lane-inter4 r4: `size_group_lookup[BLOCK_SIZES_ALL]` (libaom
12772 // `common_data.h:60`) is 0 for every block with a 4-px side
12773 // (4x4/4x8/8x4/4x16/16x4), 1 for min side 8, 2 for 16, 3 above -- the old
12774 // `0..=8 => 1` row gave a sub-8 leaf group 1 where libaom says 0.
12775 match w.min(h) {
12776 0..=4 => 0,
12777 8 => 1,
12778 16 => 2,
12779 _ => 3,
12780 }
12781}
12782
12783#[test]
12784fn size_group_wh_matches_libaom_size_group_lookup() {
12785 // `BLOCK_SIZES_ALL` in libaom's own order, with `size_group_lookup`'s
12786 // transcribed values (common_data.h:60-62).
12787 const TABLE: [((usize, usize), usize); 22] = [
12788 ((4, 4), 0), ((4, 8), 0), ((8, 4), 0), ((8, 8), 1), ((8, 16), 1), ((16, 8), 1),
12789 ((16, 16), 2), ((16, 32), 2), ((32, 16), 2), ((32, 32), 3), ((32, 64), 3),
12790 ((64, 32), 3), ((64, 64), 3), ((64, 128), 3), ((128, 64), 3), ((128, 128), 3),
12791 ((4, 16), 0), ((16, 4), 0), ((8, 32), 1), ((32, 8), 1), ((16, 64), 2), ((64, 16), 2),
12792 ];
12793 for ((w, h), want) in TABLE {
12794 assert_eq!(size_group_wh(w, h), want, "size_group_wh({w}, {h})");
12795 }
12796}
12797
12798/// The default (2D) coefficient scan of a rectangular transform.
12799fn rect_scan(w: usize, h: usize) -> Result<&'static [u16]> {
12800 Ok(match (w, h) {
12801 (32, 16) => &SCAN_32X16,
12802 (16, 32) => &SCAN_16X32,
12803 (16, 8) => &SCAN_16X8,
12804 (8, 16) => &SCAN_8X16,
12805 (16, 4) => &SCAN_16X4,
12806 (4, 16) => &SCAN_4X16,
12807 (8, 4) => &SCAN_8X4,
12808 (4, 8) => &SCAN_4X8,
12809 (32, 8) => &SCAN_32X8,
12810 (8, 32) => &SCAN_8X32,
12811 _ => {
12812 return Err(unsupported(
12813 "a rectangular transform unit whose shape has no coefficient scan table here",
12814 ));
12815 }
12816 })
12817}
12818
12819/// [`read_block_tx_size`] for a rectangular inter block (lane-inter4 r2):
12820/// spec 5.11.17 / libaom `read_tx_size_vartx` starting from the block's own
12821/// `max_txsize_rect_lookup` entry, which for a 2:1 strip IS rectangular. The
12822/// depth-0 `txfm_partition` symbol reads its context off the rect transform's
12823/// own width/height; a `0` leaves one whole-block rect transform unit
12824/// (`None`), and a `1` splits it into `sub_tx_size_map`'s two SQUARE
12825/// sub-transforms (`sub_tx_size_map[TX_32X16] == TX_16X16`), from which the
12826/// ordinary square [`read_var_tx_size`] recursion continues at depth 1 -- so
12827/// every leaf of a split rect block is square and the existing square leaf
12828/// loop reconstructs it unchanged.
12829#[allow(clippy::too_many_arguments)]
12830fn read_block_tx_size_rect(
12831 dec: &mut SymbolDecoder,
12832 cdfs: &mut Cdfs,
12833 n: &mut Neighbours,
12834 at_mi: (usize, usize),
12835 (bw, bh): (usize, usize),
12836 (mi_cols, mi_rows): (usize, usize),
12837 skip: bool,
12838) -> Result<Option<Vec<(usize, usize, usize, usize)>>> {
12839 if skip {
12840 // `set_txfm_ctxs(.., skip && is_inter)`: a skipped inter block records
12841 // its own BLOCK size -- width above, height left -- not a transform.
12842 txfm_partition_update_rect(n, at_mi, (bw, bh), (bw, bh));
12843 return Ok(None);
12844 }
12845 // `max_txsize_rect_lookup` is the block's own size, capped at 64 -- and
12846 // `rect_inter_residual_supported` has already excluded everything above 32.
12847 let (tx_w, tx_h) = (bw, bh);
12848 if !TX_SELECT_INTER.with(std::cell::Cell::get) {
12849 // `TX_MODE_LARGEST`: no symbol at all, the whole block is one
12850 // transform, and `set_txfm_ctxs` records exactly what
12851 // `txfm_partition_update` would for that same unit.
12852 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
12853 RECT_INTER_TU_HITS.with(|c| c.set(c.get() + 1));
12854 return Ok(None);
12855 }
12856 let ctx = txfm_partition_ctx_rect(
12857 n.above_txfm[at_mi.1],
12858 n.left_txfm[at_mi.0],
12859 bw.max(bh),
12860 tx_w,
12861 tx_h,
12862 );
12863 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
12864 TXFM_SPLIT_READS.with(|c| c.set(c.get() + 1));
12865 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
12866 let (rng, _) = dec.debug_state();
12867 eprintln!(
12868 "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}",
12869 at_mi.0,
12870 at_mi.1,
12871 u8::from(split)
12872 );
12873 }
12874 if !split {
12875 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
12876 RECT_INTER_TU_HITS.with(|c| c.set(c.get() + 1));
12877 return Ok(None);
12878 }
12879 TXFM_SPLIT_HITS.with(|c| c.set(c.get() + 1));
12880 RECT_INTER_TXSPLIT_HITS.with(|c| c.set(c.get() + 1));
12881 // lane-r14 r3: `sub_tx_size_map` (libaom `common_data.c`) stays
12882 // RECTANGULAR under a 1:4 strip -- `[TX_64X16] == TX_32X16`,
12883 // `[TX_16X64] == TX_16X32` -- so the recursion below is the general
12884 // rect one and its leaves carry their own width and height.
12885 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
12886 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(at_mi.1));
12887 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(at_mi.0));
12888 let mut leaves = Vec::new();
12889 for row in (0..bh / MI).step_by(sub_h / MI) {
12890 for col in (0..bw / MI).step_by(sub_w / MI) {
12891 read_var_tx_size(
12892 dec,
12893 cdfs,
12894 n,
12895 at_mi,
12896 bw.max(bh),
12897 (max_w_mi, max_h_mi),
12898 (sub_w, sub_h),
12899 1,
12900 row,
12901 col,
12902 &mut leaves,
12903 );
12904 }
12905 }
12906 Ok(Some(leaves))
12907}
12908
12909/// [`read_inter_plane`] for a rectangular transform unit (lane-inter4 r2):
12910/// the coefficients are read with the rect coefficient machinery
12911/// ([`read_coeffs_rect`], whose `TxClass` handling covers the 1D `V_*`/`H_*`
12912/// types), inverted with the rect inverse transform
12913/// ([`dequant_and_inverse_typed_wh`], which carries the 2:1 `sqrt2` scale),
12914/// and added onto the top-left `w x h` of the block's own square-strided
12915/// motion-compensated prediction buffer. Returns the *rect* coefficient grid
12916/// and the coded `tx_type`.
12917///
12918/// `txb_skip_ctx` is 0 for luma: this unit covers the whole block, i.e.
12919/// `get_txb_ctx`'s `plane_bsize == txsize_to_bsize[tx_size]` branch.
12920#[allow(clippy::too_many_arguments)]
12921fn read_inter_plane_rect(
12922 dec: &mut SymbolDecoder,
12923 cdfs: &mut Cdfs,
12924 set: TxbSet,
12925 (w, h): (usize, usize),
12926 stride: usize,
12927 plane_idx: usize,
12928 around: (bool, bool, i32),
12929 tx_mode: usize,
12930 plane: &mut PlaneBuf,
12931 x: usize,
12932 y: usize,
12933 prediction: &[u16],
12934 inherited_luma_tx_type: Option<TxType>,
12935 luma_skip_ctx: Option<usize>,
12936) -> Result<(Vec<i32>, TxType)> {
12937 let skip_ctx = if plane_idx == 0 {
12938 // `get_txb_ctx_general`: 0 only when this unit IS the whole plane
12939 // block; a var-tx leaf passes its own neighbour-table context.
12940 luma_skip_ctx.unwrap_or(0)
12941 } else {
12942 usize::from(around.0) + usize::from(around.1)
12943 };
12944 let mut coding = cdfs.txb(set, tx_mode);
12945 // `av1_get_ext_tx_set_type`'s DCT-only clamp is on `tx_size_sqr_up`, i.e.
12946 // the *longer* side of this rect transform.
12947 let default_tx_type = match inherited_luma_tx_type {
12948 Some(t) => reduce_inherited_chroma_tx_type(t, w, h),
12949 None => TxType::DctDct,
12950 };
12951 // lane-r14 r2: a 64-length axis codes only its low 32 coefficients
12952 // (`av1_get_max_eob`), so the coded unit is the `min(w,32) x min(h,32)`
12953 // corner, zero-extended into the true `w x h` grid before the inverse
12954 // transform -- exactly what the intra superblock-strip path does. A
12955 // corner that comes out square (32x32, under a 64x32/32x64 strip) reads
12956 // through the SQUARE coefficient reader with `rect_shape = Some((w, h))`,
12957 // because `av1_nz_map_ctx_offset` is indexed by the real, un-adjusted
12958 // rectangular shape (lane-sbpart r8).
12959 let (cw, ch) = (w.min(32), h.min(32));
12960 if plane_idx == 0 && w.max(h) == 64 {
12961 RECT64_INTER_TU_HITS.with(|c| c.set(c.get() + 1));
12962 }
12963 let (corner, tx_type) = if (cw, ch) == (32, 32) {
12964 let scan32 = default_scan(TX32);
12965 read_coeffs(
12966 dec,
12967 &mut coding,
12968 &scan32,
12969 skip_ctx,
12970 dc_sign_ctx(around.2),
12971 default_tx_type,
12972 Some((w, h)),
12973 )?
12974 } else {
12975 read_coeffs_rect(
12976 dec,
12977 &mut coding,
12978 rect_scan(cw, ch)?,
12979 cw,
12980 ch,
12981 skip_ctx,
12982 dc_sign_ctx(around.2),
12983 default_tx_type,
12984 )?
12985 };
12986 let grid = if (cw, ch) == (w, h) {
12987 corner
12988 } else {
12989 let mut full = vec![0i32; w * h];
12990 for row in 0..ch {
12991 full[row * w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
12992 }
12993 full
12994 };
12995 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
12996 let residual = dequant_and_inverse_typed_wh(
12997 &grid,
12998 w,
12999 h,
13000 bit_depth(),
13001 block_q_idx(),
13002 dc_delta,
13003 ac_delta,
13004 tx_type,
13005 );
13006 // `reconstruct_mc_rect` reads both buffers at the square prediction
13007 // stride, so the dense `w x h` residual is re-laid at that stride first.
13008 let mut strided = vec![0i32; stride * stride];
13009 for row in 0..h {
13010 strided[row * stride..][..w].copy_from_slice(&residual[row * w..][..w]);
13011 }
13012 plane.reconstruct_mc_rect(x, y, stride, w, h, prediction, &strided);
13013 Ok((grid, tx_type))
13014}
13015
13016/// A rect coefficient grid re-laid into the square `stride x stride` grid the
13017/// neighbour/deblock stamps downstream of the residual expect.
13018fn embed_rect_grid(grid: &[i32], w: usize, h: usize, stride: usize) -> Vec<i32> {
13019 let mut full = vec![0i32; stride * stride];
13020 for row in 0..h {
13021 full[row * stride..][..w].copy_from_slice(&grid[row * w..][..w]);
13022 }
13023 full
13024}
13025
13026/// One 8x8 inter leaf's luma residual (lane-txselect): either the whole-8x8
13027/// transform, or -- when [`read_block_tx_size`]'s var-tx tree took the single
13028/// split a `BLOCK_8X8` can take (`split`) -- the four 4x4 transform units in
13029/// raster order, each reading its own coefficient context off the units
13030/// already decoded before it. Returns the block's luma grid (all-zero in the
13031/// split case, whose reconstruction has already happened unit by unit) and
13032/// the `tx_type` chroma inherits: `av1_get_tx_type`'s colocated luma lookup,
13033/// which for a split block lands on the top-left unit.
13034#[allow(clippy::too_many_arguments)]
13035fn read_inter_luma8(
13036 dec: &mut SymbolDecoder,
13037 cdfs: &mut Cdfs,
13038 neighbours: &mut Neighbours,
13039 leaf_mi: (usize, usize),
13040 y: &mut PlaneBuf,
13041 px: usize,
13042 py: usize,
13043 pred_y: &[u16],
13044 mode_for_tx: usize,
13045 base_q_idx: u8,
13046 scan8: &[u16],
13047 scan4: &[u16],
13048 reduced_tx_set: bool,
13049 split: bool,
13050) -> Result<(Vec<i32>, TxType)> {
13051 if !split {
13052 return read_inter_plane(
13053 dec,
13054 cdfs,
13055 if reduced_tx_set {
13056 TxbSet::Luma8Inter
13057 } else {
13058 TxbSet::Luma8InterSet1
13059 },
13060 scan8,
13061 0,
13062 neighbours.around_mi(leaf_mi, 8)[0],
13063 mode_for_tx,
13064 y,
13065 px,
13066 py,
13067 8,
13068 base_q_idx,
13069 pred_y,
13070 None,
13071 None,
13072 );
13073 }
13074 let mut first = TxType::DctDct;
13075 for tu_row in 0..2 {
13076 for tu_col in 0..2 {
13077 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
13078 let mut tu_pred = Vec::with_capacity(16);
13079 for rr in 0..4 {
13080 let start = (tu_row * 4 + rr) * 8 + tu_col * 4;
13081 tu_pred.extend_from_slice(&pred_y[start..start + 4]);
13082 }
13083 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
13084 let (tu_grid, tu_tx_type) = read_inter_plane(
13085 dec,
13086 cdfs,
13087 if reduced_tx_set {
13088 TxbSet::Luma4Inter
13089 } else {
13090 TxbSet::Luma4InterSet1
13091 },
13092 scan4,
13093 0,
13094 neighbours.around_mi(tu_mi, 4)[0],
13095 mode_for_tx,
13096 y,
13097 px + tu_col * 4,
13098 py + tu_row * 4,
13099 4,
13100 base_q_idx,
13101 &tu_pred,
13102 None,
13103 Some(tu_skip_ctx),
13104 )?;
13105 if tu_row == 0 && tu_col == 0 {
13106 first = tu_tx_type;
13107 }
13108 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
13109 }
13110 }
13111 Ok((vec![0i32; 64], first))
13112}
13113
13114/// The [`TxbSet`] one leaf of an inter block's var-tx tree reads its
13115/// coefficient tables from -- the inter counterpart of [`txbset_for`].
13116/// `av1_get_tx_type`'s chroma tail (libaom `av1/common/blockd.h:1291-1305`):
13117/// an inter block's chroma transform inherits the *colocated luma* unit's
13118/// coded `tx_type`, then drops back to `DCT_DCT` unless that type is a member
13119/// of the extended set the CHROMA transform size selects
13120/// (`av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)][tx_type]`,
13121/// `blockd.h:1036`/`1097`). lane-golomb r7: we used to force `DCT_DCT` at
13122/// every chroma side >= 32, but `av1_get_ext_tx_set_type`'s DCT-only rung is
13123/// `tx_size_sqr_up > TX_32X32`; at exactly TX_32X32 an inter block reads
13124/// `EXT_TX_SET_DCT_IDTX`, so a 64x64 inter block whose first luma leaf coded
13125/// `IDTX` inherits IDTX on its 32x32 chroma units. `IDTX` and `DCT_DCT` are
13126/// both `TX_CLASS_2D`, so that mistake left the entropy stream perfectly in
13127/// sync and only corrupted the inverse transform (one 64x64 superblock of
13128/// high-frequency chroma noise, luma bit-exact).
13129fn reduce_inherited_chroma_tx_type(t: TxType, w: usize, h: usize) -> TxType {
13130 use TxType::*;
13131 let sqr_up = w.max(h);
13132 let sqr = w.min(h);
13133 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
13134 // `av1_get_ext_tx_set_type(tx_size, is_inter = 1, reduced)`.
13135 let allowed: &[TxType] = if sqr_up > 32 {
13136 // EXT_TX_SET_DCTONLY
13137 &[DctDct]
13138 } else if sqr_up == 32 || reduced {
13139 // EXT_TX_SET_DCT_IDTX
13140 &[DctDct, Idtx]
13141 } else if sqr == 16 {
13142 // EXT_TX_SET_DTT9_IDTX_1DDCT -- TX_TYPES 0..=11, i.e. everything but
13143 // the four 1D ADST/FLIPADST types.
13144 &[
13145 DctDct, AdstDct, DctAdst, AdstAdst, FlipAdstDct, DctFlipAdst, FlipAdstFlipAdst,
13146 AdstFlipAdst, FlipAdstAdst, Idtx, VDct, HDct,
13147 ]
13148 } else {
13149 // EXT_TX_SET_ALL16
13150 return t;
13151 };
13152 if allowed.contains(&t) { t } else { DctDct }
13153}
13154
13155fn inter_txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
13156 match tx_px {
13157 // lane-sb128c r1: a 128x128 inter block's own luma unit
13158 // (`max_txsize_rect_lookup[BLOCK_128X128] == TX_64X64`).
13159 // `av1_get_ext_tx_set_type` is `DCT_ONLY` at `tx_size_sqr_up ==
13160 // TX_64X64`, so no `tx_type` symbol is coded and the intra/inter sets
13161 // coincide -- exactly the set the whole-64x64 inter block already uses.
13162 64 => TxbSet::Luma64,
13163 32 => TxbSet::Luma32Inter,
13164 16 if reduced_tx_set => TxbSet::Luma16Inter,
13165 16 => TxbSet::Luma16InterSet1,
13166 8 if reduced_tx_set => TxbSet::Luma8Inter,
13167 8 => TxbSet::Luma8InterSet1,
13168 4 if reduced_tx_set => TxbSet::Luma4Inter,
13169 4 => TxbSet::Luma4InterSet1,
13170 _ => unreachable!("a var-tx leaf is never wider than a 64x64 block's 32x32 sub-transform"),
13171 }
13172}
13173
13174/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
13175/// the only four sizes a `TxMode::Select` block's coded coefficient grid
13176/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
13177fn scan_for<'a>(
13178 tx_px: usize,
13179 scan32: &'a [u16],
13180 scan16: &'a [u16],
13181 scan8: &'a [u16],
13182 scan4: &'a [u16],
13183) -> &'a [u16] {
13184 match tx_px {
13185 32 => scan32,
13186 16 => scan16,
13187 8 => scan8,
13188 4 => scan4,
13189 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
13190 }
13191}
13192
13193/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
13194/// from -- 64 is only ever the 64x64-block, depth-0, corner-scanned case
13195/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
13196/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
13197/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
13198/// regardless of the flag (`av1_get_ext_tx_set_type`'s
13199/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
13200/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
13201/// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]).
13202/// [`txbset_for`], for a block libaom's `is_inter_block` calls inter -- which
13203/// an intrabc block is (`blockd.h:373`), so its `tx_type` comes off the
13204/// inter `ext_tx` sets, never the mode-indexed intra ones.
13205fn txbset_for_inter(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
13206 match tx_px {
13207 64 => TxbSet::Luma64,
13208 32 => TxbSet::Luma32Inter,
13209 16 if reduced_tx_set => TxbSet::Luma16Inter,
13210 16 => TxbSet::Luma16InterSet1,
13211 8 if reduced_tx_set => TxbSet::Luma8Inter,
13212 8 => TxbSet::Luma8InterSet1,
13213 _ => TxbSet::Luma64,
13214 }
13215}
13216
13217fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
13218 match tx_px {
13219 64 => TxbSet::Luma64,
13220 32 => TxbSet::Luma32,
13221 16 => TxbSet::Luma16,
13222 8 if reduced_tx_set => TxbSet::Luma8,
13223 8 => TxbSet::Luma8Set1,
13224 4 if reduced_tx_set => TxbSet::Luma4,
13225 4 => TxbSet::Luma4Set1,
13226 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
13227 }
13228}
13229
13230/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
13231/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
13232fn unit_log2(px: u32) -> i32 {
13233 if px == 0 {
13234 0
13235 } else {
13236 px.trailing_zeros() as i32 - 2
13237 }
13238}
13239
13240/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
13241/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
13242/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
13243/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
13244/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
13245/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
13246/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
13247/// block anywhere aborted the whole stream's decode before comparison).
13248fn lf_level(
13249 lf: &LoopFilterParams,
13250 plane_idx: usize,
13251 dir: usize,
13252 ref_frame: i8,
13253 delta_lf: i32,
13254 segment_id: u8,
13255) -> i32 {
13256 let base = i32::from(if plane_idx == 0 {
13257 lf.level[dir]
13258 } else if plane_idx == 1 {
13259 lf.level[2]
13260 } else {
13261 lf.level[3]
13262 });
13263 // spec 7.14.4: the per-superblock `DeltaLF` term applies before the
13264 // ref/mode delta scaling below, and regardless of `delta_enabled`
13265 // (that flag only gates `ref_deltas`/`mode_deltas`).
13266 let base = (base + delta_lf).clamp(0, 63);
13267 // lane-seg, spec 7.14.4 / libaom `av1_loop_filter_frame_init`: this
13268 // block's segment's own `SEG_LVL_ALT_LF_*` delta applies after the
13269 // per-superblock `DeltaLF` term and before the ref/mode deltas below.
13270 // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4)
13271 // for chroma.
13272 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
13273 let base = match seg_feature(usize::from(segment_id), feature) {
13274 Some(data) => (base + data).clamp(0, 63),
13275 None => base,
13276 };
13277 if !lf.delta_enabled {
13278 return base;
13279 }
13280 let scale = 1i32 << (base >> 5);
13281 let is_inter = ref_frame != 0;
13282 let is_globalmv = ref_frame < 0;
13283 let ref_idx = ref_frame.unsigned_abs() as usize;
13284 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
13285 if is_inter {
13286 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
13287 }
13288 lvl.clamp(0, 63)
13289}
13290
13291/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
13292/// no-segmentation, no-delta-LF path and to this decoder's own invariant
13293/// that a coded block's transform is always its own full size -- so a TU
13294/// edge is always also a PU edge, and the "both sides skipped, not a PU
13295/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
13296/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
13297/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
13298fn edge_params(
13299 lf: &LoopFilterParams,
13300 n: &Neighbours,
13301 plane_idx: usize,
13302 dir: usize,
13303 chroma: bool,
13304 x0: usize,
13305 y0: usize,
13306) -> Option<(u8, i32)> {
13307 let (mi_r, mi_c) = (plane_to_mi(chroma, y0), plane_to_mi(chroma, x0));
13308 let cur_tx = if dir == 0 {
13309 tx_px_at(n, chroma, mi_r, mi_c)
13310 } else {
13311 tx_h_px_at(n, chroma, mi_r, mi_c)
13312 };
13313 if cur_tx == 0 || (if dir == 0 { x0 } else { y0 }) % cur_tx as usize != 0 {
13314 return None;
13315 }
13316 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
13317 let (pv_mi_r, pv_mi_c) = if dir == 0 {
13318 (mi_r, mi_c - 1)
13319 } else {
13320 (mi_r - 1, mi_c)
13321 };
13322 let pv_tx = if dir == 0 {
13323 tx_px_at(n, chroma, pv_mi_r, pv_mi_c)
13324 } else {
13325 tx_h_px_at(n, chroma, pv_mi_r, pv_mi_c)
13326 };
13327 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
13328 let delta_idx = if plane_idx == 0 { dir } else { plane_idx + 1 };
13329 let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][delta_idx]);
13330 let pv_delta_lf = i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][delta_idx]);
13331
13332 // spec 7.14.2 / libaom `set_lpf_parameters`: a transform edge between two
13333 // SKIPPED INTER blocks is filtered only when it is also a prediction
13334 // (coded-block) edge -- `!pv_skip || !curr_skipped || pu_edge`. The
13335 // omission of this term (on the stale invariant "a coded block's transform
13336 // is always its own full size", which var-tx broke) had us filtering an
13337 // interior 8-px lattice the reference never touches: on the pinned 192x68
13338 // inter stream frame 1 went from 7244 wrong post-deblock luma px to 0.
13339 let cur_org = n.blk_org_grid[mi_r * n.skip_grid_cols_mi + mi_c];
13340 let pu_edge = if dir == 0 {
13341 mi_c == usize::from(cur_org[1])
13342 } else {
13343 mi_r == usize::from(cur_org[0])
13344 };
13345 if !pu_edge
13346 && cur_ref != 0
13347 && pv_ref != 0
13348 && n.skip_at(mi_r, mi_c)
13349 && n.skip_at(pv_mi_r, pv_mi_c)
13350 {
13351 return None;
13352 }
13353 let cur_level = lf_level(lf, plane_idx, dir, cur_ref, cur_delta_lf, segment_id_at(mi_r, mi_c));
13354 let pv_level = lf_level(
13355 lf,
13356 plane_idx,
13357 dir,
13358 pv_ref,
13359 pv_delta_lf,
13360 segment_id_at(pv_mi_r, pv_mi_c),
13361 );
13362 if cur_level == 0 && pv_level == 0 {
13363 return None;
13364 }
13365 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
13366 let len: u8 = if chroma {
13367 if dim == 0 { 4 } else { 6 }
13368 } else {
13369 [4, 8, 14, 14, 14][dim]
13370 };
13371 let level = if cur_level != 0 { cur_level } else { pv_level };
13372 DEBLOCK_HITS.with(|c| c.set(c.get() + 1));
13373 Some((len, level))
13374}
13375
13376/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
13377fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
13378 let sharpness = i32::from(sharpness);
13379 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
13380 let mut lim = level >> shift;
13381 if sharpness > 0 {
13382 lim = lim.min(9 - sharpness);
13383 }
13384 lim = lim.max(1);
13385 (2 * (level + 2) + lim, lim, level >> 4)
13386}
13387
13388fn sclamp(v: i32) -> i32 {
13389 // libaom's `signed_char_clamp_high`: the clamp range scales with
13390 // `128 << (bit_depth - 8)` alongside the centering constant below.
13391 let scale = 1i32 << (bit_depth() - 8);
13392 v.clamp(-128 * scale, 128 * scale - 1)
13393}
13394
13395fn round_pow2(v: i32, n: u32) -> i32 {
13396 (v + (1 << (n - 1))) >> n
13397}
13398
13399/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
13400/// fallback.
13401fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32) -> [i32; 4] {
13402 if !mask {
13403 return [p1, p0, q0, q1];
13404 }
13405 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
13406 let centre = 128i32 << (bit_depth() - 8);
13407 let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre);
13408 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
13409 let filter = sclamp(outer + 3 * (qs0 - ps0));
13410 let filter1 = sclamp(filter + 4) >> 3;
13411 let filter2 = sclamp(filter + 3) >> 3;
13412 let oq0 = sclamp(qs0 - filter1) + centre;
13413 let op0 = sclamp(ps0 + filter2) + centre;
13414 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
13415 let oq1 = sclamp(qs1 - tap) + centre;
13416 let op1 = sclamp(ps1 + tap) + centre;
13417 [op1, op0, oq0, oq1]
13418}
13419
13420/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
13421/// `filter4`'s narrow taps.
13422#[allow(clippy::too_many_arguments)]
13423fn filter6(
13424 mask: bool,
13425 thresh: i32,
13426 flat: bool,
13427 p2: i32,
13428 p1: i32,
13429 p0: i32,
13430 q0: i32,
13431 q1: i32,
13432 q2: i32,
13433) -> [i32; 4] {
13434 if flat && mask {
13435 [
13436 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
13437 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
13438 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
13439 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
13440 ]
13441 } else {
13442 filter4(mask, thresh, p1, p0, q0, q1)
13443 }
13444}
13445
13446/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
13447#[allow(clippy::too_many_arguments)]
13448fn filter8(
13449 mask: bool,
13450 thresh: i32,
13451 flat: bool,
13452 p3: i32,
13453 p2: i32,
13454 p1: i32,
13455 p0: i32,
13456 q0: i32,
13457 q1: i32,
13458 q2: i32,
13459 q3: i32,
13460) -> [i32; 6] {
13461 if flat && mask {
13462 [
13463 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
13464 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
13465 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
13466 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
13467 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
13468 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
13469 ]
13470 } else {
13471 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1);
13472 [p2, op1, op0, oq0, oq1, q2]
13473 }
13474}
13475
13476/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
13477/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
13478/// way -- they are only ever taps here, never written).
13479#[allow(clippy::too_many_arguments)]
13480fn filter14(
13481 mask: bool,
13482 thresh: i32,
13483 flat: bool,
13484 flat2: bool,
13485 p6: i32,
13486 p5: i32,
13487 p4: i32,
13488 p3: i32,
13489 p2: i32,
13490 p1: i32,
13491 p0: i32,
13492 q0: i32,
13493 q1: i32,
13494 q2: i32,
13495 q3: i32,
13496 q4: i32,
13497 q5: i32,
13498 q6: i32,
13499) -> [i32; 12] {
13500 if flat2 && flat && mask {
13501 [
13502 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
13503 round_pow2(
13504 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
13505 4,
13506 ),
13507 round_pow2(
13508 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
13509 4,
13510 ),
13511 round_pow2(
13512 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
13513 4,
13514 ),
13515 round_pow2(
13516 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
13517 4,
13518 ),
13519 round_pow2(
13520 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
13521 4,
13522 ),
13523 round_pow2(
13524 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
13525 4,
13526 ),
13527 round_pow2(
13528 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
13529 4,
13530 ),
13531 round_pow2(
13532 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
13533 4,
13534 ),
13535 round_pow2(
13536 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
13537 4,
13538 ),
13539 round_pow2(
13540 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
13541 4,
13542 ),
13543 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
13544 ]
13545 } else {
13546 let [op2, op1, op0, oq0, oq1, oq2] =
13547 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3);
13548 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
13549 }
13550}
13551
13552/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
13553/// the first (`q0`) sample past the edge, `outer_stride` advances to the
13554/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
13555/// the next along the edge's own filtering direction.
13556#[allow(clippy::too_many_arguments)]
13557fn filter_edge(
13558 data: &mut [u16],
13559 base: usize,
13560 outer_stride: isize,
13561 tap_stride: isize,
13562 len: u8,
13563 level: i32,
13564 sharpness: u8,
13565) {
13566 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
13567 // libaom `highbd_filter_mask*`/`highbd_flat_mask4`/`highbd_hev_mask`:
13568 // every 8-bit threshold (including the flat masks' fixed `1`) is
13569 // compared against a raw pixel difference on the stream's own bit-depth
13570 // scale, so each is shifted left by `bit_depth - 8` before use.
13571 let shift = bit_depth() - 8;
13572 let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift);
13573 let flat_thresh = 1i32 << shift;
13574 for i in 0..4isize {
13575 let center = (base as isize + i * outer_stride) as usize;
13576 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
13577 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
13578 match len {
13579 4 => {
13580 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
13581 let mask = (p1 - p0).abs() <= limit
13582 && (q1 - q0).abs() <= limit
13583 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
13584 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1);
13585 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
13586 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
13587 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
13588 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
13589 }
13590 6 => {
13591 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
13592 let mask = (p2 - p1).abs() <= limit
13593 && (p1 - p0).abs() <= limit
13594 && (q1 - q0).abs() <= limit
13595 && (q2 - q1).abs() <= limit
13596 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
13597 let flat = (p1 - p0).abs() <= flat_thresh
13598 && (q1 - q0).abs() <= flat_thresh
13599 && (p2 - p0).abs() <= flat_thresh
13600 && (q2 - q0).abs() <= flat_thresh;
13601 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2);
13602 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
13603 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
13604 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
13605 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
13606 }
13607 8 => {
13608 let (p3, p2, p1, p0, q0, q1, q2, q3) =
13609 (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3));
13610 let mask = (p3 - p2).abs() <= limit
13611 && (p2 - p1).abs() <= limit
13612 && (p1 - p0).abs() <= limit
13613 && (q1 - q0).abs() <= limit
13614 && (q2 - q1).abs() <= limit
13615 && (q3 - q2).abs() <= limit
13616 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
13617 let flat = (p1 - p0).abs() <= flat_thresh
13618 && (q1 - q0).abs() <= flat_thresh
13619 && (p2 - p0).abs() <= flat_thresh
13620 && (q2 - q0).abs() <= flat_thresh
13621 && (p3 - p0).abs() <= flat_thresh
13622 && (q3 - q0).abs() <= flat_thresh;
13623 let [op2, op1, op0, oq0, oq1, oq2] =
13624 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3);
13625 data[idx(-3)] = op2.clamp(0, sample_max()) as u16;
13626 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
13627 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
13628 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
13629 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
13630 data[idx(2)] = oq2.clamp(0, sample_max()) as u16;
13631 }
13632 _ => {
13633 let (p6, p5, p4, p3, p2, p1, p0) =
13634 (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1));
13635 let (q0, q1, q2, q3, q4, q5, q6) =
13636 (px(0), px(1), px(2), px(3), px(4), px(5), px(6));
13637 let mask = (p3 - p2).abs() <= limit
13638 && (p2 - p1).abs() <= limit
13639 && (p1 - p0).abs() <= limit
13640 && (q1 - q0).abs() <= limit
13641 && (q2 - q1).abs() <= limit
13642 && (q3 - q2).abs() <= limit
13643 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
13644 let flat = (p1 - p0).abs() <= flat_thresh
13645 && (q1 - q0).abs() <= flat_thresh
13646 && (p2 - p0).abs() <= flat_thresh
13647 && (q2 - q0).abs() <= flat_thresh
13648 && (p3 - p0).abs() <= flat_thresh
13649 && (q3 - q0).abs() <= flat_thresh;
13650 let flat2 = (p4 - p0).abs() <= flat_thresh
13651 && (q4 - q0).abs() <= flat_thresh
13652 && (p5 - p0).abs() <= flat_thresh
13653 && (q5 - q0).abs() <= flat_thresh
13654 && (p6 - p0).abs() <= flat_thresh
13655 && (q6 - q0).abs() <= flat_thresh;
13656 let out = filter14(
13657 mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5,
13658 q6,
13659 );
13660 for (k, v) in (-6..=5isize).zip(out) {
13661 data[idx(k)] = v.clamp(0, sample_max()) as u16;
13662 }
13663 }
13664 }
13665 }
13666}
13667
13668/// One plane's worth of spec 7.14: every vertical edge across the plane,
13669/// then every horizontal edge (the order the spec and libaom both use).
13670fn deblock_plane(
13671 plane: &mut PlaneBuf,
13672 plane_idx: usize,
13673 lf: &LoopFilterParams,
13674 n: &Neighbours,
13675 frame_width: usize,
13676 frame_height: usize,
13677) {
13678 let chroma = plane_idx != 0;
13679 // r7: libaom clips the deblock loop to the CODED frame's own
13680 // width/height, not the mi-aligned `true_width`/`true_height` margin
13681 // (the padding up to the next 8-pixel/superblock boundary that
13682 // reconstruction still fills in but the loop filter never visits).
13683 // Confirmed against the superres gate: with the margin included, the
13684 // last coded mi column's horizontal edges were filtered when libaom's
13685 // real output leaves them untouched (r6's post-deblock diff, 37 px, all
13686 // in columns 44-47); clipping here closes it (3/3 frames pixel-exact).
13687 // lane-golomb r9: the bound is the MI-ROUNDED frame, not the coded
13688 // frame. libaom's `av1_filter_block_plane_vert/horz` walk the superblock
13689 // and stop at `cm->mi_params.mi_cols`/`mi_rows`, which
13690 // `av1_set_mb_mi` derives from `ALIGN_POWER_OF_TWO(width, 3)` -- the
13691 // 8-pixel-aligned frame, i.e. a 68-wide frame is filtered out to column
13692 // 72 and the vertical edge AT x=68 is a real edge that rewrites the
13693 // in-crop columns 64..67. Clipping at `frame_width` skipped it, which is
13694 // the +-1 straddling-band defect (68x192 cq35, frame 1, 141 luma pixels
13695 // all in columns 64..67; frame 0 survived because that edge carried no
13696 // filter level there). r7's superres measurement is preserved: its frame
13697 // was already 8-aligned, so this bound equals `frame_width` there and
13698 // still excludes the superblock padding up to `true_width`.
13699 let (cw, ch) = if chroma {
13700 (frame_width.div_ceil(2), frame_height.div_ceil(2))
13701 } else {
13702 (frame_width, frame_height)
13703 };
13704 let (tw, th, stride) = (
13705 plane.true_width.min(cw),
13706 plane.true_height.min(ch),
13707 plane.width,
13708 );
13709 if std::env::var_os("EC_AV1_DEBLOCK_TRACE_V").is_some() {
13710 eprintln!("DEBLOCK plane={plane_idx} tw={tw} th={th} stride={stride} true={}x{} crop={cw}x{ch}", plane.true_width, plane.true_height);
13711 }
13712 let mut y0 = 0usize;
13713 while y0 < th {
13714 let mut x0 = 4usize;
13715 while x0 < tw {
13716 if let Some((len, level)) = edge_params(lf, n, plane_idx, 0, chroma, x0, y0) {
13717 if std::env::var_os("EC_AV1_DEBLOCK_TRACE_V").is_some() && plane_idx == 0 {
13718 eprintln!("VEDGE x0={x0} y0={y0} len={len} level={level}");
13719 }
13720 filter_edge(
13721 &mut plane.data,
13722 y0 * stride + x0,
13723 stride as isize,
13724 1,
13725 len,
13726 level,
13727 lf.sharpness,
13728 );
13729 }
13730 x0 += 4;
13731 }
13732 y0 += 4;
13733 }
13734 let mut x0 = 0usize;
13735 while x0 < tw {
13736 let mut y0 = 4usize;
13737 while y0 < th {
13738 if let Some((len, level)) = edge_params(lf, n, plane_idx, 1, chroma, x0, y0) {
13739 if std::env::var_os("EC_AV1_DEBLOCK_TRACE").is_some()
13740 && plane_idx == 0
13741 && x0 == 44
13742 {
13743 eprintln!(
13744 "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}",
13745 lf.sharpness
13746 );
13747 }
13748 filter_edge(
13749 &mut plane.data,
13750 y0 * stride + x0,
13751 1,
13752 stride as isize,
13753 len,
13754 level,
13755 lf.sharpness,
13756 );
13757 }
13758 y0 += 4;
13759 }
13760 x0 += 4;
13761 }
13762}
13763
13764fn apply_cdef(
13765 y: &mut PlaneBuf,
13766 u: &mut PlaneBuf,
13767 v: &mut PlaneBuf,
13768 cdef: &CdefParams,
13769 skip_grid: &Neighbours,
13770 // This frame header's own CROPPED luma size, for the straddling-unit
13771 // counter only -- CDEF itself walks the mi-rounded plane.
13772 (frame_w, frame_h): (usize, usize),
13773) {
13774 // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling.
13775 if std::env::var_os("EC_AV1_DEBUG_SKIP_CDEF").is_some() {
13776 return;
13777 }
13778 // `cdef.bits == 0` still means "no filtering at all" whenever the single
13779 // (index 0) strength pair is all-zero -- the fast path every existing
13780 // gate stream takes. A `bits > 0` frame can still be all-zero-strength
13781 // at every index, but that is rare enough not to special-case; the
13782 // per-superblock lookup below degrades to the same index-0 read anyway
13783 // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`).
13784 if cdef.bits == 0
13785 && cdef.y_pri_strength[0] == 0
13786 && cdef.y_sec_strength[0] == 0
13787 && cdef.uv_pri_strength[0] == 0
13788 && cdef.uv_sec_strength[0] == 0
13789 {
13790 return;
13791 }
13792 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
13793 let idx_grid = CDEF_IDX_GRID.with(|g| g.borrow().clone());
13794 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
13795 if sb_cols == 0 {
13796 return 0;
13797 }
13798 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
13799 idx_grid
13800 .get(sb_r * sb_cols + sb_c)
13801 .copied()
13802 .unwrap_or(0) as usize
13803 };
13804 let src_y = y.data.clone();
13805 let src_u = u.data.clone();
13806 let src_v = v.data.clone();
13807 // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`,
13808 // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`.
13809 let coeff_shift = i32::from(bit_depth()) - 8;
13810 let damping = i32::from(cdef.damping) + coeff_shift;
13811 let damping_uv = (damping - 1).max(0);
13812 let mut mi_r = 0usize;
13813 while mi_r < skip_grid.mi_rows {
13814 let mut mi_c = 0usize;
13815 while mi_c < skip_grid.mi_cols {
13816 if skip_grid.is_skip_txfm(mi_r, mi_c) {
13817 CDEF_SKIPPED_UNITS.with(|c| c.set(c.get() + 1));
13818 }
13819 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
13820 let sidx = strength_idx(mi_r, mi_c);
13821 let (ox, oy) = (mi_c * 4, mi_r * 4);
13822 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
13823 let sample_y = |r: i32, c: i32| -> i32 {
13824 let (ny, nx) = (oy as i32 + r, ox as i32 + c);
13825 if ny < 0 || nx < 0 || ny as usize >= y_true_h || nx as usize >= y_true_w {
13826 CDEF_VERY_LARGE
13827 } else {
13828 i32::from(src_y[ny as usize * y_stride + nx as usize])
13829 }
13830 };
13831 // lane-cdef r1: the direction search reads the SAME padded
13832 // block the taps do -- libaom runs `cdef_find_dir` on the
13833 // prepared filter block (`cdef_block.c:296-320` over
13834 // `cdef_prepare_fb`'s buffer, `cdef.c:249-256`), whose columns
13835 // and rows past the mi-rounded frame extent are CDEF_VERY_LARGE.
13836 // Clamping to the last real sample instead made every straddling
13837 // edge 8x8 (odd `mi_cols`/`mi_rows`) pick a different var, hence
13838 // a different `adjust_strength`, hence a +-1 band at the crop edge.
13839 let (dir, var) = cdef_find_dir(coeff_shift, |r, c| sample_y(r as i32, c as i32));
13840
13841 // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
13842 // -- each plane zeroes the shared direction when *its own*
13843 // frame-level primary strength is 0, independent of the
13844 // per-block adjusted `t` and of the other plane's strength.
13845 let y_pri_strength = i32::from(cdef.y_pri_strength[sidx]) << coeff_shift;
13846 let y_sec_strength = i32::from(cdef.y_sec_strength[sidx]) << coeff_shift;
13847 let y_dir = if y_pri_strength != 0 { dir } else { 0 };
13848 let t = cdef_adjust_strength(y_pri_strength, var);
13849 // lane-cdef r1 rung: one line per filtered 8x8 luma CDEF unit.
13850 if std::env::var_os("EC_AV1_CDEF_DBG").is_some() {
13851 eprintln!(
13852 "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}"
13853 );
13854 }
13855 let enable_primary = t != 0;
13856 let enable_secondary = y_sec_strength != 0;
13857 if (ox + 8 > frame_w || oy + 8 > frame_h)
13858 && (enable_primary
13859 || enable_secondary
13860 || cdef.uv_pri_strength[sidx] != 0
13861 || cdef.uv_sec_strength[sidx] != 0)
13862 {
13863 CDEF_STRADDLE_UNITS.with(|c| c.set(c.get() + 1));
13864 }
13865 if enable_primary || enable_secondary {
13866 cdef_filter_block(
13867 sample_y,
13868 y,
13869 ox,
13870 oy,
13871 8,
13872 8,
13873 t,
13874 y_sec_strength,
13875 y_dir,
13876 damping,
13877 damping,
13878 enable_primary,
13879 enable_secondary,
13880 coeff_shift,
13881 );
13882 }
13883
13884 let t_uv = i32::from(cdef.uv_pri_strength[sidx]) << coeff_shift;
13885 let uv_sec_strength = i32::from(cdef.uv_sec_strength[sidx]) << coeff_shift;
13886 let uv_dir = if t_uv != 0 { dir } else { 0 };
13887 let enable_primary_uv = t_uv != 0;
13888 let enable_secondary_uv = uv_sec_strength != 0;
13889 if enable_primary_uv || enable_secondary_uv {
13890 let (cox, coy) = (ox / 2, oy / 2);
13891 for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] {
13892 let (tw, th) = (plane.true_width, plane.true_height);
13893 let stride = plane.width;
13894 let sample_uv = |r: i32, c: i32| -> i32 {
13895 let (ny, nx) = (coy as i32 + r, cox as i32 + c);
13896 if ny < 0 || nx < 0 || ny as usize >= th || nx as usize >= tw {
13897 CDEF_VERY_LARGE
13898 } else {
13899 i32::from(src_p[ny as usize * stride + nx as usize])
13900 }
13901 };
13902 cdef_filter_block(
13903 sample_uv,
13904 plane,
13905 cox,
13906 coy,
13907 4,
13908 4,
13909 t_uv,
13910 uv_sec_strength,
13911 uv_dir,
13912 damping_uv,
13913 damping_uv,
13914 enable_primary_uv,
13915 enable_secondary_uv,
13916 coeff_shift,
13917 );
13918 }
13919 }
13920 }
13921 mi_c += 2;
13922 }
13923 mi_r += 2;
13924 }
13925}
13926
13927/// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
13928/// ordering note: libaom also runs `superres_post_decode` between the two,
13929/// but this decoder never implements super-resolution, so there is nothing
13930/// to interleave). `deblocked_*` is each plane's post-deblock, pre-CDEF
13931/// buffer (the caller clones it before calling [`apply_cdef`]) -- loop
13932/// restoration's stripe-boundary rows read from it instead of the
13933/// CDEF-filtered plane, per `restoration.rs`'s own `lr_sample` doc comment.
13934#[allow(clippy::too_many_arguments)]
13935fn apply_loop_restoration(
13936 y: &mut PlaneBuf,
13937 u: &mut PlaneBuf,
13938 v: &mut PlaneBuf,
13939 deblocked_y: &PlaneBuf,
13940 deblocked_u: &PlaneBuf,
13941 deblocked_v: &PlaneBuf,
13942 lr: &LoopRestorationParams,
13943 grid: &crate::restoration::RestorationGrid,
13944 // lane-golomb r8: this frame header's own (cropped) luma size. Loop
13945 // restoration is the ONE post-decode filter that does NOT run over the
13946 // mi-rounded plane: libaom's `av1_loop_restoration_filter_frame` sizes
13947 // every plane with `av1_get_upsampled_plane_size` -- `plane_w =
13948 // ROUND_POWER_OF_TWO(cm->superres_upscaled_width, ss_x)`, `plane_h =
13949 // ROUND_POWER_OF_TWO(cm->height, ss_y)` (`av1/common/restoration.c:47`)
13950 // -- and asserts it equals the buffer's CROP width
13951 // (`restoration.c:1106`), then `av1_extend_frame(..., plane_w, plane_h,
13952 // ...)` (`restoration.c:1109`) replicates the right/bottom border from
13953 // that cropped edge before any unit is filtered. Deblock and CDEF DO
13954 // walk the mi grid, which is why passing `true_width`/`true_height`
13955 // here went unnoticed until a frame whose size is not a multiple of 8
13956 // (68 -> mi-rounded 72): the LR taps at the last four real columns then
13957 // read this decoder's own decoded samples at columns 68..71 where
13958 // libaom reads column 67 replicated -- +-1 over the straddling band
13959 // (class av1-truesize-lane: true frame size vs mi-rounded).
13960 (frame_w, frame_h): (usize, usize),
13961) {
13962 y.data = crate::restoration::apply_loop_restoration_plane(
13963 &y.data,
13964 &deblocked_y.data,
13965 y.width,
13966 frame_w,
13967 frame_h,
13968 0,
13969 lr.frame_restoration_type[0],
13970 lr.loop_restoration_size[0],
13971 grid,
13972 0,
13973 );
13974 u.data = crate::restoration::apply_loop_restoration_plane(
13975 &u.data,
13976 &deblocked_u.data,
13977 u.width,
13978 frame_w.div_ceil(2),
13979 frame_h.div_ceil(2),
13980 1,
13981 lr.frame_restoration_type[1],
13982 lr.loop_restoration_size[1],
13983 grid,
13984 1,
13985 );
13986 v.data = crate::restoration::apply_loop_restoration_plane(
13987 &v.data,
13988 &deblocked_v.data,
13989 v.width,
13990 frame_w.div_ceil(2),
13991 frame_h.div_ceil(2),
13992 1,
13993 lr.frame_restoration_type[2],
13994 lr.loop_restoration_size[2],
13995 grid,
13996 2,
13997 );
13998}
13999
14000/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
14001/// returning the picture it reconstructs to.
14002///
14003/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
14004/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
14005/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
14006/// `compute_image_size` derives one from the other, but not losslessly: a
14007/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
14008/// what the reconstruction is cropped to on the way out, mirroring
14009/// [`crate::encode::crop_encoded`].
14010///
14011/// # Errors
14012/// Returns an error when a block's partition, mode, skip flag or transform
14013/// type is anything this decoder does not reconstruct (round 2: inter, tx
14014/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
14015/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
14016/// or when the tile payload runs out of the symbols this decode expects (a
14017/// genuinely foreign stream).
14018pub fn decode_key_frame_tile(
14019 data: &[u8],
14020 mi_cols: u32,
14021 mi_rows: u32,
14022 base_q_idx: u8,
14023 frame_width: u32,
14024 frame_height: u32,
14025 enable_filter_intra: bool,
14026 cdef: &CdefParams,
14027 loop_filter: &LoopFilterParams,
14028 tx_select: bool,
14029 reduced_tx_set: bool,
14030 allow_screen_content_tools: bool,
14031 allow_intrabc: bool,
14032) -> Result<Picture> {
14033 let delta = DeltaParams::default();
14034 let single_tile = TileInfo {
14035 mi_col_starts: vec![0, mi_cols],
14036 mi_row_starts: vec![0, mi_rows],
14037 ..TileInfo::default()
14038 };
14039 decode_key_frame_tile_with_cdfs(
14040 &[data],
14041 &single_tile,
14042 mi_cols,
14043 mi_rows,
14044 base_q_idx,
14045 crate::quant::QuantDeltas::default(),
14046 frame_width,
14047 frame_height,
14048 enable_filter_intra,
14049 false,
14050 cdef,
14051 loop_filter,
14052 &LoopRestorationParams::default(),
14053 None,
14054 tx_select,
14055 reduced_tx_set,
14056 allow_screen_content_tools,
14057 allow_intrabc,
14058 delta,
14059 )
14060 .map(|(picture, _)| picture)
14061}
14062
14063thread_local! {
14064 /// lane-superres r3: the real decoded margin beyond `frame_width` up to
14065 /// the mi-aligned `true_width`, set by the most recent
14066 /// [`decode_key_frame_tile_with_cdfs`] OR (lane-superres r10)
14067 /// [`decode_inter_frame_tile_with_cdfs`] call -- both frame kinds crop
14068 /// their reconstructed buffer down from the same mi-aligned extent, so
14069 /// they share this one slot. See each function's own comment at its
14070 /// write site. `None` when there was no margin to save.
14071 static LAST_FRAME_WIDE_MARGIN: std::cell::RefCell<Option<Picture>> =
14072 const { std::cell::RefCell::new(None) };
14073}
14074
14075/// The margin the most recent key- or inter-frame tile decode stashed
14076/// (see [`LAST_FRAME_WIDE_MARGIN`]) -- `stream.rs`'s superres path
14077/// reads this immediately after the call, before any other frame
14078/// decode can overwrite it.
14079pub(crate) fn take_last_frame_wide_margin() -> Option<Picture> {
14080 LAST_FRAME_WIDE_MARGIN.with(|m| m.borrow_mut().take())
14081}
14082
14083/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
14084/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
14085/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
14086/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs,
14087/// since a key frame's own header always forces `primary_ref_frame ==
14088/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table
14089/// alongside the picture, for the caller to save into whichever reference
14090/// slots this frame's `refresh_frame_flags` names.
14091/// The order the 64x64 superblock quadrants of a tile are decoded in.
14092///
14093/// At `sb_size == 64` this is plain raster order over the tile's own
14094/// superblock grid. At `sb_size == 128` libaom's `decode_partition` recurses
14095/// each 128x128 superblock in raster order and visits its four 64x64
14096/// quadrants (TL, TR, BL, BR) before moving to the next superblock, so the
14097/// 64-level bodies must run in that nested order. `row_start` marks the first
14098/// item of each *superblock* row (where the left neighbour context resets),
14099/// `sb_start` the first item of each superblock (where the 128 root's own
14100/// loop-restoration units and partition symbol are read).
14101fn sb_visit_order(r0: u32, r1: u32, c0: u32, c1: u32, sb128: bool) -> Vec<(u32, u32, bool, bool)> {
14102 let mut out = Vec::new();
14103 if !sb128 {
14104 for r in r0..r1 {
14105 for c in c0..c1 {
14106 out.push((r, c, c == c0, true));
14107 }
14108 }
14109 return out;
14110 }
14111 let mut r = r0;
14112 while r < r1 {
14113 let mut first_in_row = true;
14114 let mut c = c0;
14115 while c < c1 {
14116 let mut first_in_sb = true;
14117 for qr in 0..2 {
14118 for qc in 0..2 {
14119 let (rr, cc) = (r + qr, c + qc);
14120 if rr >= r1 || cc >= c1 {
14121 continue;
14122 }
14123 out.push((rr, cc, first_in_row, first_in_sb));
14124 first_in_row = false;
14125 first_in_sb = false;
14126 }
14127 }
14128 c += 2;
14129 }
14130 r += 2;
14131 }
14132 out
14133}
14134
14135/// lane-sb128 r2: the 128x128 superblock root, shared by the key-frame and
14136/// the inter tile loop. Its loop-restoration units are read once for the whole
14137/// 128x128 (spec 5.11.57 is called with the superblock's own size), then one
14138/// partition symbol off the `BLOCK_128X128` CDF (8 symbols, no HORZ_4/VERT_4)
14139/// decides the root -- only SPLIT recurses into the four 64x64 quadrants this
14140/// decoder codes, the other seven arms refuse by name.
14141#[allow(clippy::too_many_arguments)]
14142thread_local! {
14143 /// How many 128x128 superblock roots resolved to `PARTITION_NONE` -- one
14144 /// whole 128x128 block (lane-sb128b r1's gate counter).
14145 pub(crate) static PART128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
14146}
14147
14148/// [`PART128_NONE_HITS`], for a gate's own before/after delta.
14149pub(crate) fn part128_none_hits() -> usize {
14150 PART128_NONE_HITS.with(std::cell::Cell::get)
14151}
14152
14153thread_local! {
14154 /// How many CHROMA transform units were coded inside a block whose uv
14155 /// plane block is more than one unit (lane-sb128b r2 -- only a 128x128
14156 /// block, four per plane).
14157 pub(crate) static CHROMA_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
14158}
14159
14160/// [`CHROMA_SPLIT_TX_HITS`], for a gate's own before/after delta.
14161pub(crate) fn chroma_split_tx_hits() -> usize {
14162 CHROMA_SPLIT_TX_HITS.with(std::cell::Cell::get)
14163}
14164
14165fn read_sb128_root(
14166 dec: &mut SymbolDecoder,
14167 cdfs: &mut Cdfs,
14168 neighbours: &Neighbours,
14169 lr: &LoopRestorationParams,
14170 lr_grid: &mut crate::restoration::RestorationGrid,
14171 lr_reference: &mut [(
14172 crate::restoration::WienerInfo,
14173 crate::restoration::SgrprojInfo,
14174 ); 3],
14175 sb_r: u32,
14176 sb_c: u32,
14177 mi_cols: u32,
14178 mi_rows: u32,
14179) -> Result<usize> {
14180 let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI);
14181 crate::restoration::read_lr(
14182 dec,
14183 cdfs,
14184 lr,
14185 lr_grid,
14186 lr_reference,
14187 mi_r128,
14188 mi_c128,
14189 SB_MI * 2,
14190 );
14191 let at128 = ((mi_r128 / SUB_MI) as usize, (mi_c128 / SUB_MI) as usize);
14192 let ctx128 = neighbours.partition_ctx(at128, 128);
14193 let (has_cols128, has_rows128) = (mi_c128 + SB_MI < mi_cols, mi_r128 + SB_MI < mi_rows);
14194 let part128 = if has_cols128 && has_rows128 {
14195 PART128_SYMBOLS.with(|c| c.set(c.get() + 1));
14196 let p = dec.symbol(&mut cdfs.partition_w128[ctx128]);
14197 if std::env::var_os("EC_AV1_TRACE").is_some() {
14198 eprintln!("TRACE partition_w128 ctx={ctx128} value={p}");
14199 }
14200 p
14201 } else {
14202 // lane-sb128 r4: the gathered half-out-of-frame reads DECIDE the
14203 // partition, they are not a forced split -- exactly the discarded-bit
14204 // defect the 64 root carries a comment about at `partition_w64`'s
14205 // gathered arm. Value 1 is SPLIT; 0 is HORZ (rows out of frame) or
14206 // VERT (cols out of frame), which the refusal below then names
14207 // instead of silently reconstructing a split.
14208 PART128_GATHERED_SYMBOLS.with(|c| c.set(c.get() + 1));
14209 match (has_cols128, has_rows128) {
14210 (true, false) => {
14211 if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &VERT_ALIKE128)) == 1 {
14212 PARTITION_SPLIT
14213 } else {
14214 PARTITION_HORZ
14215 }
14216 }
14217 (false, true) => {
14218 if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &HORZ_ALIKE128)) == 1 {
14219 PARTITION_SPLIT
14220 } else {
14221 PARTITION_VERT
14222 }
14223 }
14224 _ => {
14225 PART128_GATHERED_SYMBOLS.with(|c| c.set(c.get() - 1));
14226 PARTITION_SPLIT
14227 }
14228 }
14229 };
14230 // lane-sb128b r1: `PARTITION_NONE` -- one 128x128 block -- is decoded by
14231 // the key-frame caller below. The six remaining arms (HORZ/VERT and the
14232 // four AB shapes) still need the rect/AB machinery at this size.
14233 if part128 != PARTITION_SPLIT && part128 != PARTITION_NONE {
14234 return Err(unsupported(
14235 "a 128x128 superblock HORZ/VERT or AB partition (only SPLIT and NONE are decoded at the 128 root)",
14236 ));
14237 }
14238 if part128 == PARTITION_SPLIT {
14239 PART128_SPLIT_HITS.with(|c| c.set(c.get() + 1));
14240 } else {
14241 PART128_NONE_HITS.with(|c| c.set(c.get() + 1));
14242 }
14243 Ok(part128)
14244}
14245
14246pub(crate) fn decode_key_frame_tile_with_cdfs(
14247 tiles: &[&[u8]],
14248 tile_info: &TileInfo,
14249 mi_cols: u32,
14250 mi_rows: u32,
14251 base_q_idx: u8,
14252 // lane-sbpart r11: this frame header's own per-plane DC/AC quantizer
14253 // deltas (spec 5.9.12), threaded to [`QUANT_DELTAS`] at the top of every
14254 // tile alongside [`CURRENT_Q_IDX`].
14255 deltas: crate::quant::QuantDeltas,
14256 frame_width: u32,
14257 frame_height: u32,
14258 enable_filter_intra: bool,
14259 enable_edge_filter: bool,
14260 cdef: &CdefParams,
14261 loop_filter: &LoopFilterParams,
14262 lr: &LoopRestorationParams,
14263 initial_cdfs: Option<Cdfs>,
14264 tx_select: bool,
14265 reduced_tx_set: bool,
14266 allow_screen_content_tools: bool,
14267 allow_intrabc: bool,
14268 // lane-realworld r4: this frame header's own `delta` (spec 5.9.17/5.9.18)
14269 // -- only `q_present`/`q_res` are actually read ([`maybe_read_delta_q`]);
14270 // `stream.rs` still refuses a frame with `lf_present` set before this
14271 // function is ever called.
14272 delta: DeltaParams,
14273) -> Result<(Picture, Cdfs)> {
14274 if mi_cols == 0 || mi_rows == 0 {
14275 return Err(unsupported("a frame with no mode-info grid"));
14276 }
14277 ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));
14278 let sb128 = sb128();
14279 if sb128 && allow_intrabc {
14280 return Err(unsupported(
14281 "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)",
14282 ));
14283 }
14284 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
14285 INTRABC_MI_GRID.with(|g| {
14286 *g.borrow_mut() = allow_intrabc.then(|| {
14287 (
14288 crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize),
14289 mi_cols as usize,
14290 mi_rows as usize,
14291 )
14292 });
14293 });
14294 INTRABC_DV.with(|c| c.set(None));
14295 CDEF_BITS.with(|c| c.set(cdef.bits));
14296 CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
14297 CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
14298 DELTA_Q_PRESENT.with(|c| c.set(delta.q_present));
14299 DELTA_Q_RES.with(|c| c.set(1i32 << delta.q_res));
14300 DELTA_LF_PRESENT.with(|c| c.set(delta.lf_present));
14301 DELTA_LF_RES.with(|c| c.set(1i32 << delta.lf_res));
14302 DELTA_LF_MULTI.with(|c| c.set(delta.lf_multi));
14303 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
14304 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
14305 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
14306
14307 let mut y = PlaneBuf {
14308 data: vec![0u16; width * height],
14309 width,
14310 height,
14311 true_width,
14312 true_height,
14313 tile_x0: 0,
14314 tile_y0: 0,
14315 tile_x1: width,
14316 tile_y1: height,
14317 };
14318 let mut u = PlaneBuf {
14319 data: vec![0u16; width * height / 4],
14320 width: width / 2,
14321 height: height / 2,
14322 true_width: true_width / 2,
14323 true_height: true_height / 2,
14324 tile_x0: 0,
14325 tile_y0: 0,
14326 tile_x1: width / 2,
14327 tile_y1: height / 2,
14328 };
14329 let mut v = PlaneBuf {
14330 data: vec![0u16; width * height / 4],
14331 width: width / 2,
14332 height: height / 2,
14333 true_width: true_width / 2,
14334 true_height: true_height / 2,
14335 tile_x0: 0,
14336 tile_y0: 0,
14337 tile_x1: width / 2,
14338 tile_y1: height / 2,
14339 };
14340
14341 let scan32 = default_scan(TX32);
14342 let scan16 = default_scan(TX16);
14343 let scan8 = default_scan(TX8);
14344 let scan4 = default_scan(TX4);
14345
14346 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
14347 let mut result_cdfs = base_cdfs.clone();
14348 let mut neighbours = Neighbours::new(
14349 cols32 as usize * 2,
14350 rows32 as usize * 2,
14351 mi_cols as usize,
14352 mi_rows as usize,
14353 );
14354 let mut lr_grid = crate::restoration::RestorationGrid::new(lr, frame_width, frame_height);
14355 let mut lr_reference = [(
14356 crate::restoration::WienerInfo::default(),
14357 crate::restoration::SgrprojInfo::default(),
14358 ); 3];
14359
14360 // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its
14361 // own byte range and its own fresh copy of the frame's initial CDFs
14362 // (spec 5.11.2 `decode_tile`'s `init_symbol`); only the tile named by
14363 // `context_update_tile_id` has its end-of-tile adapted table kept as the
14364 // frame's own output (spec `exit_symbol`) -- every other tile's
14365 // adaptation is discarded, matching the refusal this replaces.
14366 for (tile_idx, &tile_bytes) in tiles.iter().enumerate() {
14367 let tile_num = tile_idx as u32;
14368 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
14369 let mi_row0 = tile_info.mi_row_starts[trow as usize];
14370 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
14371 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
14372 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
14373 // Tile boundaries are always superblock-aligned in mi units (spec
14374 // 5.9.15's uniform/non-uniform derivation both only ever emit
14375 // multiples of the superblock's own mi size), so plain division is
14376 // exact here -- no rounding needed.
14377 // `mi_row0`/`mi_col0` (this tile's own start, `0` or an interior
14378 // tile boundary) are always superblock-aligned by spec 5.9.15; the
14379 // frame's own true final edge (`mi_row_starts`/`mi_col_starts`'
14380 // last entry) is not, so the upper bound needs `div_ceil` the same
14381 // way the whole-frame `sb_rows`/`sb_cols` above does, to keep the
14382 // trailing partial superblock row/column in scope.
14383 let (sb_r0, sb_r1) = ((mi_row0 / SB_MI).min(sb_rows), mi_row1.div_ceil(SB_MI).min(sb_rows));
14384 let (sb_c0, sb_c1) = ((mi_col0 / SB_MI).min(sb_cols), mi_col1.div_ceil(SB_MI).min(sb_cols));
14385
14386 let mut cdfs = base_cdfs.clone();
14387 // spec `decode_tile`: `CurrentQIndex` resets to the frame's own
14388 // `base_q_idx` at the top of every tile, not once per frame.
14389 CURRENT_Q_IDX.with(|c| c.set(i32::from(base_q_idx)));
14390 QUANT_DELTAS.with(|c| c.set(deltas));
14391 CURRENT_DELTA_LF.with(|c| c.set([0; 4]));
14392 if std::env::var_os("EC_AV1_TRACE").is_some() {
14393 eprintln!(
14394 "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
14395 tile_bytes.len(),
14396 &tile_bytes[..tile_bytes.len().min(8)]
14397 );
14398 }
14399 let mut dec = SymbolDecoder::new(tile_bytes);
14400 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize);
14401 y.set_tile_origin(
14402 mi_col0 as usize * 4,
14403 mi_row0 as usize * 4,
14404 (mi_col1 as usize * 4).min(y.width),
14405 (mi_row1 as usize * 4).min(y.height),
14406 );
14407 u.set_tile_origin(
14408 mi_col0 as usize * 2,
14409 mi_row0 as usize * 2,
14410 (mi_col1 as usize * 2).min(u.width),
14411 (mi_row1 as usize * 2).min(u.height),
14412 );
14413 v.set_tile_origin(
14414 mi_col0 as usize * 2,
14415 mi_row0 as usize * 2,
14416 (mi_col1 as usize * 2).min(v.width),
14417 (mi_row1 as usize * 2).min(v.height),
14418 );
14419 TILE_HITS.with(|c| c.set(c.get() + 1));
14420
14421 // lane-sb128b r1: set when the 128 root resolved to `PARTITION_NONE` --
14422 // its one block covers all four 64x64 quadrants, so the remaining three
14423 // visits of this superblock code nothing at all.
14424 let mut sb128_none = false;
14425 for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) {
14426 if row_start {
14427 neighbours.start_row();
14428 }
14429 if sb_start {
14430 sb128_none = false;
14431 }
14432 if sb128_none {
14433 continue;
14434 }
14435 {
14436 // lane-sb128 r1: the 128 root. Its loop-restoration units are read
14437 // once for the whole 128x128 (spec 5.11.57 is called with the
14438 // superblock's own size), then one partition symbol off the
14439 // `BLOCK_128X128` CDF (8 symbols) decides the root -- only SPLIT
14440 // recurses into the four 64x64 quadrants this decoder codes.
14441 if sb128 && sb_start {
14442 let part128 = read_sb128_root(
14443 &mut dec,
14444 &mut cdfs,
14445 &neighbours,
14446 lr,
14447 &mut lr_grid,
14448 &mut lr_reference,
14449 sb_r,
14450 sb_c,
14451 mi_cols,
14452 mi_rows,
14453 )?;
14454 if part128 == PARTITION_NONE {
14455 // One 128x128 intra block: four TX_64X64 luma units and a
14456 // single 64x64 chroma unit per plane (`av1_get_max_uv_txsize`
14457 // of a 128x128 block is TX_64X64 over its 64x64 uv plane
14458 // block). No CfL, no filter intra, no palette at this size --
14459 // [`read_intra_mode`]'s own size gates already say so.
14460 sb128_none = true;
14461 CDEF_TRANSMITTED.with(|c| c.set(false));
14462 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
14463 decode_block(
14464 &mut dec,
14465 &mut cdfs,
14466 &mut neighbours,
14467 at128,
14468 SB * 2,
14469 TxbSet::Luma64,
14470 TxbSet::Chroma32,
14471 TX32,
14472 TX32,
14473 (&scan32, &scan32),
14474 false,
14475 &mut y,
14476 &mut u,
14477 &mut v,
14478 base_q_idx,
14479 enable_filter_intra,
14480 allow_screen_content_tools,
14481 allow_intrabc,
14482 &scan32,
14483 &scan16,
14484 &scan8,
14485 &scan4,
14486 tx_select,
14487 reduced_tx_set,
14488 )?;
14489 // libaom writes one `cdef_strength` into the block's own
14490 // `MB_MODE_INFO`, which every mi cell of the block --
14491 // hence all four 64x64 CDEF units -- points at; our grid
14492 // is per-unit, so the read (which only ever lands in the
14493 // top-left unit, `read_cdef`'s index 0) is copied across.
14494 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
14495 CDEF_IDX_GRID.with(|g| {
14496 let mut g = g.borrow_mut();
14497 let cols = CDEF_SB_COLS.with(|c| c.get());
14498 if cols > 0 && q_r * cols + q_c < g.len() {
14499 let idx = g[q_r * cols + q_c];
14500 for (dr, dc) in [(0, 1), (1, 0), (1, 1)] {
14501 let i = (q_r + dr) * cols + q_c + dc;
14502 if q_c + dc < cols && i < g.len() {
14503 g[i] = idx;
14504 }
14505 }
14506 }
14507 });
14508 continue;
14509 }
14510 }
14511 if !sb128 {
14512 crate::restoration::read_lr(
14513 &mut dec,
14514 &mut cdfs,
14515 lr,
14516 &mut lr_grid,
14517 &mut lr_reference,
14518 sb_r * SB_MI,
14519 sb_c * SB_MI,
14520 SB_MI,
14521 );
14522 }
14523 CDEF_TRANSMITTED.with(|c| c.set(false));
14524 let at = (sb_r as usize * 4, sb_c as usize * 4);
14525 let ctx = neighbours.partition_ctx(at, SB);
14526 let (has_cols, has_rows) = (
14527 sb_c * SB_MI + SB_MI / 2 < mi_cols,
14528 sb_r * SB_MI + SB_MI / 2 < mi_rows,
14529 );
14530 // Recomputed at this superblock's own half (spec
14531 // `decode_partition`): a full alphabet symbol when both halves are
14532 // inside the true frame, a single gathered bit when just one is
14533 // (the superblock cannot be left whole, so this is forced split),
14534 // and nothing at all (SPLIT inferred, no bits) when neither is —
14535 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
14536 // three-way write exactly.
14537 let part = if has_cols && has_rows {
14538 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
14539 if std::env::var_os("EC_AV1_TRACE").is_some() {
14540 eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
14541 }
14542 p
14543 } else {
14544 // lane-hgkf r1 (class `parsed-then-discarded`, same finding as
14545 // the unmerged lane-golomb r1): the gathered bit IS the
14546 // partition -- libaom `ec_read_partition_impl` returns
14547 // PARTITION_HORZ (resp. VERT) for 0 and only SPLIT for 1.
14548 // Forcing SPLIT desynced the last superblock row of every
14549 // frame whose height is not a multiple of 64: the ReelB key frames (3840x1608) diverge at mi_row=400 mi_col=0,
14550 // the first block of that row.
14551 match (has_cols, has_rows) {
14552 (true, false) => {
14553 trace_edge((sb_r * SB_MI) as usize, (sb_c * SB_MI) as usize, 12, ctx, dec.debug_state().0 as u32);
14554 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
14555 bump_edge32(4 + b.min(1) as usize);
14556 bump_edge_part(b.min(1) as usize);
14557 if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ }
14558 }
14559 (false, true) => {
14560 trace_edge((sb_r * SB_MI) as usize, (sb_c * SB_MI) as usize, 12, ctx, dec.debug_state().0 as u32);
14561 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
14562 bump_edge32(4 + b.min(1) as usize);
14563 bump_edge_part(b.min(1) as usize);
14564 if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT }
14565 }
14566 _ => PARTITION_SPLIT,
14567 }
14568 };
14569 match part {
14570 PARTITION_NONE => {
14571 decode_block(
14572 &mut dec,
14573 &mut cdfs,
14574 &mut neighbours,
14575 at,
14576 SB,
14577 TxbSet::Luma64,
14578 TxbSet::Chroma32,
14579 TX32,
14580 TX32,
14581 (&scan32, &scan32),
14582 false,
14583 &mut y,
14584 &mut u,
14585 &mut v,
14586 base_q_idx,
14587 enable_filter_intra,
14588 allow_screen_content_tools,
14589 allow_intrabc,
14590 &scan32,
14591 &scan16,
14592 &scan8,
14593 &scan4,
14594 tx_select,
14595 reduced_tx_set,
14596 )?;
14597 }
14598 PARTITION_SPLIT => {
14599 for q in 0..4 {
14600 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
14601 if r32 >= rows32 || c32 >= cols32 {
14602 continue;
14603 }
14604 let at32 = (r32 as usize * 2, c32 as usize * 2);
14605 let ctx32 = neighbours.partition_ctx(at32, BLOCK);
14606 let (has_cols32, has_rows32) = (
14607 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
14608 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
14609 );
14610 let part32 = if has_cols32 && has_rows32 {
14611 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
14612 if std::env::var_os("EC_AV1_TRACE").is_some() {
14613 let (rng, _) = dec.debug_state();
14614 eprintln!(
14615 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p} rng={rng}",
14616 r32 * BLOCK_MI,
14617 c32 * BLOCK_MI
14618 );
14619 }
14620 p
14621 } else {
14622 // lane-hgkf r1: the 32-level frame-edge bit is the
14623 // partition too (same libaom reader as the
14624 // superblock level above).
14625 match (has_cols32, has_rows32) {
14626 (true, false) => {
14627 trace_edge((r32 * BLOCK_MI) as usize, (c32 * BLOCK_MI) as usize, 9, ctx32, dec.debug_state().0 as u32);
14628 let b = dec.symbol_fixed(&gather(
14629 &cdfs.partition_w32[ctx32],
14630 VERT_ALIKE,
14631 ));
14632 bump_edge32(b.min(1) as usize);
14633 bump_edge_part(2 + b.min(1) as usize);
14634 if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ }
14635 }
14636 (false, true) => {
14637 trace_edge((r32 * BLOCK_MI) as usize, (c32 * BLOCK_MI) as usize, 9, ctx32, dec.debug_state().0 as u32);
14638 let b = dec.symbol_fixed(&gather(
14639 &cdfs.partition_w32[ctx32],
14640 HORZ_ALIKE,
14641 ));
14642 bump_edge32(b.min(1) as usize);
14643 bump_edge_part(2 + b.min(1) as usize);
14644 if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT }
14645 }
14646 _ => PARTITION_SPLIT,
14647 }
14648 };
14649 match part32 {
14650 PARTITION_NONE => {
14651 decode_block(
14652 &mut dec,
14653 &mut cdfs,
14654 &mut neighbours,
14655 at32,
14656 BLOCK,
14657 TxbSet::Luma32,
14658 TxbSet::Chroma16,
14659 TX32,
14660 TX16,
14661 (&scan32, &scan16),
14662 true,
14663 &mut y,
14664 &mut u,
14665 &mut v,
14666 base_q_idx,
14667 enable_filter_intra,
14668 allow_screen_content_tools,
14669 allow_intrabc,
14670 &scan32,
14671 &scan16,
14672 &scan8,
14673 &scan4,
14674 tx_select,
14675 reduced_tx_set,
14676 )?;
14677 }
14678 PARTITION_SPLIT => {
14679 for sub in 0..4 {
14680 let (sr, sc) =
14681 (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
14682 if (sr as u32) * SUB_MI >= mi_rows
14683 || (sc as u32) * SUB_MI >= mi_cols
14684 {
14685 continue;
14686 }
14687 let (has_cols16, has_rows16) = (
14688 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
14689 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
14690 );
14691 let at16 = (sr, sc);
14692 let ctx16 = neighbours.partition_ctx(at16, SUB);
14693 if has_cols16 && has_rows16 {
14694 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
14695 if std::env::var_os("EC_AV1_TRACE").is_some() {
14696 eprintln!(
14697 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}",
14698 at16.0, at16.1
14699 );
14700 }
14701 if part16 == PARTITION_NONE {
14702 decode_block(
14703 &mut dec,
14704 &mut cdfs,
14705 &mut neighbours,
14706 at16,
14707 SUB,
14708 TxbSet::Luma16,
14709 TxbSet::Chroma8,
14710 TX16,
14711 TX8,
14712 (&scan16, &scan8),
14713 true,
14714 &mut y,
14715 &mut u,
14716 &mut v,
14717 base_q_idx,
14718 enable_filter_intra,
14719 allow_screen_content_tools,
14720 allow_intrabc,
14721 &scan32,
14722 &scan16,
14723 &scan8,
14724 &scan4,
14725 tx_select,
14726 reduced_tx_set,
14727 )?;
14728 continue;
14729 }
14730 if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part16) {
14731 // lane-ab16 r1: the four AB (T-shaped) partitions at the 16x16
14732 // level -- two 8x8 squares plus one 16x8/8x16 strip. libaom's
14733 // `decode_partition` visit order (decodeframe.c):
14734 // HORZ_A: TL 8x8, TR 8x8, bottom 16x8
14735 // HORZ_B: top 16x8, BL 8x8, BR 8x8
14736 // VERT_A: TL 8x8, BL 8x8, right 8x16
14737 // VERT_B: left 8x16, TR 8x8, BR 8x8
14738 // The squares go through `decode_leaf8`, the strip through
14739 // `decode_leaf_rect` (real, non-skip 16x8/8x16 coefficients --
14740 // lane-rectx r2-r4; the older `decode_block_rect` this VERT_B arm
14741 // used refuses the non-skip case at this size). Both writers keep
14742 // mi-granular mode/skip/palette records, so a later block's
14743 // `above_mi`/`left_mi` sees the real sub-block, not the coarse
14744 // 16x16 cell.
14745 //
14746 // VERT_A/VERT_B visit TL,BL,TR,BR, so the bottom-left square's
14747 // top-right neighbour is the partition's own not-yet-decoded
14748 // rectangle: libaom switches those squares onto `has_tr_vert_*`/
14749 // `has_bl_vert_*` (`reconintra.c` `get_has_tr_table`), which is
14750 // `Reach::vert_ab_partition()` (lane-part32 r5, cherry-picked here).
14751 let arm = part16 - PARTITION_HORZ_A;
14752 bump_ab16(arm);
14753 if part16 == PARTITION_VERT_B {
14754 VERT_B_INTRA_HITS.with(|c| c.set(c.get() + 1));
14755 }
14756 let _vert_guard = if part16 == PARTITION_VERT_A || part16 == PARTITION_VERT_B {
14757 Some(crate::encode::Reach::vert_ab_partition())
14758 } else {
14759 None
14760 };
14761 let (mi_row0, mi_col0) = (sr * SUB_MI as usize, sc * SUB_MI as usize);
14762 macro_rules! ab_leaf8 {
14763 ($mi:expr, $prev:expr) => {
14764 decode_leaf8(
14765 &mut dec,
14766 &mut cdfs,
14767 &mut neighbours,
14768 at16,
14769 $mi,
14770 (&scan8, &scan4),
14771 $prev,
14772 &mut y,
14773 &mut u,
14774 &mut v,
14775 base_q_idx,
14776 enable_filter_intra,
14777 allow_screen_content_tools,
14778 allow_intrabc,
14779 tx_select,
14780 reduced_tx_set,
14781 )?
14782 };
14783 }
14784 macro_rules! ab_strip {
14785 ($mi:expr, $bw:expr, $bh:expr, $prev:expr) => {
14786 decode_leaf_rect(
14787 &mut dec,
14788 &mut cdfs,
14789 &mut neighbours,
14790 at16,
14791 $mi,
14792 $bw,
14793 $bh,
14794 $prev,
14795 &mut y,
14796 &mut u,
14797 &mut v,
14798 enable_filter_intra,
14799 allow_screen_content_tools,
14800 base_q_idx,
14801 tx_select,
14802 reduced_tx_set,
14803 )?
14804 };
14805 }
14806 let tl = (mi_row0, mi_col0);
14807 let tr = (mi_row0, mi_col0 + 2);
14808 let bl = (mi_row0 + 2, mi_col0);
14809 let br = (mi_row0 + 2, mi_col0 + 2);
14810 let mut done: Vec<((usize, usize), usize)> = Vec::new();
14811 match part16 {
14812 PARTITION_HORZ_A => {
14813 let m_tl = ab_leaf8!(tl, done.last().copied());
14814 done.push((tl, m_tl));
14815 let m_tr = ab_leaf8!(tr, done.last().copied());
14816 done.push((tr, m_tr));
14817 let m_bot = ab_strip!(bl, 16, 8, Some((tl, m_tl)));
14818 done.push((bl, m_bot));
14819 }
14820 PARTITION_HORZ_B => {
14821 let m_top = ab_strip!(tl, 16, 8, None);
14822 done.push((tl, m_top));
14823 let m_bl = ab_leaf8!(bl, done.last().copied());
14824 done.push((bl, m_bl));
14825 let m_br = ab_leaf8!(br, done.last().copied());
14826 done.push((br, m_br));
14827 }
14828 PARTITION_VERT_A => {
14829 let m_tl = ab_leaf8!(tl, done.last().copied());
14830 done.push((tl, m_tl));
14831 let m_bl = ab_leaf8!(bl, done.last().copied());
14832 done.push((bl, m_bl));
14833 let m_right = ab_strip!(tr, 8, 16, Some((tl, m_tl)));
14834 done.push((tr, m_right));
14835 }
14836 _ => {
14837 let m_left = ab_strip!(tl, 8, 16, None);
14838 done.push((tl, m_left));
14839 let m_tr = ab_leaf8!(tr, done.last().copied());
14840 done.push((tr, m_tr));
14841 let m_br = ab_leaf8!(br, done.last().copied());
14842 done.push((br, m_br));
14843 }
14844 }
14845 // Same coarse-slot write-back the real SPLIT path takes: the
14846 // 16x16 cell's single `above_mode`/`left_mode` entry gets the
14847 // sub-block on the parent's bottom / right edge (the mi-exact map
14848 // above wins wherever it has an entry).
14849 write_back_split_modes(&mut neighbours, &done, (mi_row0, mi_col0), (sr, sc));
14850 continue;
14851 }
14852 if part16 == PARTITION_HORZ {
14853 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
14854 let (mi_row0, mi_col0) = (
14855 sr as u32 * SUB_MI,
14856 sc as u32 * SUB_MI,
14857 );
14858 let top = (mi_row0 as usize, mi_col0 as usize);
14859 let bot = (mi_row0 as usize + 2, mi_col0 as usize);
14860 let mode_top = decode_leaf_rect(
14861 &mut dec,
14862 &mut cdfs,
14863 &mut neighbours,
14864 at16,
14865 top,
14866 16,
14867 8,
14868 None,
14869 &mut y,
14870 &mut u,
14871 &mut v,
14872 enable_filter_intra,
14873 allow_screen_content_tools,
14874 base_q_idx,
14875 tx_select,
14876 reduced_tx_set,
14877 )?;
14878 let mode_bot = decode_leaf_rect(
14879 &mut dec,
14880 &mut cdfs,
14881 &mut neighbours,
14882 at16,
14883 bot,
14884 16,
14885 8,
14886 Some((top, mode_top)),
14887 &mut y,
14888 &mut u,
14889 &mut v,
14890 enable_filter_intra,
14891 allow_screen_content_tools,
14892 base_q_idx,
14893 tx_select,
14894 reduced_tx_set,
14895 )?;
14896 neighbours.above_mode[sc] = mode_bot;
14897 neighbours.left_mode[sr] = mode_bot;
14898 continue;
14899 }
14900 if part16 == PARTITION_VERT {
14901 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
14902 let (mi_row0, mi_col0) = (
14903 sr as u32 * SUB_MI,
14904 sc as u32 * SUB_MI,
14905 );
14906 let left = (mi_row0 as usize, mi_col0 as usize);
14907 let right = (mi_row0 as usize, mi_col0 as usize + 2);
14908 let mode_left = decode_leaf_rect(
14909 &mut dec,
14910 &mut cdfs,
14911 &mut neighbours,
14912 at16,
14913 left,
14914 8,
14915 16,
14916 None,
14917 &mut y,
14918 &mut u,
14919 &mut v,
14920 enable_filter_intra,
14921 allow_screen_content_tools,
14922 base_q_idx,
14923 tx_select,
14924 reduced_tx_set,
14925 )?;
14926 let mode_right = decode_leaf_rect(
14927 &mut dec,
14928 &mut cdfs,
14929 &mut neighbours,
14930 at16,
14931 right,
14932 8,
14933 16,
14934 Some((left, mode_left)),
14935 &mut y,
14936 &mut u,
14937 &mut v,
14938 enable_filter_intra,
14939 allow_screen_content_tools,
14940 base_q_idx,
14941 tx_select,
14942 reduced_tx_set,
14943 )?;
14944 neighbours.above_mode[sc] = mode_right;
14945 neighbours.left_mode[sr] = mode_right;
14946 continue;
14947 }
14948 if part16 == PARTITION_HORZ_4
14949 || part16 == PARTITION_VERT_4
14950 {
14951 decode_rect4_16(
14952 &mut dec,
14953 &mut cdfs,
14954 &mut neighbours,
14955 at16,
14956 part16 == PARTITION_HORZ_4,
14957 &mut y,
14958 &mut u,
14959 &mut v,
14960 enable_filter_intra,
14961 allow_screen_content_tools,
14962 base_q_idx,
14963 tx_select,
14964 reduced_tx_set,
14965 )?;
14966 continue;
14967 }
14968 // lane-r14 r2 (verifier note): every
14969 // one of the 10 symbols this CDF can
14970 // produce is handled above, so SPLIT
14971 // is the only value that reaches
14972 // here -- the refusal that used to
14973 // stand here was unreachable and is
14974 // gone from `refusal_inventory`.
14975 debug_assert_eq!(part16, PARTITION_SPLIT);
14976 // A real (non-straddle) SPLIT of a
14977 // whole 16x16 into four 8x8 leaves --
14978 // the same recursion the straddle
14979 // path below already runs when the
14980 // true frame edge forces it, just
14981 // over all four positions instead of
14982 // the one or two the edge leaves.
14983 let (mi_row0, mi_col0) =
14984 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
14985 // Each 8x8 leaf's intra-mode context
14986 // must see its own siblings: the
14987 // bottom-left leaf's ABOVE neighbour
14988 // is leaf 0, not the previously
14989 // decoded leaf 1 (and the bottom-right
14990 // leaf's above is leaf 1, while
14991 // `prev_leaf` only ever carried the
14992 // immediately preceding one). The
14993 // coarse `above_mode`/`left_mode`
14994 // arrays hold one slot per 16x16, so
14995 // the sibling modes are swapped in
14996 // around each leaf call and restored
14997 // after; the loop tail writes the last
14998 // leaf's mode as before.
14999 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
15000 for i in 0..4 {
15001 let (mr, mc) =
15002 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
15003 let leaf_mi = (mr as usize, mc as usize);
15004 let li = i as usize;
15005 let saved_modes =
15006 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
15007 if li >= 2 {
15008 if let Some((below, _)) = sib_modes[li - 2] {
15009 neighbours.above_mode[sc] = below;
15010 }
15011 }
15012 if li % 2 == 1 {
15013 if let Some((_, right)) = sib_modes[li - 1] {
15014 neighbours.left_mode[sr] = right;
15015 }
15016 }
15017 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
15018 let part8 =
15019 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
15020 if std::env::var_os("EC_AV1_TRACE").is_some() {
15021 eprintln!(
15022 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
15023 );
15024 }
15025 let leaf_mode = if part8 == PARTITION_NONE {
15026 decode_leaf8(
15027 &mut dec,
15028 &mut cdfs,
15029 &mut neighbours,
15030 at16,
15031 leaf_mi,
15032 (&scan8, &scan4),
15033 None,
15034 &mut y,
15035 &mut u,
15036 &mut v,
15037 base_q_idx,
15038 enable_filter_intra,
15039 allow_screen_content_tools,
15040 allow_intrabc,
15041 tx_select,
15042 reduced_tx_set,
15043 ).map(|m| (m, m))?
15044 } else if part8 == PARTITION_SPLIT {
15045 decode_leaf_split4(
15046 &mut dec,
15047 &mut cdfs,
15048 &mut neighbours,
15049 at16,
15050 leaf_mi,
15051 &scan4,
15052 None,
15053 &mut y,
15054 &mut u,
15055 &mut v,
15056 base_q_idx,
15057 enable_filter_intra,
15058 allow_intrabc,
15059 reduced_tx_set,
15060 )?
15061 } else if part8 == PARTITION_HORZ
15062 || part8 == PARTITION_VERT
15063 {
15064 decode_leaf_rect8(
15065 &mut dec,
15066 &mut cdfs,
15067 &mut neighbours,
15068 at16,
15069 leaf_mi,
15070 part8 == PARTITION_VERT,
15071 &scan4,
15072 &mut y,
15073 &mut u,
15074 &mut v,
15075 base_q_idx,
15076 enable_filter_intra,
15077 allow_intrabc,
15078 tx_select,
15079 reduced_tx_set,
15080 )?
15081 } else {
15082 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
15083 };
15084 neighbours.above_mode[sc] = saved_modes.0;
15085 neighbours.left_mode[sr] = saved_modes.1;
15086 sib_modes[li] = Some(leaf_mode);
15087 }
15088 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
15089 neighbours.above_mode[sc] = below;
15090 }
15091 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
15092 neighbours.left_mode[sr] = right;
15093 }
15094 continue;
15095 }
15096 // The true edge falls inside this 16x16
15097 // leaf itself (mod-32==8 target sizes,
15098 // lane-av1-rect): one axis only -- an 8x8
15099 // leaf never itself straddles, so the
15100 // block splits cleanly along whichever
15101 // axis is short.
15102 if !has_cols16 && !has_rows16 {
15103 return Err(unsupported(
15104 "a 16x16 block whose true edge cuts through both \
15105 axes needs a rectangular transform this decoder \
15106 does not code yet",
15107 ));
15108 }
15109 // lane-golomb r1 (class
15110 // `parsed-then-discarded`): the gathered
15111 // bit IS the partition -- 0 names
15112 // PARTITION_HORZ (resp. VERT), only 1 is
15113 // SPLIT (libaom `ec_read_partition_impl`).
15114 // This path can only walk the four SPLIT
15115 // leaves, so a 0 refuses by name instead
15116 // of desyncing.
15117 trace_edge(sr * SUB_MI as usize, sc * SUB_MI as usize, 6, ctx16, dec.debug_state().0 as u32);
15118 let edge_split = if has_cols16 {
15119 dec.symbol_fixed(&gather(
15120 &cdfs.partition_w16[ctx16],
15121 VERT_ALIKE,
15122 ))
15123 } else {
15124 dec.symbol_fixed(&gather(
15125 &cdfs.partition_w16[ctx16],
15126 HORZ_ALIKE,
15127 ))
15128 };
15129 // lane-hgkf r1: slots 2/3 of
15130 // [`EDGE_PART_HITS`], the gate's proof the
15131 // non-SPLIT edge arm actually decoded.
15132 bump_edge_part(if edge_split == 1 { 3 } else { 2 });
15133 if edge_split == 0 {
15134 // lane-oddh r1: the strip IS decodable
15135 // -- libaom's `decode_partition` codes
15136 // only the FIRST half of an edge
15137 // HORZ/VERT (the second call is
15138 // guarded by the same has_rows/
15139 // has_cols test that made the
15140 // partition non-square), so one
15141 // 16x8 (resp. 8x16) strip covers the
15142 // whole visible band of a frame whose
15143 // height (resp. width) is 8 mod 16 --
15144 // the user's 3840x1608 film.
15145 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
15146 EDGE_RECT_STRIP_HITS.with(|c| c.set(c.get() + 1));
15147 let (mi_row0, mi_col0) =
15148 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
15149 let (bw, bh) = if has_cols16 { (16, 8) } else { (8, 16) };
15150 let mode = decode_leaf_rect(
15151 &mut dec,
15152 &mut cdfs,
15153 &mut neighbours,
15154 at16,
15155 (mi_row0 as usize, mi_col0 as usize),
15156 bw,
15157 bh,
15158 None,
15159 &mut y,
15160 &mut u,
15161 &mut v,
15162 enable_filter_intra,
15163 allow_screen_content_tools,
15164 base_q_idx,
15165 tx_select,
15166 reduced_tx_set,
15167 )?;
15168 neighbours.above_mode[sc] = mode;
15169 neighbours.left_mode[sr] = mode;
15170 continue;
15171 }
15172 let (mi_row0, mi_col0) =
15173 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
15174 let leaf_positions: Vec<(u32, u32)> = (0..4)
15175 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
15176 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
15177 .collect();
15178 // See the sibling-mode note in the clean
15179 // SPLIT path above.
15180 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
15181 for (mr, mc) in leaf_positions {
15182 let leaf_mi = (mr as usize, mc as usize);
15183 let li = (((mr - mi_row0) / 2) * 2 + (mc - mi_col0) / 2)
15184 as usize;
15185 let saved_modes =
15186 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
15187 if li >= 2 {
15188 if let Some((below, _)) = sib_modes[li - 2] {
15189 neighbours.above_mode[sc] = below;
15190 }
15191 }
15192 if li % 2 == 1 {
15193 if let Some((_, right)) = sib_modes[li - 1] {
15194 neighbours.left_mode[sr] = right;
15195 }
15196 }
15197 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
15198 let pre8 = dec.debug_state().0;
15199 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
15200 if std::env::var_os("EC_AV1_TRACE").is_some() {
15201 eprintln!(
15202 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8} pre_rng={pre8}"
15203 );
15204 }
15205 let leaf_mode = if part8 == PARTITION_NONE {
15206 decode_leaf8(
15207 &mut dec,
15208 &mut cdfs,
15209 &mut neighbours,
15210 at16,
15211 leaf_mi,
15212 (&scan8, &scan4),
15213 None,
15214 &mut y,
15215 &mut u,
15216 &mut v,
15217 base_q_idx,
15218 enable_filter_intra,
15219 allow_screen_content_tools,
15220 allow_intrabc,
15221 tx_select,
15222 reduced_tx_set,
15223 ).map(|m| (m, m))?
15224 } else if part8 == PARTITION_SPLIT {
15225 decode_leaf_split4(
15226 &mut dec,
15227 &mut cdfs,
15228 &mut neighbours,
15229 at16,
15230 leaf_mi,
15231 &scan4,
15232 None,
15233 &mut y,
15234 &mut u,
15235 &mut v,
15236 base_q_idx,
15237 enable_filter_intra,
15238 allow_intrabc,
15239 reduced_tx_set,
15240 )?
15241 } else if part8 == PARTITION_HORZ
15242 || part8 == PARTITION_VERT
15243 {
15244 decode_leaf_rect8(
15245 &mut dec,
15246 &mut cdfs,
15247 &mut neighbours,
15248 at16,
15249 leaf_mi,
15250 part8 == PARTITION_VERT,
15251 &scan4,
15252 &mut y,
15253 &mut u,
15254 &mut v,
15255 base_q_idx,
15256 enable_filter_intra,
15257 allow_intrabc,
15258 tx_select,
15259 reduced_tx_set,
15260 )?
15261 } else {
15262 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
15263 };
15264 neighbours.above_mode[sc] = saved_modes.0;
15265 neighbours.left_mode[sr] = saved_modes.1;
15266 sib_modes[li] = Some(leaf_mode);
15267 }
15268 // `record()`'s `above_mode`/`left_mode`
15269 // write is a no-op at an 8x8 leaf's own
15270 // side, so force the write once the whole
15271 // 16x16 slot's leaves are done, from the
15272 // last leaf (mirrors the writer's r15
15273 // fix).
15274 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
15275 neighbours.above_mode[sc] = below;
15276 }
15277 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
15278 neighbours.left_mode[sr] = right;
15279 }
15280 }
15281 }
15282 PARTITION_HORZ => {
15283 // lane-intradisp r1: two true 32x16 strips.
15284 decode_block_rect(
15285 &mut dec,
15286 &mut cdfs,
15287 &mut neighbours,
15288 at32,
15289 32,
15290 16,
15291 &mut y,
15292 &mut u,
15293 &mut v,
15294 enable_filter_intra,
15295 allow_screen_content_tools,
15296 base_q_idx,
15297 tx_select,
15298 reduced_tx_set,
15299 )?;
15300 if !has_rows32 {
15301 bump_edge32(2);
15302 }
15303 // lane-hgkf r1: at the frame edge only the first half of the strip is
15304 // coded (libaom `decode_partition` guards the second half with the same
15305 // test that made this partition non-square).
15306 if has_rows32 {
15307 decode_block_rect(
15308 &mut dec,
15309 &mut cdfs,
15310 &mut neighbours,
15311 (at32.0 + 1, at32.1),
15312 32,
15313 16,
15314 &mut y,
15315 &mut u,
15316 &mut v,
15317 enable_filter_intra,
15318 allow_screen_content_tools,
15319 base_q_idx,
15320 tx_select,
15321 reduced_tx_set,
15322 )?;
15323 }
15324 }
15325 PARTITION_VERT => {
15326 // lane-intradisp r1: mirror of PARTITION_HORZ
15327 // above with width/height swapped.
15328 decode_block_rect(
15329 &mut dec,
15330 &mut cdfs,
15331 &mut neighbours,
15332 at32,
15333 16,
15334 32,
15335 &mut y,
15336 &mut u,
15337 &mut v,
15338 enable_filter_intra,
15339 allow_screen_content_tools,
15340 base_q_idx,
15341 tx_select,
15342 reduced_tx_set,
15343 )?;
15344 if !has_cols32 {
15345 bump_edge32(3);
15346 }
15347 // lane-hgkf r1: at the frame edge only the first half of the strip is
15348 // coded (libaom `decode_partition` guards the second half with the same
15349 // test that made this partition non-square).
15350 if has_cols32 {
15351 decode_block_rect(
15352 &mut dec,
15353 &mut cdfs,
15354 &mut neighbours,
15355 (at32.0, at32.1 + 1),
15356 16,
15357 32,
15358 &mut y,
15359 &mut u,
15360 &mut v,
15361 enable_filter_intra,
15362 allow_screen_content_tools,
15363 base_q_idx,
15364 tx_select,
15365 reduced_tx_set,
15366 )?;
15367 }
15368 }
15369 PARTITION_HORZ_A => {
15370 // lane-part32 r1: two 16x16 squares on top +
15371 // a true 32x16 strip below (mirrors
15372 // decode_inter_block's cd6cb6d HORZ_A: TL,
15373 // TR, bottom strip).
15374 INTRA_HORZ_A_HITS.with(|c| c.set(c.get() + 1));
15375 decode_block(
15376 &mut dec,
15377 &mut cdfs,
15378 &mut neighbours,
15379 at32,
15380 SUB,
15381 TxbSet::Luma16,
15382 TxbSet::Chroma8,
15383 TX16,
15384 TX8,
15385 (&scan16, &scan8),
15386 true,
15387 &mut y,
15388 &mut u,
15389 &mut v,
15390 base_q_idx,
15391 enable_filter_intra,
15392 allow_screen_content_tools,
15393 allow_intrabc,
15394 &scan32,
15395 &scan16,
15396 &scan8,
15397 &scan4,
15398 tx_select,
15399 reduced_tx_set,
15400 )?;
15401 decode_block(
15402 &mut dec,
15403 &mut cdfs,
15404 &mut neighbours,
15405 (at32.0, at32.1 + 1),
15406 SUB,
15407 TxbSet::Luma16,
15408 TxbSet::Chroma8,
15409 TX16,
15410 TX8,
15411 (&scan16, &scan8),
15412 true,
15413 &mut y,
15414 &mut u,
15415 &mut v,
15416 base_q_idx,
15417 enable_filter_intra,
15418 allow_screen_content_tools,
15419 allow_intrabc,
15420 &scan32,
15421 &scan16,
15422 &scan8,
15423 &scan4,
15424 tx_select,
15425 reduced_tx_set,
15426 )?;
15427 decode_block_rect(
15428 &mut dec,
15429 &mut cdfs,
15430 &mut neighbours,
15431 (at32.0 + 1, at32.1),
15432 32,
15433 16,
15434 &mut y,
15435 &mut u,
15436 &mut v,
15437 enable_filter_intra,
15438 allow_screen_content_tools,
15439 base_q_idx,
15440 tx_select,
15441 reduced_tx_set,
15442 )?;
15443 }
15444 PARTITION_HORZ_B => {
15445 // lane-part32 r1: a true 32x16 strip on top +
15446 // two 16x16 squares below (mirrors HORZ_A
15447 // with the strip/squares order flipped, same
15448 // shape as libaom decode_partition's HORZ_B).
15449 INTRA_HORZ_B_HITS.with(|c| c.set(c.get() + 1));
15450 decode_block_rect(
15451 &mut dec,
15452 &mut cdfs,
15453 &mut neighbours,
15454 at32,
15455 32,
15456 16,
15457 &mut y,
15458 &mut u,
15459 &mut v,
15460 enable_filter_intra,
15461 allow_screen_content_tools,
15462 base_q_idx,
15463 tx_select,
15464 reduced_tx_set,
15465 )?;
15466 decode_block(
15467 &mut dec,
15468 &mut cdfs,
15469 &mut neighbours,
15470 (at32.0 + 1, at32.1),
15471 SUB,
15472 TxbSet::Luma16,
15473 TxbSet::Chroma8,
15474 TX16,
15475 TX8,
15476 (&scan16, &scan8),
15477 true,
15478 &mut y,
15479 &mut u,
15480 &mut v,
15481 base_q_idx,
15482 enable_filter_intra,
15483 allow_screen_content_tools,
15484 allow_intrabc,
15485 &scan32,
15486 &scan16,
15487 &scan8,
15488 &scan4,
15489 tx_select,
15490 reduced_tx_set,
15491 )?;
15492 decode_block(
15493 &mut dec,
15494 &mut cdfs,
15495 &mut neighbours,
15496 (at32.0 + 1, at32.1 + 1),
15497 SUB,
15498 TxbSet::Luma16,
15499 TxbSet::Chroma8,
15500 TX16,
15501 TX8,
15502 (&scan16, &scan8),
15503 true,
15504 &mut y,
15505 &mut u,
15506 &mut v,
15507 base_q_idx,
15508 enable_filter_intra,
15509 allow_screen_content_tools,
15510 allow_intrabc,
15511 &scan32,
15512 &scan16,
15513 &scan8,
15514 &scan4,
15515 tx_select,
15516 reduced_tx_set,
15517 )?;
15518 }
15519 PARTITION_VERT_A => {
15520 // lane-part32 r1: mirror of HORZ_A with
15521 // width/height swapped (TL, BL, right 16x32
15522 // strip).
15523 INTRA_VERT_A_HITS.with(|c| c.set(c.get() + 1));
15524 let _vert_ab = crate::encode::Reach::vert_ab_partition();
15525 decode_block(
15526 &mut dec,
15527 &mut cdfs,
15528 &mut neighbours,
15529 at32,
15530 SUB,
15531 TxbSet::Luma16,
15532 TxbSet::Chroma8,
15533 TX16,
15534 TX8,
15535 (&scan16, &scan8),
15536 true,
15537 &mut y,
15538 &mut u,
15539 &mut v,
15540 base_q_idx,
15541 enable_filter_intra,
15542 allow_screen_content_tools,
15543 allow_intrabc,
15544 &scan32,
15545 &scan16,
15546 &scan8,
15547 &scan4,
15548 tx_select,
15549 reduced_tx_set,
15550 )?;
15551 decode_block(
15552 &mut dec,
15553 &mut cdfs,
15554 &mut neighbours,
15555 (at32.0 + 1, at32.1),
15556 SUB,
15557 TxbSet::Luma16,
15558 TxbSet::Chroma8,
15559 TX16,
15560 TX8,
15561 (&scan16, &scan8),
15562 true,
15563 &mut y,
15564 &mut u,
15565 &mut v,
15566 base_q_idx,
15567 enable_filter_intra,
15568 allow_screen_content_tools,
15569 allow_intrabc,
15570 &scan32,
15571 &scan16,
15572 &scan8,
15573 &scan4,
15574 tx_select,
15575 reduced_tx_set,
15576 )?;
15577 decode_block_rect(
15578 &mut dec,
15579 &mut cdfs,
15580 &mut neighbours,
15581 (at32.0, at32.1 + 1),
15582 16,
15583 32,
15584 &mut y,
15585 &mut u,
15586 &mut v,
15587 enable_filter_intra,
15588 allow_screen_content_tools,
15589 base_q_idx,
15590 tx_select,
15591 reduced_tx_set,
15592 )?;
15593 }
15594 PARTITION_VERT_B => {
15595 // lane-part32 r1: a true 16x32 strip on the
15596 // left + two 16x16 squares on the right
15597 // (libaom decode_partition VERT_B: left
15598 // strip, TR, BR).
15599 INTRA_VERT_B_HITS.with(|c| c.set(c.get() + 1));
15600 let _vert_ab = crate::encode::Reach::vert_ab_partition();
15601 decode_block_rect(
15602 &mut dec,
15603 &mut cdfs,
15604 &mut neighbours,
15605 at32,
15606 16,
15607 32,
15608 &mut y,
15609 &mut u,
15610 &mut v,
15611 enable_filter_intra,
15612 allow_screen_content_tools,
15613 base_q_idx,
15614 tx_select,
15615 reduced_tx_set,
15616 )?;
15617 decode_block(
15618 &mut dec,
15619 &mut cdfs,
15620 &mut neighbours,
15621 (at32.0, at32.1 + 1),
15622 SUB,
15623 TxbSet::Luma16,
15624 TxbSet::Chroma8,
15625 TX16,
15626 TX8,
15627 (&scan16, &scan8),
15628 true,
15629 &mut y,
15630 &mut u,
15631 &mut v,
15632 base_q_idx,
15633 enable_filter_intra,
15634 allow_screen_content_tools,
15635 allow_intrabc,
15636 &scan32,
15637 &scan16,
15638 &scan8,
15639 &scan4,
15640 tx_select,
15641 reduced_tx_set,
15642 )?;
15643 decode_block(
15644 &mut dec,
15645 &mut cdfs,
15646 &mut neighbours,
15647 (at32.0 + 1, at32.1 + 1),
15648 SUB,
15649 TxbSet::Luma16,
15650 TxbSet::Chroma8,
15651 TX16,
15652 TX8,
15653 (&scan16, &scan8),
15654 true,
15655 &mut y,
15656 &mut u,
15657 &mut v,
15658 base_q_idx,
15659 enable_filter_intra,
15660 allow_screen_content_tools,
15661 allow_intrabc,
15662 &scan32,
15663 &scan16,
15664 &scan8,
15665 &scan4,
15666 tx_select,
15667 reduced_tx_set,
15668 )?;
15669 }
15670 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
15671 // lane-tx64x16 r3: the 1:4 pair at the 32x32
15672 // level -- four 32x8 (or 8x32) strips in
15673 // raster order, `quarter_step` = 2 mi, with
15674 // libaom `decode_partition`'s own `i > 0`
15675 // frame-edge break.
15676 let horz = part32 == PARTITION_HORZ_4;
15677 let base_mi = (at32.0 * (SUB / MI), at32.1 * (SUB / MI));
15678 let mut prev: Option<((usize, usize), usize)> = None;
15679 for i in 0..4 {
15680 let strip_mi = if horz {
15681 (base_mi.0 + i * 2, base_mi.1)
15682 } else {
15683 (base_mi.0, base_mi.1 + i * 2)
15684 };
15685 if i > 0
15686 && (strip_mi.0 >= mi_rows as usize
15687 || strip_mi.1 >= mi_cols as usize)
15688 {
15689 break;
15690 }
15691 let (bw, bh) = if horz { (32, 8) } else { (8, 32) };
15692 let (mode, _uv) = decode_block_rect4(
15693 &mut dec,
15694 &mut cdfs,
15695 &mut neighbours,
15696 strip_mi,
15697 bw,
15698 bh,
15699 prev,
15700 &mut y,
15701 &mut u,
15702 &mut v,
15703 enable_filter_intra,
15704 allow_screen_content_tools,
15705 base_q_idx,
15706 tx_select,
15707 )?;
15708 prev = Some((strip_mi, mode));
15709 }
15710 }
15711 _ => {
15712 return Err(unsupported(format!(
15713 "a 32x32 partition type this decoder does not code (value={part32})"
15714 )));
15715 }
15716 }
15717 }
15718 }
15719 PARTITION_HORZ => {
15720 // lane-sbpart r2: two true 64x32 strips.
15721 decode_block_rect64(
15722 &mut dec,
15723 &mut cdfs,
15724 &mut neighbours,
15725 at,
15726 64,
15727 32,
15728 &mut y,
15729 &mut u,
15730 &mut v,
15731 enable_filter_intra,
15732 allow_screen_content_tools,
15733 base_q_idx,
15734 tx_select,
15735 reduced_tx_set,
15736 )?;
15737 if !has_rows {
15738 bump_edge32(6);
15739 }
15740 // lane-golomb r1: at the frame edge only the first half of the
15741 // strip is coded (libaom `decode_partition` guards the second
15742 // with the same has_rows test that made this partition non-square).
15743 if has_rows {
15744 decode_block_rect64(
15745 &mut dec,
15746 &mut cdfs,
15747 &mut neighbours,
15748 (at.0 + 2, at.1),
15749 64,
15750 32,
15751 &mut y,
15752 &mut u,
15753 &mut v,
15754 enable_filter_intra,
15755 allow_screen_content_tools,
15756 base_q_idx,
15757 tx_select,
15758 reduced_tx_set,
15759 )?;
15760 }
15761 }
15762 PARTITION_VERT => {
15763 // lane-sbpart r2: mirror of PARTITION_HORZ above with
15764 // width/height swapped.
15765 decode_block_rect64(
15766 &mut dec,
15767 &mut cdfs,
15768 &mut neighbours,
15769 at,
15770 32,
15771 64,
15772 &mut y,
15773 &mut u,
15774 &mut v,
15775 enable_filter_intra,
15776 allow_screen_content_tools,
15777 base_q_idx,
15778 tx_select,
15779 reduced_tx_set,
15780 )?;
15781 if !has_cols {
15782 bump_edge32(7);
15783 }
15784 // lane-golomb r1: at the frame edge only the first half of the
15785 // strip is coded (libaom `decode_partition` guards the second
15786 // with the same has_cols test that made this partition non-square).
15787 if has_cols {
15788 decode_block_rect64(
15789 &mut dec,
15790 &mut cdfs,
15791 &mut neighbours,
15792 (at.0, at.1 + 2),
15793 32,
15794 64,
15795 &mut y,
15796 &mut u,
15797 &mut v,
15798 enable_filter_intra,
15799 allow_screen_content_tools,
15800 base_q_idx,
15801 tx_select,
15802 reduced_tx_set,
15803 )?;
15804 }
15805 }
15806 PARTITION_HORZ_A | PARTITION_HORZ_B | PARTITION_VERT_A | PARTITION_VERT_B => {
15807 // lane-part32 r4: the four superblock-level AB arms, each
15808 // two 32x32 squares plus one 64x32/32x64 strip, in
15809 // libaom's own `decode_partition` order (decodeframe.c:
15810 // HORZ_A = TL, TR, bottom strip; HORZ_B = top strip, BL,
15811 // BR; VERT_A = TL, BL, right strip; VERT_B = left strip,
15812 // TR, BR). The pieces are exactly the ones already proven
15813 // by the `PARTITION_NONE`-under-SPLIT (32x32 square) and
15814 // `PARTITION_HORZ`/`VERT` (rect64 strip) arms above.
15815 SB_AB_HITS.with(|c| {
15816 let mut h = c.get();
15817 h[part - PARTITION_HORZ_A] += 1;
15818 c.set(h);
15819 });
15820 // lane-part32 r5: only the two VERTICAL arms reorder the
15821 // square sub-blocks (TL, BL, TR, BR), so only they switch
15822 // libaom's `has_tr`/`has_bl` tables.
15823 let _vert_ab = (part == PARTITION_VERT_A || part == PARTITION_VERT_B)
15824 .then(crate::encode::Reach::vert_ab_partition);
15825 macro_rules! square32 {
15826 ($at:expr) => {
15827 decode_block(
15828 &mut dec,
15829 &mut cdfs,
15830 &mut neighbours,
15831 $at,
15832 BLOCK,
15833 TxbSet::Luma32,
15834 TxbSet::Chroma16,
15835 TX32,
15836 TX16,
15837 (&scan32, &scan16),
15838 true,
15839 &mut y,
15840 &mut u,
15841 &mut v,
15842 base_q_idx,
15843 enable_filter_intra,
15844 allow_screen_content_tools,
15845 allow_intrabc,
15846 &scan32,
15847 &scan16,
15848 &scan8,
15849 &scan4,
15850 tx_select,
15851 reduced_tx_set,
15852 )?
15853 };
15854 }
15855 macro_rules! strip64 {
15856 ($at:expr, $bw:expr, $bh:expr) => {
15857 decode_block_rect64(
15858 &mut dec,
15859 &mut cdfs,
15860 &mut neighbours,
15861 $at,
15862 $bw,
15863 $bh,
15864 &mut y,
15865 &mut u,
15866 &mut v,
15867 enable_filter_intra,
15868 allow_screen_content_tools,
15869 base_q_idx,
15870 tx_select,
15871 reduced_tx_set,
15872 )?
15873 };
15874 }
15875 let (br, bc) = (at.0 + 2, at.1 + 2);
15876 match part {
15877 PARTITION_HORZ_A => {
15878 square32!(at);
15879 square32!((at.0, bc));
15880 strip64!((br, at.1), 64, 32);
15881 }
15882 PARTITION_HORZ_B => {
15883 strip64!(at, 64, 32);
15884 square32!((br, at.1));
15885 square32!((br, bc));
15886 }
15887 PARTITION_VERT_A => {
15888 square32!(at);
15889 square32!((br, at.1));
15890 strip64!((at.0, bc), 32, 64);
15891 }
15892 _ => {
15893 strip64!(at, 32, 64);
15894 square32!((at.0, bc));
15895 square32!((br, bc));
15896 }
15897 }
15898 }
15899 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
15900 // lane-tx64x16: the 1:4 pair at 64x64 -- four 64x16 (or
15901 // 16x64) strips in raster order. `decode_partition`
15902 // (`decodeframe.c`) steps by `quarter_step = mi_size / 4`
15903 // (4 mi = 16 px = one SUB unit here) and BREAKS at the
15904 // frame edge for `i > 0`, so a partial superblock codes
15905 // only the strips whose origin is inside the frame.
15906 let horz = part == PARTITION_HORZ_4;
15907 for i in 0..4 {
15908 let step_mi = i * (SB_MI as usize / 4);
15909 let (this_r_mi, this_c_mi) = if horz {
15910 (sb_r as usize * SB_MI as usize + step_mi, sb_c as usize * SB_MI as usize)
15911 } else {
15912 (sb_r as usize * SB_MI as usize, sb_c as usize * SB_MI as usize + step_mi)
15913 };
15914 if i > 0
15915 && (this_r_mi >= mi_rows as usize || this_c_mi >= mi_cols as usize)
15916 {
15917 break;
15918 }
15919 let strip_at = if horz { (at.0 + i, at.1) } else { (at.0, at.1 + i) };
15920 let (bw, bh) = if horz { (64, 16) } else { (16, 64) };
15921 decode_block_rect64(
15922 &mut dec,
15923 &mut cdfs,
15924 &mut neighbours,
15925 strip_at,
15926 bw,
15927 bh,
15928 &mut y,
15929 &mut u,
15930 &mut v,
15931 enable_filter_intra,
15932 allow_screen_content_tools,
15933 base_q_idx,
15934 tx_select,
15935 reduced_tx_set,
15936 )?;
15937 }
15938 }
15939 _ => {
15940 return Err(unsupported(
15941 "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4",
15942 ));
15943 }
15944 }
15945 }
15946 }
15947
15948 if tile_num == tile_info.context_update_tile_id {
15949 result_cdfs = cdfs;
15950 }
15951 }
15952
15953 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
15954 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
15955 // that isolate whether a decode-order frame's mismatch already exists
15956 // in reconstruction (this dump) vs is introduced by the loop filter
15957 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
15958 // Decode-order frame marker for the EC_OBMC / EC_TRACE_MODE ladders.
15959 if std::env::var_os("EC_OBMC").is_some() || std::env::var_os("EC_TRACE_MODE").is_some() {
15960 eprintln!(
15961 "EC_PICT idx={}",
15962 PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst)
15963 );
15964 }
15965 dump_stage16("EC_AV1_PREFILT_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
15966 if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") {
15967 use std::io::Write;
15968 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
15969 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
15970 let narrow = |p: &PlaneBuf| -> Vec<u8> { p.data.iter().map(|&s| s as u8).collect() };
15971 let _ = f.write_all(&narrow(&y));
15972 let _ = f.write_all(&narrow(&u));
15973 let _ = f.write_all(&narrow(&v));
15974 }
15975 } else {
15976 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
15977 }
15978 if let Ok(path) = std::env::var("EC_AV1_PREFILT_WIDE_DUMP") {
15979 use std::io::Write;
15980 static IDX2: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
15981 let idx = IDX2.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
15982 let crop_wide = |plane: &PlaneBuf| -> Vec<u8> {
15983 let mut out = Vec::with_capacity(plane.true_width * plane.true_height);
15984 for row in 0..plane.true_height {
15985 out.extend(plane.data[row * plane.width..][..plane.true_width].iter().map(|&s| s as u8));
15986 }
15987 out
15988 };
15989 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
15990 let _ = f.write_all(&crop_wide(&y));
15991 let _ = f.write_all(&crop_wide(&u));
15992 let _ = f.write_all(&crop_wide(&v));
15993 }
15994 }
15995 apply_deblock(
15996 &mut y,
15997 &mut u,
15998 &mut v,
15999 loop_filter,
16000 &neighbours,
16001 frame_width as usize,
16002 frame_height as usize,
16003 );
16004 let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());
16005 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
16006 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
16007 // dump above these bisect WHICH filter stage introduced a mismatch.
16008 dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v);
16009 dump_stage16("EC_AV1_POSTDEBLOCK_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
16010 apply_cdef(
16011 &mut y,
16012 &mut u,
16013 &mut v,
16014 cdef,
16015 &neighbours,
16016 (frame_width as usize, frame_height as usize),
16017 );
16018 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
16019 dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
16020 apply_loop_restoration(
16021 &mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid,
16022 (frame_width as usize, frame_height as usize),
16023 );
16024
16025 let (fw, fh) = (frame_width as usize, frame_height as usize);
16026 if fw == width && fh == height {
16027 LAST_FRAME_WIDE_MARGIN.with(|m| *m.borrow_mut() = None);
16028 return Ok((
16029 Picture {
16030 width,
16031 height,
16032 y: y.data,
16033 u: u.data,
16034 v: v.data,
16035 },
16036 result_cdfs,
16037 ));
16038 }
16039 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u16> {
16040 let mut out = Vec::with_capacity(w * h);
16041 for row in 0..h {
16042 out.extend(plane.data[row * plane.width..][..w].iter().copied());
16043 }
16044 out
16045 };
16046 // lane-superres r3: `true_width`/`true_height` (`mi_cols`/`mi_rows` * 4)
16047 // is the real reconstructed extent -- columns `[fw, true_width)` hold
16048 // genuine decoded samples (the last coding block straddles the frame
16049 // edge whenever `frame_width` isn't 8-sample aligned), not padding.
16050 // libaom's superres upscale runs on that buffer's own border-extended
16051 // margin, so it reads those real columns, not a synthetic replicate of
16052 // column `fw - 1`. Stash them for `stream.rs`'s superres path (a real
16053 // aomenc 43->64 stream pinned column-by-column against libaom's own
16054 // `av1_convolve_horiz_rs_c` via `scripts/superres-pin-harness.c` --
16055 // `row6-realedgeval` proved the replicate-of-`fw-1` padding this
16056 // decoder used before was off by 1 at the columns the tap window
16057 // reaches into that real margin; `None` when there is no margin (this
16058 // frame's `true_width`/`true_height` already equal `fw`/`fh`, e.g. a
16059 // non-superres frame whose width just isn't 32-block aligned).
16060 LAST_FRAME_WIDE_MARGIN.with(|m| {
16061 *m.borrow_mut() = if true_width > fw || true_height > fh {
16062 let yc = crop(&y, true_width, true_height);
16063 if let Ok(path) = std::env::var("EC_AV1_MARGIN_DUMP") {
16064 use std::io::Write;
16065 static IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
16066 let idx = IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
16067 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
16068 // corner-cut: this diagnostic dump stays 8-bit-narrowed
16069 // regardless of the stream's real bit depth (debug-only,
16070 // never read by a gate); widen if a >8-bit margin dump
16071 // is ever needed.
16072 let _ = f.write_all(&yc.iter().map(|&s| s as u8).collect::<Vec<u8>>());
16073 }
16074 }
16075 Some(Picture {
16076 width: true_width,
16077 height: true_height,
16078 y: yc,
16079 u: crop(&u, true_width.div_ceil(2), true_height.div_ceil(2)),
16080 v: crop(&v, true_width.div_ceil(2), true_height.div_ceil(2)),
16081 })
16082 } else {
16083 None
16084 }
16085 });
16086 Ok((
16087 Picture {
16088 width: fw,
16089 height: fh,
16090 y: crop(&y, fw, fh),
16091 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
16092 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
16093 },
16094 result_cdfs,
16095 ))
16096}
16097
16098/// `av1_get_pred_context_switchable_interp`'s context for `interp_filter[dir]`
16099/// -- `above`/`left` are the neighbour's own resolved index for this
16100/// direction (0..=2, or `3` = no info, spec `SWITCHABLE_FILTERS`).
16101/// `is_compound` folds in libaom `av1_get_pred_context_switchable_interp`'s
16102/// own `ctx_offset` term (`INTER_FILTER_COMP_OFFSET` = 4, added when *this*
16103/// block itself has a second reference) -- lane-av1idx: a stale "this
16104/// decoder never codes a compound reference" assumption baked this to
16105/// always-0, which desynced the CDF context bucket (not the decoded value
16106/// outright, hence small pixel deltas rather than a hard desync) the moment
16107/// lane-av1blend unmasked plain-average compound blocks on a Switchable-
16108/// filter frame.
16109fn switchable_interp_ctx(above: u8, left: u8, dir: usize, is_compound: bool) -> usize {
16110 let base = dir * 8 + if is_compound { 4 } else { 0 };
16111 let term = if left == above {
16112 left
16113 } else if left == 3 {
16114 above
16115 } else if above == 3 {
16116 left
16117 } else {
16118 3
16119 };
16120 base + term as usize
16121}
16122
16123/// Resolves the interpolation filter kernel(s) an inter block's motion
16124/// compensation reads (spec 5.11.10/5.11.20): a fixed-filter frame
16125/// (`interp_fixed = Some`) never reads a symbol; a `Switchable` frame
16126/// (`interp_fixed = None`) reads `interp_filter[0]` and, when
16127/// `enable_dual_filter`, a second `interp_filter[1]` -- unless
16128/// `force_regular` (this block's own `needs_interp_filter() == 0` case: a
16129/// `GLOBALMV` block, whose global motion is always `IDENTITY` in this
16130/// decoder's scope, spec 5.11.10's `large && YMode == GLOBALMV` branch),
16131/// which forces `EIGHTTAP` without reading anything.
16132#[allow(clippy::too_many_arguments)]
16133fn resolve_interp_filter(
16134 dec: &mut SymbolDecoder,
16135 cdfs: &mut Cdfs,
16136 interp_fixed: Option<mc::InterpFilterKind>,
16137 enable_dual_filter: bool,
16138 force_regular: bool,
16139 above: [u8; 2],
16140 left: [u8; 2],
16141 is_compound: bool,
16142) -> (mc::InterpFilterKind, mc::InterpFilterKind, [u8; 2]) {
16143 if let Some(kind) = interp_fixed {
16144 return (kind, kind, [3, 3]);
16145 }
16146 if force_regular {
16147 return (
16148 mc::InterpFilterKind::Regular,
16149 mc::InterpFilterKind::Regular,
16150 [0, 0],
16151 );
16152 }
16153 // libaom `av1_extract_interp_filter`/`read_mb_interp_filter`: the
16154 // symbol read at `dir=0` becomes the block's *vertical* (`y_filter`)
16155 // kernel, `dir=1` the *horizontal* (`x_filter`) one -- `dir` is not
16156 // "horizontal then vertical" despite `predict_with_filters`' own
16157 // `h_kind`/`v_kind` argument order, which is why this function returns
16158 // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`).
16159 let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound);
16160 if std::env::var_os("EC_AV1_IFDBG").is_some() {
16161 eprintln!(
16162 "IFDBG dir=0 ctx={ctx0} above={above:?} left={left:?} cdf={:?}",
16163 &cdfs.switchable_interp[ctx0][..3]
16164 );
16165 }
16166 let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8;
16167 let sym1 = if enable_dual_filter {
16168 let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound);
16169 if std::env::var_os("EC_AV1_IFDBG").is_some() {
16170 eprintln!(
16171 "IFDBG dir=1 ctx={ctx1} above={above:?} left={left:?} cdf={:?} sym0={sym0}",
16172 &cdfs.switchable_interp[ctx1][..3]
16173 );
16174 }
16175 dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8
16176 } else {
16177 sym0
16178 };
16179 if enable_dual_filter && sym0 != sym1 {
16180 DUAL_FILTER_DIFF_HITS.with(|c| c.set(c.get() + 1));
16181 }
16182 if std::env::var_os("EC_TRACE_MODE").is_some() {
16183 eprintln!(
16184 "EC_IF ctx0={ctx0} above={above:?} left={left:?} sym0={sym0} sym1={sym1} rng={}",
16185 dec.debug_state().0
16186 );
16187 }
16188 (
16189 mc::InterpFilterKind::from_switchable_symbol(sym1 as usize),
16190 mc::InterpFilterKind::from_switchable_symbol(sym0 as usize),
16191 [sym0, sym1],
16192 )
16193}
16194
16195/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`),
16196/// duplicating [`crate::tile`]'s private copy of the same rule.
16197pub(crate) fn intra_inter_ctx(
16198 has_above: bool,
16199 has_left: bool,
16200 above_inter: bool,
16201 left_inter: bool,
16202) -> usize {
16203 match (has_above, has_left) {
16204 (true, true) => {
16205 let (above_intra, left_intra) = (!above_inter, !left_inter);
16206 if above_intra && left_intra {
16207 3
16208 } else {
16209 usize::from(above_intra || left_intra)
16210 }
16211 }
16212 (true, false) => 2 * usize::from(!above_inter),
16213 (false, true) => 2 * usize::from(!left_inter),
16214 (false, false) => 0,
16215 }
16216}
16217
16218/// `CLASS0_SIZE << (class + 2)`, duplicating `crate::tile`'s private
16219/// `mv_class_base` (spec 3): the magnitude an `MV_CLASS_n` component's own
16220/// bits start counting from.
16221fn mv_class_base(class: usize) -> i32 {
16222 if class == 0 { 0 } else { 2i32 << (class + 2) }
16223}
16224
16225/// One motion vector component's non-zero diff (spec 5.11.32
16226/// `read_mv_component`), the inverse of [`crate::tile`]'s private
16227/// `write_mv_component`.
16228fn read_mv_component(
16229 dec: &mut SymbolDecoder,
16230 c: &mut MvComponentCdfs,
16231 allow_high_precision_mv: bool,
16232 force_integer_mv: bool,
16233) -> i32 {
16234 let sign = dec.symbol(&mut c.sign);
16235 let class = dec.symbol(&mut c.class);
16236 let local = if class == 0 {
16237 let bit = dec.symbol(&mut c.class0_bit);
16238 // spec 5.11.32 `mv_class0_fr`: not coded at all when the frame
16239 // forces integer motion vectors -- implicitly `3` (the top
16240 // fractional value) rather than read, else every symbol after it
16241 // in the tile desyncs by one read.
16242 let fr = if force_integer_mv {
16243 3
16244 } else {
16245 dec.symbol(&mut c.class0_fr[bit])
16246 };
16247 // spec 5.11.32 `mv_class0_hp`: read only when the frame allows
16248 // high-precision motion vectors, else implicitly 1 (the low bit
16249 // stays at half-pel precision) -- this crate's own writer always
16250 // leaves the flag off, but a foreign stream can set it per frame.
16251 let hp = if allow_high_precision_mv {
16252 dec.symbol(&mut c.class0_hp)
16253 } else {
16254 1
16255 };
16256 (bit << 3) | (fr << 1) | hp
16257 } else {
16258 let mut d = 0;
16259 for i in 0..class {
16260 d |= dec.symbol(&mut c.bit[i]) << i;
16261 }
16262 // spec 5.11.32 `mv_fr`: same force_integer_mv carve-out as
16263 // `mv_class0_fr` above.
16264 let fr = if force_integer_mv { 3 } else { dec.symbol(&mut c.fr) };
16265 let hp = if allow_high_precision_mv {
16266 dec.symbol(&mut c.hp)
16267 } else {
16268 1
16269 };
16270 (d << 3) | (fr << 1) | hp
16271 };
16272 let mag = mv_class_base(class) + local as i32 + 1;
16273 if sign == 1 { -mag } else { mag }
16274}
16275
16276/// A motion vector coded as a residual against `pred` (spec 5.11.32
16277/// `read_mv`), the inverse of [`crate::tile`]'s private `write_mv`.
16278fn read_mv(
16279 dec: &mut SymbolDecoder,
16280 mv_comp: &mut [MvComponentCdfs; 2],
16281 mv_joint: &mut [u16; 5],
16282 pred: (i32, i32),
16283 allow_high_precision_mv: bool,
16284 force_integer_mv: bool,
16285) -> (i32, i32) {
16286 let joint = dec.symbol(mv_joint);
16287 let mut diff = (0, 0);
16288 if joint == 2 || joint == 3 {
16289 diff.0 = read_mv_component(dec, &mut mv_comp[0], allow_high_precision_mv, force_integer_mv);
16290 }
16291 if joint == 1 || joint == 3 {
16292 diff.1 = read_mv_component(dec, &mut mv_comp[1], allow_high_precision_mv, force_integer_mv);
16293 }
16294 (pred.0 + diff.0, pred.1 + diff.1)
16295}
16296
16297/// One intrabc block's block vector (spec 5.11.13 `read_intrabc_info` ->
16298/// `assign_mv` with `use_intrabc`, libaom `assign_dv`/`av1_find_ref_dv`).
16299///
16300/// The predictor is the ordinary MV stack built against `INTRA_FRAME`
16301/// (`av1_find_mv_refs(..., INTRA_FRAME, ...)`): `nearestmv`, or `nearmv`
16302/// when that is zero, or -- when both are -- the fixed fallback DV one
16303/// superblock up, or `INTRABC_DELAY_PIXELS` (256) plus one superblock to the
16304/// left when this is the tile's first superblock row. The predictor is then
16305/// rounded to full pel, and the difference reads off the *dv* nmv context
16306/// (libaom `ndvc`) at full-pel precision (`MV_SUBPEL_NONE`: no `fr`/`hp`
16307/// symbols, exactly this decoder's `force_integer_mv` carve-out). No DRL
16308/// symbol is coded for a DV, so none of this can move the bitstream
16309/// position -- only the reconstructed vector.
16310fn read_intrabc_dv(
16311 dec: &mut SymbolDecoder,
16312 cdfs: &mut Cdfs,
16313 mi_r: usize,
16314 mi_c: usize,
16315 side: usize,
16316) -> (i32, i32) {
16317 const INTRABC_DELAY_PIXELS: i32 = 256;
16318 let n4 = side / MI;
16319 let stack_pred = INTRABC_MI_GRID.with(|g| {
16320 let g = g.borrow();
16321 g.as_ref().map(|(grid, mi_cols, mi_rows)| {
16322 let stack = crate::mvstack::find_mv_stack(
16323 grid, mi_r, mi_c, n4, n4, 0, /* INTRA_FRAME */
16324 *mi_cols, *mi_rows,
16325 );
16326 if stack.nearest_mv == (0, 0) {
16327 stack.near_mv
16328 } else {
16329 stack.nearest_mv
16330 }
16331 })
16332 });
16333 let mut pred = stack_pred.unwrap_or((0, 0));
16334 if pred == (0, 0) {
16335 // `av1_find_ref_dv` (mvref_common.c). Tile row start is 0 here (the
16336 // single-tile-row case every intrabc gate stream is).
16337 let sb_px = SB_MI as i32 * MI as i32;
16338 pred = if mi_r < SB_MI as usize {
16339 (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8)
16340 } else {
16341 (-sb_px * 8, 0)
16342 };
16343 }
16344 // "Ref DV should not have sub-pel" (`assign_dv`): floor to full pel.
16345 let pred = ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8);
16346 read_mv(dec, &mut cdfs.dv_comp, &mut cdfs.dv_joint, pred, false, true)
16347}
16348
16349/// A 1/8-pel motion vector component converted to the 1/16-pel offset
16350/// [`mc::predict`] takes, duplicating [`crate::encode`]'s private `mv_to_q4`
16351/// (its own doc comment explains the `*2`/`*1` luma/chroma split).
16352fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
16353 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
16354}
16355
16356impl PlaneBuf {
16357 /// Adds `residual` onto an already-computed `prediction` (motion
16358 /// compensation's output, rather than [`predict`]'s intra one), writing
16359 /// the clamped reconstruction into the plane at `(x, y)` -- the inter
16360 /// counterpart of [`PlaneBuf::reconstruct`].
16361 fn reconstruct_mc(
16362 &mut self,
16363 x: usize,
16364 y: usize,
16365 side: usize,
16366 prediction: &[u16],
16367 residual: &[i32],
16368 ) {
16369 self.reconstruct_mc_rect(x, y, side, side, side, prediction, residual);
16370 }
16371
16372 /// [`Self::reconstruct_mc`], writing only a `w`x`h` sub-rectangle of the
16373 /// `side`x`side` `prediction`/`residual` buffers (which stay `side`-square
16374 /// for stride/indexing) -- lane-partitions r1: a true rectangular HORZ/
16375 /// VERT strip is predicted at its enclosing square `side` (matching
16376 /// `HORZ_B`'s already-accepted square-context corner-cut, lane-warp r5)
16377 /// but only its own true `w`x`h` footprint is committed to the plane, so
16378 /// two strips sharing a square's coordinate origin never clobber each
16379 /// other's real pixels.
16380 fn reconstruct_mc_rect(
16381 &mut self,
16382 x: usize,
16383 y: usize,
16384 side: usize,
16385 w: usize,
16386 h: usize,
16387 prediction: &[u16],
16388 residual: &[i32],
16389 ) {
16390 for row in 0..h {
16391 for col in 0..w {
16392 let sample = (i32::from(prediction[row * side + col]) + residual[row * side + col])
16393 .clamp(0, crate::decode::sample_max()) as u16;
16394 self.data[(y + row) * self.width + x + col] = sample;
16395 }
16396 }
16397 }
16398}
16399
16400/// Reads one inter-coded plane's transform block and reconstructs it by
16401/// adding its residual onto a motion-compensated `prediction` -- the inter
16402/// counterpart of [`read_plane`] (every inter transform this decoder reads is
16403/// `side`-square with no oversized-64 case, so there is no padded-grid
16404/// branch to mirror).
16405#[allow(clippy::too_many_arguments)]
16406fn read_inter_plane(
16407 dec: &mut SymbolDecoder,
16408 cdfs: &mut Cdfs,
16409 set: TxbSet,
16410 scan: &[u16],
16411 plane_idx: usize,
16412 around: (bool, bool, i32),
16413 tx_mode: usize,
16414 plane: &mut PlaneBuf,
16415 x: usize,
16416 y: usize,
16417 side: usize,
16418 base_q_idx: u8,
16419 prediction: &[u16],
16420 // lane-chromau: this block's own luma transform's *actual coded*
16421 // `tx_type` -- `av1_get_tx_type` (libaom `blockd.h`): an inter block's
16422 // chroma plane never codes its own `tx_type` symbol, but (unlike an
16423 // intra block, which falls back to `Intra_Mode_To_Tx_Type`) it inherits
16424 // the colocated luma transform's coded type, narrowed to the extended
16425 // set the CHROMA size selects ([`reduce_inherited_chroma_tx_type`]).
16426 // `None` for the luma call itself
16427 // (`plane_idx == 0`), where the `TxbSet`'s own symbol (or the true
16428 // `DCT_DCT` default at 32-point+) already resolves it without help.
16429 inherited_luma_tx_type: Option<TxType>,
16430 // lane-txselect: the luma `txb_skip_ctx` of a transform unit smaller than
16431 // its own block (spec `get_txb_ctx_general`'s `plane_bsize != tx_size`
16432 // branch, [`Neighbours::luma_skip_ctx`]) -- `None` for the whole-block
16433 // transform every non-var-tx caller reads, whose plane-0 context is the
16434 // lone-transform-unit 0.
16435 luma_skip_ctx: Option<usize>,
16436) -> Result<(Vec<i32>, TxType)> {
16437 let skip_ctx = if plane_idx == 0 {
16438 luma_skip_ctx.unwrap_or(0)
16439 } else {
16440 // lane-sb128c r1: on a CHROMA plane this same parameter carries
16441 // `get_txb_ctx`'s own offset instead -- `combine_entropy_contexts(..)`
16442 // is +7 normally and +10 when the plane block is LARGER than the
16443 // transform (a 128x128 block's 64x64 uv plane block with TX_32X32
16444 // units, AV1's only such case), and the `txb_skip_chroma_32` table
16445 // carries the offset-10 rows at +3 (lane-sb128b r3).
16446 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
16447 };
16448 let mut coding = cdfs.txb(set, tx_mode);
16449 let default_tx_type = match inherited_luma_tx_type {
16450 Some(t) => reduce_inherited_chroma_tx_type(t, side, side),
16451 None => TxType::DctDct,
16452 };
16453 let (grid, tx_type) = read_coeffs(
16454 dec,
16455 &mut coding,
16456 scan,
16457 skip_ctx,
16458 dc_sign_ctx(around.2),
16459 default_tx_type,
16460 None,
16461 )?;
16462 note_chroma_class1(plane_idx, tx_type);
16463 // lane-inter8 r1: a 64-point transform covers the whole 64x64 area but
16464 // codes only its top-left 32x32 of frequencies (spec 5.11.40) -- the
16465 // caller hands the 32-point `scan` there, and the coded corner goes into
16466 // the top-left of the true `side`-sized grid before dequantization
16467 // (dqDenom is keyed by the true size, not the corner's), mirroring
16468 // [`read_plane`]'s own `tx_side != side` branch. Every other transform
16469 // this decoder codes has `tx_side == side`, so this is inert below 64.
16470 let tx_side = side.min(32);
16471 let grid = if tx_side == side {
16472 grid
16473 } else {
16474 let mut full = vec![0i32; side * side];
16475 for row in 0..tx_side {
16476 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
16477 }
16478 full
16479 };
16480 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
16481 let residual = dequant_and_inverse_typed(&grid, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type);
16482 plane.reconstruct_mc(x, y, side, prediction, &residual);
16483 Ok((grid, tx_type))
16484}
16485
16486/// Spec 5.11.25's `single_ref_p1`..`p6` tree (reachable only once `comp_mode`
16487/// is known `SINGLE_REFERENCE` -- `decode_stream` refuses any frame with
16488/// `reference_select` set before this is ever called, so that read is never
16489/// needed here). `above_ref`/`left_ref` are `-1` for an intra/unavailable
16490/// neighbour, else the `1..=7` reference that neighbour coded (lane-av1refs).
16491fn read_single_ref(
16492 dec: &mut SymbolDecoder,
16493 cdfs: &mut Cdfs,
16494 above_ref: i8,
16495 above_ref1: Option<i8>,
16496 left_ref: i8,
16497 left_ref1: Option<i8>,
16498) -> i8 {
16499 let above = (above_ref > 0).then_some(above_ref);
16500 let left = (left_ref > 0).then_some(left_ref);
16501 let p1 = dec.symbol(&mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0]);
16502 let ref_frame = if p1 == 1 {
16503 let p2 = dec.symbol(&mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1]);
16504 if p2 == 1 {
16505 ALTREF_FRAME
16506 } else {
16507 let p6 = dec.symbol(&mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5]);
16508 if p6 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
16509 }
16510 } else {
16511 let p3 = dec.symbol(&mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2]);
16512 if p3 == 1 {
16513 let p5 = dec.symbol(&mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4]);
16514 if p5 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
16515 } else {
16516 let p4 = dec.symbol(&mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3]);
16517 if p4 == 1 { LAST2_FRAME } else { LAST_FRAME }
16518 }
16519 };
16520 if ref_frame != LAST_FRAME {
16521 NON_LAST_REF_HITS.with(|c| c.set(c.get() + 1));
16522 let c = match ref_frame {
16523 LAST2_FRAME => &LAST2_HITS,
16524 LAST3_FRAME => &LAST3_HITS,
16525 GOLDEN_FRAME => &GOLDEN_HITS,
16526 BWDREF_FRAME => &BWDREF_HITS,
16527 ALTREF2_FRAME => &ALTREF2_HITS,
16528 ALTREF_FRAME => &ALTREF_HITS,
16529 _ => unreachable!("read_single_ref only ever returns LAST_FRAME..=ALTREF_FRAME"),
16530 };
16531 c.with(|v| v.set(v.get() + 1));
16532 }
16533 ref_frame
16534}
16535
16536/// Spec 5.11.25's `comp_mode` (lane-av1comp): whether an inter block reads
16537/// `SINGLE_REFERENCE` or `COMPOUND_REFERENCE`, only reached once a frame's
16538/// `reference_select` header bit lets a block choose per-block instead of
16539/// fixing the mode. `above`/`left` are `None` for an intra/unavailable
16540/// neighbour, [`NeighbourRef`] for a coded one -- [`reference_mode_ctx`]'s
16541/// own doc. Called from [`decode_inter_block`] once its own `reference_select`
16542/// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same
16543/// way with a coarser (`LAST_FRAME`-only) neighbour shape.
16544/// Resolves a compound reference's own planes -- the same `ref_frame ==
16545/// LAST_FRAME -> ref_y/u/v, else other_refs[ref_frame]` lookup
16546/// [`decode_inter_block`]'s single-ref path already does, factored out so
16547/// the compound path can call it twice (lane-av1comp).
16548fn ref_planes<'a>(
16549 ref_frame: i8,
16550 ref_y: &'a PlaneBuf,
16551 ref_u: &'a PlaneBuf,
16552 ref_v: &'a PlaneBuf,
16553 other_refs: &'a RefSlots,
16554) -> Result<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)> {
16555 if ref_frame == LAST_FRAME {
16556 Ok((ref_y, ref_u, ref_v))
16557 } else {
16558 match other_refs[ref_frame as usize] {
16559 Some((ry, ru, rv)) => Ok((ry, ru, rv)),
16560 None => Err(unsupported(
16561 "a reference frame selected with no picture at this frame's own \
16562 ref_frame_idx slot for it",
16563 )),
16564 }
16565 }
16566}
16567
16568/// libaom `foreach_overlappable_nb_above` (`obmc.h`): walks the mi row
16569/// directly above this block's own column span, one bordering block at a
16570/// time (stepping by that neighbour's own `MiInfo::size`, which is always
16571/// `<= 16` since no block this decoder ever codes exceeds 64x64), collecting
16572/// every *inter* neighbour found (an intra or unset cell is skipped, one mi
16573/// unit at a time, and does not itself count as a step). `max_neighbors`
16574/// caller-bounds the scan: `1` for the eligibility check (any hit at all),
16575/// `av1_build_obmc_inter_prediction`'s own `max_neighbor_obmc` table for the
16576/// real blend pass. Round 1 corner-cut: libaom's own "4-wide block, treat as
16577/// half of a chroma pair" merge (`obmc.h`'s `mi_step == 1` special case) is
16578/// not ported -- no block this decoder codes is narrower than 8px, so it
16579/// never fires here regardless of what a neighbour's own decoder was.
16580fn overlappable_above(
16581 grid: &MiGrid,
16582 mi_row: usize,
16583 mi_col: usize,
16584 bw4: usize,
16585 mi_cols: usize,
16586 max_neighbors: usize,
16587) -> Vec<(usize, usize, MiInfo)> {
16588 let mut out = Vec::new();
16589 if mi_row == 0 {
16590 return out;
16591 }
16592 let end_col = (mi_col + bw4).min(mi_cols);
16593 let mut col = mi_col;
16594 while col < end_col && out.len() < max_neighbors {
16595 let cell = grid.get(mi_row - 1, col);
16596 let step = cell.map_or(1, |c| c.size).max(1);
16597 if let Some(info) = cell {
16598 if info.is_inter {
16599 out.push((col - mi_col, step.min(end_col - col), *info));
16600 }
16601 }
16602 col += step;
16603 }
16604 out
16605}
16606
16607/// `foreach_overlappable_nb_left`'s left-column mirror of
16608/// [`overlappable_above`] -- see its doc for the shared corner-cut.
16609fn overlappable_left(
16610 grid: &MiGrid,
16611 mi_row: usize,
16612 mi_col: usize,
16613 bh4: usize,
16614 mi_rows: usize,
16615 max_neighbors: usize,
16616) -> Vec<(usize, usize, MiInfo)> {
16617 let mut out = Vec::new();
16618 if mi_col == 0 {
16619 return out;
16620 }
16621 let end_row = (mi_row + bh4).min(mi_rows);
16622 let mut row = mi_row;
16623 while row < end_row && out.len() < max_neighbors {
16624 let cell = grid.get(row, mi_col - 1);
16625 // Vertical walk steps by the neighbour's HEIGHT -- a 32x16 strip's
16626 // width (8) would swallow the strip below it.
16627 let step = cell.map_or(1, |c| c.size_h).max(1);
16628 if let Some(info) = cell {
16629 if info.is_inter {
16630 out.push((row - mi_row, step.min(end_row - row), *info));
16631 }
16632 }
16633 row += step;
16634 }
16635 out
16636}
16637
16638/// The warp-sample gather's own `has_top_right` probe (libaom `av1_findSamples`
16639/// calls the same `mvref_common.c` function the MV stack does). lane-sb128 r2:
16640/// this used to hardcode `SB_MI` (a 64x64 superblock) -- at `sb_size == 128`
16641/// libaom's mask loop runs one level further and strips the top-right sample
16642/// off blocks whose neighbour IS decoded, so a warped 128-superblock frame
16643/// picked up wrong warp parameters (frame 6 of the 128 inter gate). Delegates
16644/// to the single sb-aware port in [`crate::mvstack::has_top_right`]; `bs` is
16645/// the block's own side in 4x4 (`mi`) units (square inter leaves only here).
16646fn has_top_right(mi_row: usize, mi_col: usize, bs: usize) -> bool {
16647 crate::mvstack::has_top_right(mi_row, mi_col, bs, bs)
16648}
16649
16650/// `av1_findSamples` (`mvref_common.c`), full port: the up to
16651/// `LEAST_SQUARES_SAMPLES_MAX` (8) above/left/top-left/top-right neighbour
16652/// samples (`record_samples`) that share this block's own single reference
16653/// frame and are themselves single-ref -- `mbmi->num_proj_ref` is
16654/// `.len()` of the returned vec. `bw4` is the block's own side in 4x4 units
16655/// (square, so also `bh4`; a real block's `xd->width`/`xd->height` in
16656/// libaom are also mi units of that same square side here). Each sample's
16657/// own `bw`/`bh` (fed to [`crate::warp::record_sample`]'s offset formula)
16658/// come from the *neighbour* cell's own coded size, not this block's.
16659#[allow(clippy::too_many_arguments)]
16660fn find_samples(
16661 grid: &MiGrid,
16662 mi_row: usize,
16663 mi_col: usize,
16664 bw4: usize,
16665 bh4: usize,
16666 mi_cols: usize,
16667 mi_rows: usize,
16668 ref_frame: i8,
16669) -> Vec<crate::warp::Sample> {
16670 const MAX: usize = crate::warp::LEAST_SQUARES_SAMPLES_MAX;
16671 let up_available = mi_row > 0;
16672 let left_available = mi_col > 0;
16673 let mut samples = Vec::with_capacity(MAX);
16674 let single_ref_match = |info: &MiInfo| info.ref_frame == ref_frame && info.ref_frame1.is_none();
16675 let mut do_tl = true;
16676 let mut do_tr = true;
16677 let rec = |info: &MiInfo, row_offset: i32, sign_r: i32, col_offset: i32, sign_c: i32| {
16678 let nb_bw = (info.size * 4) as i32;
16679 // lane-rect r2: the neighbour's own true height -- a rect strip
16680 // neighbour donates its sample at ITS center (aom pts y=-72 for a
16681 // 32x16 above strip; the square assumption put it at -136).
16682 let nb_bh = (info.size_h * 4) as i32;
16683 crate::warp::record_sample(nb_bw, nb_bh, info.mv, row_offset, sign_r, col_offset, sign_c)
16684 };
16685
16686 'outer: {
16687 if up_available {
16688 let above = grid.get(mi_row - 1, mi_col);
16689 let superblock_width = above.map_or(1, |c| c.size).max(1);
16690 if bw4 <= superblock_width {
16691 let col_offset = -((mi_col % superblock_width) as isize);
16692 if col_offset < 0 {
16693 do_tl = false;
16694 }
16695 if col_offset + superblock_width as isize > bw4 as isize {
16696 do_tr = false;
16697 }
16698 if let Some(info) = above {
16699 if single_ref_match(info) {
16700 samples.push(rec(info, 0, -1, col_offset as i32, 1));
16701 if samples.len() >= MAX {
16702 break 'outer;
16703 }
16704 }
16705 }
16706 } else {
16707 let mut i = 0usize;
16708 let limit = bw4.min(mi_cols.saturating_sub(mi_col));
16709 while i < limit {
16710 let cell = grid.get(mi_row - 1, mi_col + i);
16711 let sw = cell.map_or(1, |c| c.size).max(1);
16712 if let Some(info) = cell {
16713 if single_ref_match(info) {
16714 samples.push(rec(info, 0, -1, i as i32, 1));
16715 if samples.len() >= MAX {
16716 break 'outer;
16717 }
16718 }
16719 }
16720 i += sw;
16721 }
16722 }
16723 }
16724
16725 if left_available {
16726 let left = grid.get(mi_row, mi_col - 1);
16727 let superblock_height = left.map_or(1, |c| c.size_h).max(1);
16728 if bh4 <= superblock_height {
16729 let row_offset = -((mi_row % superblock_height) as isize);
16730 if row_offset < 0 {
16731 do_tl = false;
16732 }
16733 if let Some(info) = left {
16734 if single_ref_match(info) {
16735 samples.push(rec(info, row_offset as i32, 1, 0, -1));
16736 if samples.len() >= MAX {
16737 break 'outer;
16738 }
16739 }
16740 }
16741 } else {
16742 let mut i = 0usize;
16743 let limit = bh4.min(mi_rows.saturating_sub(mi_row));
16744 while i < limit {
16745 let cell = grid.get(mi_row + i, mi_col - 1);
16746 let sh = cell.map_or(1, |c| c.size_h).max(1);
16747 if let Some(info) = cell {
16748 if single_ref_match(info) {
16749 samples.push(rec(info, i as i32, 1, 0, -1));
16750 if samples.len() >= MAX {
16751 break 'outer;
16752 }
16753 }
16754 }
16755 i += sh;
16756 }
16757 }
16758 }
16759
16760 if do_tl && left_available && up_available {
16761 if let Some(info) = grid.get(mi_row - 1, mi_col - 1) {
16762 if single_ref_match(info) {
16763 samples.push(rec(info, 0, -1, 0, -1));
16764 if samples.len() >= MAX {
16765 break 'outer;
16766 }
16767 }
16768 }
16769 }
16770
16771 if do_tr && has_top_right(mi_row, mi_col, bw4) {
16772 let tr_col = mi_col + bw4;
16773 if mi_row > 0 && tr_col < mi_cols {
16774 if let Some(info) = grid.get(mi_row - 1, tr_col) {
16775 if single_ref_match(info) {
16776 samples.push(rec(info, 0, -1, bw4 as i32, 1));
16777 }
16778 }
16779 }
16780 }
16781 }
16782 samples
16783}
16784
16785/// `mbmi->num_proj_ref`: [`find_samples`]'s own count, all that
16786/// `motion_mode_allowed` needs to pick the 3-symbol `motion_mode_cdf` over
16787/// the 2-symbol `obmc_cdf` (spec 5.11.24).
16788#[allow(clippy::too_many_arguments)]
16789fn num_proj_ref(
16790 grid: &MiGrid,
16791 mi_row: usize,
16792 mi_col: usize,
16793 bw4: usize,
16794 bh4: usize,
16795 mi_cols: usize,
16796 mi_rows: usize,
16797 ref_frame: i8,
16798) -> u8 {
16799 find_samples(grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame).len() as u8
16800}
16801
16802/// `av1_get_obmc_mask` (`reconinter.c`): the per-position blend weight
16803/// (`AOM_BLEND_A64` numerator, out of 64) for the neighbour's own
16804/// contribution's *complement* -- i.e. `dst = (mask*orig + (64-mask)*nbr +
16805/// 32) >> 6`, low near the shared border (heavier neighbour weight) rising
16806/// to 64 (no neighbour contribution) away from it. Only the lengths this
16807/// decoder's own overlap sizes ever produce (luma 8/16/32, chroma 4/8/16)
16808/// are transcribed.
16809fn obmc_mask(len: usize) -> &'static [u8] {
16810 // lane-gmaffine r1: the two SHORT masks (libaom `reconinter.c`
16811 // `obmc_mask_1`/`obmc_mask_2`) -- an 8x8 leaf's chroma plane is 4x4, so
16812 // its overlap is 2 (and 1 at a half-block edge). Unreachable until this
16813 // round wired interior 16x16 splits down to real 8x8 leaves, where the
16814 // old `unreachable!()` below fired as a hard panic.
16815 const M1: [u8; 1] = [64];
16816 // lane-inter8 r1: `obmc_mask_2` (`reconinter.c` 753) -- reached by the
16817 // LEFT pass of an 8x8 block's chroma plane (overlap 4 luma columns, 2
16818 // chroma), which only became live once 8x8 inter leaves stopped being
16819 // refused.
16820 const M2: [u8; 2] = [45, 64];
16821 const M4: [u8; 4] = [39, 50, 59, 64];
16822 const M8: [u8; 8] = [36, 42, 48, 53, 57, 61, 64, 64];
16823 const M16: [u8; 16] = [
16824 34, 37, 40, 43, 46, 49, 52, 54, 56, 58, 60, 61, 64, 64, 64, 64,
16825 ];
16826 const M32: [u8; 32] = [
16827 33, 35, 36, 38, 40, 41, 43, 44, 45, 47, 48, 50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 60,
16828 61, 62, 64, 64, 64, 64, 64, 64, 64, 64,
16829 ];
16830 match len {
16831 1 => &M1,
16832 2 => &M2,
16833 4 => &M4,
16834 8 => &M8,
16835 16 => &M16,
16836 32 => &M32,
16837 _ => unreachable!("obmc overlap length outside this decoder's own block-size range"),
16838 }
16839}
16840
16841/// A bordering block's own resolved interp filter kernel, `(h, v)` --
16842/// mirrors [`resolve_interp_filter`]'s own return order from its stored
16843/// `[u8; 2]` (`Neighbours::above_filter`/`left_filter`, `[sym0, sym1]` =
16844/// `[v_sym, h_sym]`). The `[3, 3]` sentinel is only ever stored for an intra
16845/// neighbour (excluded by [`overlappable_above`]/[`overlappable_left`]'s
16846/// `is_inter` gate) or when `interp_fixed` is `Some` for the whole frame
16847/// (handled here first) -- so a sentinel reaching the kernel lookup means the
16848/// stream desynced upstream, and this refuses instead of panicking.
16849fn neighbour_filter(
16850 interp_fixed: Option<mc::InterpFilterKind>,
16851 sym: [u8; 2],
16852) -> Result<(mc::InterpFilterKind, mc::InterpFilterKind)> {
16853 if let Some(kind) = interp_fixed {
16854 return Ok((kind, kind));
16855 }
16856 // lane-interp3 r1: the `[3, 3]` sentinel reaching here is a DEFECT in
16857 // whatever path recorded the neighbour (an inter block that never stored
16858 // its own switchable symbols), and it used to abort the process through
16859 // `from_switchable_symbol`'s panic. A decoder must never crash on a real
16860 // stream: it stops by name instead, so the frame is refused and the
16861 // stream is pinned like every other unsupported case.
16862 if sym[0] > 2 || sym[1] > 2 {
16863 return Err(unsupported(
16864 "an OBMC neighbour whose interp filter was never recorded (no switchable symbol for that block)",
16865 ));
16866 }
16867 Ok((
16868 mc::InterpFilterKind::from_switchable_symbol(sym[1] as usize),
16869 mc::InterpFilterKind::from_switchable_symbol(sym[0] as usize),
16870 ))
16871}
16872
16873/// One neighbour's own re-prediction over a `w`x`h` region, MC'd fresh
16874/// against its own `mv`/reference/filter (libaom `av1_build_inter_predictor`
16875/// under `av1_setup_build_prediction_by_{above,left}_pred`).
16876#[allow(clippy::too_many_arguments)]
16877fn obmc_neighbour_pred(
16878 refplane: &PlaneBuf,
16879 x: usize,
16880 y: usize,
16881 mv: (i32, i32),
16882 w: usize,
16883 h: usize,
16884 luma: bool,
16885 h_kind: mc::InterpFilterKind,
16886 v_kind: mc::InterpFilterKind,
16887 // lane-scaledref r1: spec 7.11.3.3's x_scale_fp for THIS neighbour's own
16888 // reference (derived from luma widths, applied unchanged to chroma whose
16889 // x_q4 is already in its own plane's pixel units). `REF_NO_SCALE` takes
16890 // the ordinary stride-1 path bit-exact.
16891 x_scale_fp: i64,
16892) -> Vec<u16> {
16893 let mut out = vec![0u16; w * h];
16894 if x_scale_fp == mc::REF_NO_SCALE {
16895 mc::predict_with_filters(
16896 &refplane.data,
16897 refplane.width,
16898 refplane.true_width,
16899 refplane.true_height,
16900 mv_to_q4(x, mv.1, luma),
16901 mv_to_q4(y, mv.0, luma),
16902 w,
16903 h,
16904 h_kind,
16905 v_kind,
16906 &mut out,
16907 );
16908 } else {
16909 mc::predict_scaled(
16910 &refplane.data,
16911 refplane.width,
16912 refplane.true_width,
16913 refplane.true_height,
16914 mv_to_q4(x, mv.1, luma),
16915 mv_to_q4(y, mv.0, luma),
16916 x_scale_fp,
16917 w,
16918 h,
16919 h_kind,
16920 v_kind,
16921 &mut out,
16922 );
16923 }
16924 out
16925}
16926
16927/// Blends `tmp` into `dst` (stride `stride`) at `(ox, oy)`, mask varying by
16928/// row (the above-neighbour pass, `aom_blend_a64_vmask`).
16929/// `ii_weights1d` (reconinter.c:524): the interintra smooth-mask falloff.
16930const II_WEIGHTS_1D: [u8; 128] = [
16931 60, 58, 56, 54, 52, 50, 48, 47, 45, 44, 42, 41, 39, 38, 37, 35, 34, 33, 32,
16932 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 22, 21, 20, 19, 19, 18, 18, 17, 16,
16933 16, 15, 15, 14, 14, 13, 13, 12, 12, 12, 11, 11, 10, 10, 10, 9, 9, 9, 8,
16934 8, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4,
16935 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2,
16936 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1,
16937 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
16938];
16939
16940/// lane-interintra r1: non-wedge interintra prediction for one plane
16941/// (reconinter.c `av1_build_interintra_predictor` + `combine_interintra` +
16942/// `build_smooth_interintra_mask`). Builds the intra predictor for the
16943/// block's II mode (DC/V/H/SMOOTH, angle 0, no filter-intra) from `plane`'s
16944/// own decoded edges at `(x, y)`, then blends it over the inter prediction
16945/// in `pred`: `comp = (mask*intra + (64-mask)*inter + 32) >> 6`
16946/// (`aom_blend_a64_mask`, intra as src0). `ii_size_scales[plane_bsize]`
16947/// reduces to `128 / side` for the square plane sizes this decoder reaches.
16948/// lane-wii r2: `wedge == Some(..)` replaces the mode mask with the wedge
16949/// codebook mask (fixed sign 0; luma stride, 2x2 box-averaged for chroma).
16950fn interintra_blend(
16951 plane: &PlaneBuf,
16952 x: usize,
16953 y: usize,
16954 side: usize,
16955 ii_mode: u8,
16956 wedge: Option<(&'static [u8], usize)>,
16957 pred: &mut [u16],
16958) {
16959 // `interintra_to_intra_mode`: II_DC/II_V/II_H/II_SMOOTH.
16960 let intra_mode = match ii_mode {
16961 0 => crate::intra::DC_PRED,
16962 1 => crate::intra::V_PRED,
16963 2 => crate::intra::H_PRED,
16964 _ => crate::intra::SMOOTH_PRED,
16965 };
16966 let (above, left, corner) = plane.edges(
16967 x,
16968 y,
16969 side,
16970 crate::encode::Reach {
16971 above_right: false,
16972 below_left: false,
16973 },
16974 );
16975 let mut intra = vec![0u16; side * side];
16976 // Edge filtering never applies here: V/H at delta 0 are plain edge
16977 // copies (angle 90/180 skip the directional walk), DC/SMOOTH carry no
16978 // angle at all.
16979 predict(
16980 intra_mode,
16981 0,
16982 above.as_deref(),
16983 left.as_deref(),
16984 corner,
16985 side,
16986 side,
16987 false,
16988 false,
16989 &mut intra,
16990 );
16991 let scale = 128 / side;
16992 for i in 0..side {
16993 for j in 0..side {
16994 let m = u32::from(match wedge {
16995 // lane-wii r2: wedge-interintra mask (aom_blend_a64_mask
16996 // over the wedge codebook, intra as src0, fixed sign 0).
16997 // Luma plane: mask rows are luma-resolution, ms == side.
16998 // 4:2:0 chroma: 2x2 box average (reconinter.c sub8x8 --
16999 // subw == subh == 1).
17000 Some((mask, ms)) if ms == side => mask[i * side + j],
17001 Some((mask, ms)) => {
17002 let t = 2 * i * ms + 2 * j;
17003 ((u32::from(mask[t])
17004 + u32::from(mask[t + 1])
17005 + u32::from(mask[t + ms])
17006 + u32::from(mask[t + ms + 1])
17007 + 2)
17008 >> 2) as u8
17009 }
17010 None => match ii_mode {
17011 0 => 32,
17012 1 => II_WEIGHTS_1D[i * scale],
17013 2 => II_WEIGHTS_1D[j * scale],
17014 _ => II_WEIGHTS_1D[i.min(j) * scale],
17015 },
17016 });
17017 let idx = i * side + j;
17018 pred[idx] =
17019 ((m * u32::from(intra[idx]) + (64 - m) * u32::from(pred[idx]) + 32) >> 6) as u16;
17020 }
17021 }
17022}
17023
17024fn obmc_blend_v(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u16]) {
17025 let mask = obmc_mask(h);
17026 for row in 0..h {
17027 let m = u32::from(mask[row]);
17028 for col in 0..w {
17029 let d = &mut dst[(oy + row) * stride + ox + col];
17030 let t = u32::from(tmp[row * w + col]);
17031 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
17032 }
17033 }
17034}
17035
17036/// Blends `tmp` into `dst` at `(ox, oy)`, mask varying by column (the
17037/// left-neighbour pass, `aom_blend_a64_hmask`).
17038fn obmc_blend_h(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u16]) {
17039 let mask = obmc_mask(w);
17040 for row in 0..h {
17041 for col in 0..w {
17042 let m = u32::from(mask[col]);
17043 let d = &mut dst[(oy + row) * stride + ox + col];
17044 let t = u32::from(tmp[row * w + col]);
17045 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
17046 }
17047 }
17048}
17049
17050/// libaom's own `BLOCK_SIZE` enum index for a `w4`x`h4` (mi-unit) block --
17051/// only for the `EC_OBMC` trace rung below, so it reads byte-identical to
17052/// the instrumented aomdec's `backup_mbmi.bsize`.
17053fn ec_obmc_bsize(w4: usize, h4: usize) -> i32 {
17054 match (w4, h4) {
17055 (1, 1) => 0,
17056 (1, 2) => 1,
17057 (2, 1) => 2,
17058 (2, 2) => 3,
17059 (2, 4) => 4,
17060 (4, 2) => 5,
17061 (4, 4) => 6,
17062 (4, 8) => 7,
17063 (8, 4) => 8,
17064 (8, 8) => 9,
17065 (8, 16) => 10,
17066 (16, 8) => 11,
17067 (16, 16) => 12,
17068 (1, 4) => 16,
17069 (4, 1) => 17,
17070 (2, 8) => 18,
17071 (8, 2) => 19,
17072 (4, 16) => 20,
17073 (16, 4) => 21,
17074 _ => -1,
17075 }
17076}
17077
17078/// The `EC_OBMC` rung: one line per blended neighbour, in the instrumented
17079/// aomdec's own byte format (`decodeframe.c`
17080/// `dec_build_prediction_by_{above,left}_pred`), so the two decoders' OBMC
17081/// neighbour lists diff line for line. `filt` is libaom's packed
17082/// `interp_filters.as_int` = `y_filter | (x_filter << 16)`.
17083#[allow(clippy::too_many_arguments)]
17084fn ec_obmc_trace(
17085 dir: &str,
17086 mi_row: usize,
17087 mi_col: usize,
17088 write_w: usize,
17089 write_h: usize,
17090 rel: usize,
17091 op: usize,
17092 nb: &MiInfo,
17093 h_kind: mc::InterpFilterKind,
17094 v_kind: mc::InterpFilterKind,
17095) {
17096 if std::env::var_os("EC_OBMC").is_none() {
17097 return;
17098 }
17099 let sym = |k: mc::InterpFilterKind| match k {
17100 mc::InterpFilterKind::Smooth => 1u32,
17101 mc::InterpFilterKind::Sharp => 2,
17102 _ => 0,
17103 };
17104 eprintln!(
17105 "EC_OBMC {dir} mi=({mi_row},{mi_col}) wh=({write_w}x{write_h}) rel={rel} op={op} \
17106nbmv=({},{}) nbref={} nbbsize={} filt={}",
17107 nb.mv.0,
17108 nb.mv.1,
17109 nb.ref_frame,
17110 ec_obmc_bsize(nb.size, nb.size_h),
17111 sym(v_kind) | (sym(h_kind) << 16),
17112 );
17113}
17114
17115/// `av1_build_obmc_inter_prediction` (libaom `reconinter.c`): re-predicts
17116/// the overlap strip against each bordering above/left inter neighbour's own
17117/// mv/ref/filter and blends it into this block's just-built single-reference
17118/// prediction, luma then both 4:2:0 chroma planes -- above pass first, then
17119/// left, each reading only the *original* prediction this function was
17120/// handed (never the other pass's own output), matching libaom's own
17121/// independence between the two. `max_neighbor_obmc`'s own cap table
17122/// (`{0,1,2,3,4,4}` indexed by `mi_size_wide_log2`/`_high_log2`, this
17123/// decoder's own square blocks always index the same value both ways) bounds
17124/// how many bordering blocks actually get blended, separate from the
17125/// eligibility scan's own unbounded ("any at all") walk.
17126#[allow(clippy::too_many_arguments)]
17127fn obmc_blend(
17128 grid: &MiGrid,
17129 neighbours: &Neighbours,
17130 mi_row: usize,
17131 mi_col: usize,
17132 bw4: usize,
17133 bh4: usize,
17134 mi_rows: usize,
17135 mi_cols: usize,
17136 side: usize,
17137 write_w: usize,
17138 write_h: usize,
17139 chroma_side: usize,
17140 px: usize,
17141 py: usize,
17142 cpx: usize,
17143 cpy: usize,
17144 ref_y: &PlaneBuf,
17145 ref_u: &PlaneBuf,
17146 ref_v: &PlaneBuf,
17147 other_refs: &RefSlots,
17148 interp_fixed: Option<mc::InterpFilterKind>,
17149 // lane-scaledref r1: this frame's own coded luma width -- each OBMC
17150 // neighbour is re-predicted against ITS OWN reference, which may be
17151 // scaled differently from this block's (spec 7.11.3.3 / libaom
17152 // `av1_setup_build_prediction_by_above_pred` passing that ref's own
17153 // `scale_factors`).
17154 frame_width: usize,
17155 pred_y: &mut [u16],
17156 pred_u: &mut [u16],
17157 pred_v: &mut [u16],
17158) -> Result<()> {
17159 // lane-rect r2 (libaom av1_build_obmc_inter_prediction): each pass has
17160 // its OWN neighbour cap (width-log2 for above, height-log2 for left) and
17161 // overlap (bh/2 rows above, bw/2 cols left) -- one square `side` was
17162 // right only for square blocks.
17163 // libaom `max_neighbor_obmc[6] = { 0, 1, 2, 3, 4, 4 }` indexed by
17164 // `mi_size_wide_log2[bsize]` (above pass) / `mi_size_high_log2` (left):
17165 // 1 mi -> 0, 2 -> 1, 4 -> 2, 8 -> 3, 16+ -> 4. lane-inter4 r3: the old
17166 // `1..=4 => 2` row was right only for blocks at least 16 px on that axis
17167 // -- a 16x8 leaf's LEFT pass (bh4 = 2) walked up to two neighbours where
17168 // libaom walks one, blending an extra 8-px-tall neighbour into every
17169 // rect leaf with two of them on its left edge (class table-narrowed-to-
17170 // the-reachable-sizes; the square gates could never expose it).
17171 let max_nb = |n4: usize| match n4 {
17172 0..=1 => 0,
17173 2 => 1,
17174 3..=4 => 2,
17175 5..=8 => 3,
17176 _ => 4,
17177 };
17178 // lane-inter4 r4: r3 refused OBMC on a 16x8/8x16 leaf (5302 luma pixels
17179 // of one frame wrong). Re-measured on this tree with an `EC_OBMC` rung in
17180 // both decoders on that exact stream: the neighbour lists agree entry for
17181 // entry (position, span, mv, ref, size, filter) and all six pre-filter
17182 // frames are byte-identical to the instrumented aomdec's. The refusal is
17183 // gone; the counter below is what the gate's `--enable-obmc=1` arm reads.
17184 // The only decode-path change between r3's measurement and this one is the
17185 // lane-interbis merge (`build_motion_field`'s compound slot walk), which
17186 // moves temporal MV candidates -- not bisected further.
17187 if matches!((write_w, write_h), (16, 8) | (8, 16)) {
17188 OBMC_RECT_LEAF_HITS.with(|c| c.set(c.get() + 1));
17189 }
17190 // lane-sb128c r1: libaom caps the overlap strip at a 64x64 block's own
17191 // half (`reconinter.c` 860/899: `AOMMIN(block_size_high[bsize],
17192 // block_size_high[BLOCK_64X64]) >> 1`, and the `block_size_wide` mirror) --
17193 // inert below 128, where a 128x128 block would otherwise blend a 64-row
17194 // strip `obmc_mask` has no table for.
17195 let overlap_above = write_h.min(64) / 2;
17196 let overlap_left = write_w.min(64) / 2;
17197 // lane-inter8 r1 / lane-scaledref r1: `av1_skip_u4x4_pred_in_obmc`
17198 // (`reconinter.c` 820, `DISABLE_CHROMA_U8X8_OBMC == 0` -- "one-sided
17199 // obmc") returns `dir == 0` when the chroma plane's own block is
17200 // BLOCK_4X4/8X4/4X8 (an 8x8, 16x8 or 8x16 luma block at 4:2:0): the
17201 // ABOVE pass skips chroma entirely, the LEFT pass still blends it.
17202 let skip_chroma_above = matches!((write_w, write_h), (8, 8) | (16, 8) | (8, 16));
17203
17204 for (off4, span4, nb) in overlappable_above(grid, mi_row, mi_col, bw4, mi_cols, max_nb(bw4))
17205 {
17206 // `Neighbours::above_filter` is indexed in `SUB`(16px)-wide columns
17207 // (this decoder's own outer block-loop granularity), one step
17208 // coarser than the mi(4px) units `overlappable_above` walks in --
17209 // divide back down to that column.
17210 // lane-gmaffine r2: the neighbour's OWN mi-granular filter
17211 // (libaom `av1_setup_build_prediction_by_above_pred` reads
17212 // `above_mbmi->interp_filters`); the 16px-granular `Neighbours` slot
17213 // stays as the fallback for paths that do not record one yet
17214 // (compound), which is what every earlier round used.
17215 let (h_kind, v_kind) = neighbour_filter(
17216 interp_fixed,
17217 neighbours.above_filter[mi_col + off4],
17218 )?;
17219 ec_obmc_trace("above", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind);
17220 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
17221 let nb_scale = mc::scale_factor(ny.width, frame_width);
17222 let (bw, bh, ox) = (span4 * 4, overlap_above, off4 * 4);
17223 let tmp_y = obmc_neighbour_pred(ny, px + ox, py, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale);
17224 obmc_blend_v(pred_y, side, ox, 0, bw, bh, &tmp_y);
17225 if !skip_chroma_above {
17226 let (cbw, cbh, cox) = (bw / 2, overlap_above / 2, ox / 2);
17227 let tmp_u = obmc_neighbour_pred(nu, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
17228 obmc_blend_v(pred_u, chroma_side, cox, 0, cbw, cbh, &tmp_u);
17229 let tmp_v = obmc_neighbour_pred(nv, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
17230 obmc_blend_v(pred_v, chroma_side, cox, 0, cbw, cbh, &tmp_v);
17231 }
17232 }
17233
17234 for (off4, span4, nb) in overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, max_nb(bh4)) {
17235 let (h_kind, v_kind) = neighbour_filter(
17236 interp_fixed,
17237 neighbours.left_filter[mi_row + off4],
17238 )?;
17239 ec_obmc_trace("left", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind);
17240 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
17241 let nb_scale = mc::scale_factor(ny.width, frame_width);
17242 let (bw, bh, oy) = (overlap_left, span4 * 4, off4 * 4);
17243 let tmp_y = obmc_neighbour_pred(ny, px, py + oy, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale);
17244 obmc_blend_h(pred_y, side, 0, oy, bw, bh, &tmp_y);
17245 let (cbw, cbh, coy) = (overlap_left / 2, bh / 2, oy / 2);
17246 let tmp_u = obmc_neighbour_pred(nu, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
17247 obmc_blend_h(pred_u, chroma_side, 0, coy, cbw, cbh, &tmp_u);
17248 let tmp_v = obmc_neighbour_pred(nv, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
17249 obmc_blend_h(pred_v, chroma_side, 0, coy, cbw, cbh, &tmp_v);
17250 }
17251 Ok(())
17252}
17253
17254/// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to
17255/// the square block sizes this decoder ever decodes (32/16/8, all
17256/// `min(w,h) >= 8`, `is_comp_ref_allowed` true): `COMPOUND_DIFFWTD` is then
17257/// always `is_interinter_compound_used`, so the function is always `true`
17258/// for `side` -- kept as a named call (rather than inlined `true`) so a
17259/// future sub-8 block size does not silently misdecode a real stream.
17260fn is_any_masked_compound_used_here(bw: usize, bh: usize) -> bool {
17261 // lane-inter16ab r4 (class sweep of the r3 CDF-row defect):
17262 // `is_comp_ref_allowed(bsize)` is `AOMMIN(block_size_wide, block_size_high)
17263 // >= 8` on the block's TRUE footprint -- a 16x4/4x16 strip is NOT allowed,
17264 // so libaom writes no `comp_group_idx` symbol there at all. Keyed off the
17265 // square `side` we read one the reference never wrote.
17266 bw.min(bh) >= 8
17267}
17268
17269/// The `BLOCK_SIZES_ALL` index of a `bw x bh` block (libaom `enum BLOCK_SIZE`,
17270/// `blockd.h`) -- the row every size-indexed inter CDF table
17271/// (`compound_type_cdf`, `wedge_idx_cdf`) is keyed by. Our `decode_inter_block`
17272/// carries the enclosing SQUARE `side` for context purposes (the accepted
17273/// strip corner-cut), so a 16x8 / 8x16 PARTITION_HORZ/VERT strip that reads
17274/// one of those symbols off `side` alone takes BLOCK_16X16's row and desyncs
17275/// (lane-inter16ab r3: a real 16x8 compound strip with `comp_group_idx == 1`,
17276/// decode-order frame 5, our range 64901 vs the oracle's 47271 at the very
17277/// next block's mode read).
17278fn bsize_all_index(bw: usize, bh: usize) -> Option<usize> {
17279 Some(match (bw, bh) {
17280 (4, 4) => 0,
17281 (4, 8) => 1,
17282 (8, 4) => 2,
17283 (8, 8) => 3,
17284 (8, 16) => 4,
17285 (16, 8) => 5,
17286 (16, 16) => 6,
17287 (16, 32) => 7,
17288 (32, 16) => 8,
17289 (32, 32) => 9,
17290 (32, 64) => 10,
17291 (64, 32) => 11,
17292 (64, 64) => 12,
17293 (64, 128) => 13,
17294 (128, 64) => 14,
17295 (128, 128) => 15,
17296 (4, 16) => 16,
17297 (16, 4) => 17,
17298 (8, 32) => 18,
17299 (32, 8) => 19,
17300 (16, 64) => 20,
17301 (64, 16) => 21,
17302 _ => return None,
17303 })
17304}
17305
17306/// `av1_wedge_params_lookup[bsize].wedge_types > 0` (libaom `reconinter.c`):
17307/// the block sizes that carry a wedge codebook at all. A `compound_type`
17308/// symbol is written only for these; every other size infers
17309/// `COMPOUND_DIFFWTD`.
17310fn wedge_used_bsize(bw: usize, bh: usize) -> bool {
17311 matches!(
17312 (bw, bh),
17313 (8, 8) | (8, 16) | (16, 8) | (16, 16) | (16, 32) | (32, 16) | (32, 32) | (8, 32) | (32, 8)
17314 )
17315}
17316
17317/// libaom's `BLOCK_SIZES_ALL` index of a `w`x`h` block (`common_data.h`'s own
17318/// enum order) -- the row every bsize-indexed CDF (`compound_type_cdf`,
17319/// `wedge_idx_cdf`) is read at. lane-intersub8 r4: these two used to be
17320/// indexed by the caller's SQUARE envelope, so a 16x8 compound block read
17321/// `BLOCK_16X16`'s row (class table-indexed-by-raw-size) and desynced the
17322/// tile at its first masked-compound rect block.
17323fn bsize_index(w: usize, h: usize) -> Option<usize> {
17324 Some(match (w, h) {
17325 (4, 4) => 0,
17326 (4, 8) => 1,
17327 (8, 4) => 2,
17328 (8, 8) => 3,
17329 (8, 16) => 4,
17330 (16, 8) => 5,
17331 (16, 16) => 6,
17332 (16, 32) => 7,
17333 (32, 16) => 8,
17334 (32, 32) => 9,
17335 (32, 64) => 10,
17336 (64, 32) => 11,
17337 (64, 64) => 12,
17338 (64, 128) => 13,
17339 (128, 64) => 14,
17340 (128, 128) => 15,
17341 (4, 16) => 16,
17342 (16, 4) => 17,
17343 (8, 32) => 18,
17344 (32, 8) => 19,
17345 (16, 64) => 20,
17346 (64, 16) => 21,
17347 _ => return None,
17348 })
17349}
17350
17351/// `is_any_masked_compound_used` (libaom `reconinter.h`) on the block's TRUE
17352/// footprint: `is_comp_ref_allowed` is `AOMMIN(bw, bh) >= 8`, and every
17353/// shape that clears it has either a wedge or a DIFFWTD compound available.
17354fn masked_compound_used_wh(w: usize, h: usize) -> bool {
17355 w.min(h) >= 8
17356}
17357
17358/// `av1_wedge_params_lookup[bsize].wedge_types > 0` (libaom `reconinter.c`):
17359/// the shapes whose `compound_type` symbol is really coded. Everything else
17360/// with a compound mask infers `COMPOUND_DIFFWTD` without a symbol.
17361fn wedge_used_wh(w: usize, h: usize) -> bool {
17362 matches!(
17363 (w, h),
17364 (8, 8)
17365 | (8, 16)
17366 | (16, 8)
17367 | (16, 16)
17368 | (16, 32)
17369 | (32, 16)
17370 | (32, 32)
17371 | (8, 32)
17372 | (32, 8)
17373 | (16, 64)
17374 | (64, 16)
17375 )
17376}
17377
17378/// Whether a compound reference pair is unidirectional (both references on
17379/// the same temporal side of the current frame) -- `has_uni_comp_refs`
17380/// (libaom `av1_reference_frame_utils.h`/`pred_common.c`'s own definition:
17381/// a pair is `UNIDIR_COMP_REFERENCE` exactly when neither reference is
17382/// backward-while-the-other-is-forward, i.e. `is_backward(ref0) ==
17383/// is_backward(ref1)`). Used to build a real
17384/// [`crate::mvstack::NeighbourRef::uni`] once `ref1` is known, matching
17385/// [`crate::mvstack::comp_reference_type_ctx`]'s own `is_backward` calls.
17386fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool {
17387 let backward = |r: i8| (BWDREF_FRAME..=ALTREF_FRAME).contains(&r);
17388 backward(ref0) == backward(ref1)
17389}
17390
17391/// `get_comp_group_idx_context` (libaom `pred_common.h`): sums the
17392/// above/left neighbour contributions [`Neighbours::record_inter`]/
17393/// [`Neighbours::record_compound_ctx`] already precomputed, clamped to 5.
17394/// lane-inter8 r2: `at_mi` is the block's own top-left in 4x4 mi units --
17395/// an 8x8 leaf used to pass its enclosing 16x16's corner here, so all four
17396/// leaves read the same neighbour cell (class context-read-from-one-cell).
17397fn get_comp_group_idx_context(
17398 neighbours: &Neighbours,
17399 at_mi: (usize, usize),
17400 side: usize,
17401) -> usize {
17402 let _ = side;
17403 let (rmi, cmi) = at_mi;
17404 (neighbours.above_comp_group_idx[cmi] as usize + neighbours.left_comp_group_idx[rmi] as usize)
17405 .min(5)
17406}
17407
17408/// `get_comp_index_context` (libaom `pred_common.h`): the above/left
17409/// neighbour bits plus `3 * (fwd == bck)`, where `fwd`/`bck` are this
17410/// block's own two references' distances from the current frame (spec
17411/// 7.11.3.15's `get_relative_dist`, same convention
17412/// [`crate::compound::dist_wtd_comp_weight_assign`] uses).
17413#[allow(clippy::too_many_arguments)]
17414fn get_comp_index_context(
17415 neighbours: &Neighbours,
17416 at_mi: (usize, usize),
17417 side: usize,
17418 order_hint_bits: u32,
17419 cur_order_hint: u32,
17420 ref0_order_hint: u32,
17421 ref1_order_hint: u32,
17422) -> usize {
17423 let _ = side;
17424 let (rmi, cmi) = at_mi;
17425 let fwd =
17426 crate::motion_field::get_relative_dist(order_hint_bits, ref1_order_hint, cur_order_hint)
17427 .abs();
17428 let bck =
17429 crate::motion_field::get_relative_dist(order_hint_bits, cur_order_hint, ref0_order_hint)
17430 .abs();
17431 let offset = usize::from(fwd == bck);
17432 neighbours.above_compound_idx[cmi] as usize
17433 + neighbours.left_compound_idx[rmi] as usize
17434 + 3 * offset
17435}
17436
17437fn read_comp_mode(
17438 dec: &mut SymbolDecoder,
17439 cdfs: &mut Cdfs,
17440 above: Option<NeighbourRef>,
17441 left: Option<NeighbourRef>,
17442) -> bool {
17443 let ctx = reference_mode_ctx(above, left);
17444 let compound = dec.symbol(&mut cdfs.comp_mode[ctx]) == 1;
17445 if compound {
17446 COMP_MODE_HITS.with(|c| c.set(c.get() + 1));
17447 }
17448 compound
17449}
17450
17451/// Spec 5.11.25's `comp_reference_type` + the `uni_comp_ref`/`comp_ref`/
17452/// `comp_bwdref` trees (libaom `decodemv.c`'s `read_ref_frames` compound
17453/// arm), reached once [`read_comp_mode`] has already returned
17454/// `COMPOUND_REFERENCE`. Returns `(RefFrame[0], RefFrame[1])`.
17455/// `above`/`left` are [`comp_reference_type_ctx`]'s own `NeighbourRef`
17456/// convention; `above_ref`/`left_ref` are the scalar `1..=7`/`-1`
17457/// convention [`read_single_ref`] already uses, for every downstream binary
17458/// decision. libaom `pred_common.c`'s own compound context functions
17459/// (`av1_get_pred_context_uni_comp_ref_p[1|2]`, `comp_ref_p[1|2]`,
17460/// `comp_bwdref_p[1]`) turned out to be exactly [`single_ref_p1_ctx`]..
17461/// [`single_ref_p6_ctx`]/[`uni_comp_ref_p1_ctx`] under a different name
17462/// (same vote-the-neighbours-above-left shape, same forward/backward and
17463/// LAST/LAST2/LAST3/GOLDEN groupings) -- lane-av1comp audited each one
17464/// against the C source rather than porting six near-duplicate functions.
17465/// Its caller today only needs the symbols consumed, correctly, to keep the
17466/// arithmetic decoder's own state in sync before refusing the block by name
17467/// -- the returned pair is not yet threaded into any motion-compensation
17468/// path.
17469fn read_compound_ref_frames(
17470 dec: &mut SymbolDecoder,
17471 cdfs: &mut Cdfs,
17472 above: Option<NeighbourRef>,
17473 left: Option<NeighbourRef>,
17474 above_ref: i8,
17475 left_ref: i8,
17476) -> (i8, i8) {
17477 let a = (above_ref > 0).then_some(above_ref);
17478 let l = (left_ref > 0).then_some(left_ref);
17479 // libaom `av1_collect_neighbors_ref_counts` counts BOTH of a compound
17480 // neighbour's references, not just its first -- `a1`/`l1` carry that
17481 // second reference through to every vote below (lane-av1blend r6: a
17482 // missing `a1`/`l1` here was decoding `compound_idx` off the wrong CDF
17483 // row for a block sitting under a skip_mode-forced compound neighbour).
17484 let a1 = above.and_then(|n| n.ref1);
17485 let l1 = left.and_then(|n| n.ref1);
17486 let type_ctx = comp_reference_type_ctx(above, left);
17487 let unidir = dec.symbol(&mut cdfs.comp_ref_type[type_ctx]) == 0;
17488 if unidir {
17489 UNI_COMP_HITS.with(|c| c.set(c.get() + 1));
17490 // uni_comp_ref (p0): forward vs. backward -- av1_get_pred_context_-
17491 // uni_comp_ref_p is single_ref_p1's own forward/backward vote.
17492 let bit = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0]);
17493 if bit == 1 {
17494 (BWDREF_FRAME, ALTREF_FRAME)
17495 } else {
17496 let p1 = dec.symbol(&mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1]);
17497 if p1 == 1 {
17498 // uni_comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
17499 let p2 = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
17500 if p2 == 1 {
17501 (LAST_FRAME, GOLDEN_FRAME)
17502 } else {
17503 (LAST_FRAME, LAST3_FRAME)
17504 }
17505 } else {
17506 (LAST_FRAME, LAST2_FRAME)
17507 }
17508 }
17509 } else {
17510 // comp_ref (p0): LAST/LAST2 vs. LAST3/GOLDEN, same vote as single_ref_p3.
17511 let bit0 = dec.symbol(&mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0]);
17512 let ref0 = if bit0 == 0 {
17513 // comp_ref_p1: LAST vs. LAST2, same vote as single_ref_p4.
17514 let p1 = dec.symbol(&mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1]);
17515 if p1 == 1 { LAST2_FRAME } else { LAST_FRAME }
17516 } else {
17517 // comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
17518 let p2 = dec.symbol(&mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
17519 if p2 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
17520 };
17521 // comp_bwdref (p0): BWDREF/ALTREF2 vs. ALTREF, same vote as single_ref_p2.
17522 let bit1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0]);
17523 let ref1 = if bit1 == 0 {
17524 // comp_bwdref_p1: BWDREF vs. ALTREF2, same vote as single_ref_p6.
17525 let p1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1]);
17526 if p1 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
17527 } else {
17528 ALTREF_FRAME
17529 };
17530 (ref0, ref1)
17531 }
17532}
17533
17534/// Spec 5.11.24's `compound_mode` (lane-av1comp): which of the eight
17535/// `INTER_COMPOUND_MODES` (`NEAREST_NEARESTMV`..`NEW_NEWMV`, returned as
17536/// `0..=7`) a `COMPOUND_REFERENCE` block takes, reached once
17537/// [`read_comp_mode`] has already returned `COMPOUND_REFERENCE`. `ctx` is
17538/// libaom's `av1_mode_context_analyzer`'s compound branch --
17539/// `compound_mode_ctx_map[ref_mv_ctx >> 1][min(new_mv_ctx, COMP_NEWMV_CTXS
17540/// - 1)]` (`mvref_common.h`) -- folded from [`crate::mvstack::
17541/// find_mv_stack_compound`]'s own `new_mv_ctx`/`ref_mv_ctx`. The read symbol
17542/// is not yet turned into an assigned MV pair or motion-compensated --
17543/// lane-av1comp.
17544fn read_inter_compound_mode(
17545 dec: &mut SymbolDecoder,
17546 cdfs: &mut Cdfs,
17547 new_mv_ctx: usize,
17548 ref_mv_ctx: usize,
17549) -> u8 {
17550 let ctx = cdf::COMPOUND_MODE_CTX_MAP[ref_mv_ctx >> 1][new_mv_ctx.min(4)];
17551 COMPOUND_MODE_HITS.with(|c| c.set(c.get() + 1));
17552 dec.symbol(&mut cdfs.inter_compound_mode[ctx]) as u8
17553}
17554
17555/// spec 7.10.2.10 `assign_mv`'s compound branch, plus the compound half of
17556/// `read_drl_idx` (spec 5.11.24) it depends on -- `mode` is
17557/// [`read_inter_compound_mode`]'s own `0..=7` (`NEAREST_NEARESTMV`..
17558/// `NEW_NEWMV`, libaom `enums.h` order). Every `GLOBAL_GLOBALMV` side reads
17559/// as `(0, 0)` since [`crate::stream::decode_stream`] already refuses any
17560/// non-`IDENTITY` global motion model before a tile is ever decoded.
17561///
17562/// Ported straight from libaom `decodemv.c`'s `read_drl_idx` (the
17563/// `NEW_NEWMV`/`have_nearmv_in_inter_mode` branches) and `assign_mv`/its
17564/// caller's `ref_mv[]`/`nearmv[]` setup: the `NEAR_NEWMV`/`NEW_NEARMV`
17565/// `1 + ref_mv_idx` special case is folded into `new_idx` below, matching
17566/// `read_drl_idx`'s own comment about "offsetting the NEARESTMV mode".
17567fn assign_compound_mv(
17568 dec: &mut SymbolDecoder,
17569 cdfs: &mut Cdfs,
17570 comp_stack: &crate::mvstack::CompoundMvStack,
17571 mode: u8,
17572 allow_high_precision_mv: bool,
17573 force_integer_mv: bool,
17574 // lane-gm r2: `gm_get_motion_vector(ref0)`/`(ref1)` at this block's own
17575 // position, spec 7.10.2.10's `GLOBAL_GLOBALMV` assignment.
17576 global_mv: ((i32, i32), (i32, i32)),
17577) -> ((i32, i32), (i32, i32)) {
17578 const NEAREST_NEARESTMV: u8 = 0;
17579 const NEAR_NEARMV: u8 = 1;
17580 const NEAREST_NEWMV: u8 = 2;
17581 const NEW_NEARESTMV: u8 = 3;
17582 const NEAR_NEWMV: u8 = 4;
17583 const NEW_NEARMV: u8 = 5;
17584 const GLOBAL_GLOBALMV: u8 = 6;
17585 const NEW_NEWMV: u8 = 7;
17586
17587 let mut ref_mv_idx = 0usize;
17588 if mode == NEW_NEWMV {
17589 let mut idx = 0usize;
17590 while idx < 2 && comp_stack.entries.len() > idx + 1 {
17591 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
17592 break;
17593 }
17594 idx += 1;
17595 }
17596 ref_mv_idx = idx;
17597 } else if matches!(mode, NEAR_NEARMV | NEAR_NEWMV | NEW_NEARMV) {
17598 let mut idx = 1usize;
17599 while idx < 3 && comp_stack.entries.len() > idx + 1 {
17600 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
17601 break;
17602 }
17603 idx += 1;
17604 }
17605 ref_mv_idx = idx - 1;
17606 }
17607
17608 let near = comp_stack
17609 .entries
17610 .get(ref_mv_idx + 1)
17611 .map_or(comp_stack.near_mv, |e| (e.mv0, e.mv1));
17612 let new_idx = if matches!(mode, NEAR_NEWMV | NEW_NEARMV) {
17613 ref_mv_idx + 1
17614 } else {
17615 ref_mv_idx
17616 };
17617 let new_pred = comp_stack
17618 .entries
17619 .get(new_idx)
17620 .map_or(comp_stack.nearest_mv, |e| (e.mv0, e.mv1));
17621
17622 let read_new = |dec: &mut SymbolDecoder, cdfs: &mut Cdfs, base: (i32, i32)| {
17623 read_mv(
17624 dec,
17625 &mut cdfs.mv_comp,
17626 &mut cdfs.mv_joint,
17627 base,
17628 allow_high_precision_mv,
17629 force_integer_mv,
17630 )
17631 };
17632
17633 match mode {
17634 NEAREST_NEARESTMV => comp_stack.nearest_mv,
17635 NEAR_NEARMV => near,
17636 NEAREST_NEWMV => (comp_stack.nearest_mv.0, read_new(dec, cdfs, new_pred.1)),
17637 NEW_NEARESTMV => (read_new(dec, cdfs, new_pred.0), comp_stack.nearest_mv.1),
17638 NEAR_NEWMV => (near.0, read_new(dec, cdfs, new_pred.1)),
17639 NEW_NEARMV => (read_new(dec, cdfs, new_pred.0), near.1),
17640 GLOBAL_GLOBALMV => global_mv,
17641 _ => (
17642 read_new(dec, cdfs, new_pred.0),
17643 read_new(dec, cdfs, new_pred.1),
17644 ),
17645 }
17646}
17647
17648/// Derives this query block's own [`crate::mvstack::GmMvTable`] -- one
17649/// `gm_get_motion_vector` (spec 7.10.2.1) result per reference frame, at
17650/// THIS block's own `(mi_row, mi_col, bw4, bh4)` (mvstack.rs's own doc: the
17651/// table is always computed at the *querying* block's position, never a
17652/// donating neighbour's).
17653fn build_gm_mv_table(
17654 global_motion: &[ec_av1_syntax::WarpParams; 7],
17655 mi_row: usize,
17656 mi_col: usize,
17657 bw4: usize,
17658 bh4: usize,
17659 allow_high_precision_mv: bool,
17660 force_integer_mv: bool,
17661) -> crate::mvstack::GmMvTable {
17662 std::array::from_fn(|i| {
17663 let gm = &global_motion[i];
17664 crate::warp::gm_get_motion_vector(
17665 gm.model,
17666 &gm.params,
17667 mi_row,
17668 mi_col,
17669 bw4,
17670 bh4,
17671 allow_high_precision_mv,
17672 force_integer_mv,
17673 )
17674 })
17675}
17676
17677/// Decodes one square inter-frame block (32x32 whole or 16x16 leaf): skip,
17678/// `is_inter`, then either the single-reference/MV-stack/motion-vector chain
17679/// and motion-compensated reconstruction, or the inter frame's own intra
17680/// path (`Y_MODE` by size group, not `KF_Y_MODE` by neighbour), mirroring
17681/// [`crate::tile`]'s `sb_coeff_inter_frame_tile`'s whole-block branch and its
17682/// private `write_inter_frame_leaf` -- both share this one function here,
17683/// parameterised by `side`/the transform sets/scan tables/size group they
17684/// each use.
17685///
17686/// # Errors
17687/// Returns an error when a symbol names anything this decoder does not
17688/// reconstruct: a reference other than `LAST_FRAME`, `GLOBALMV` (round 3;
17689/// `NEARESTMV`/`NEARMV`/`NEWMV` are all reconstructed), or an intra
17690/// mode/tx-type outside what [`read_intra_mode`]/[`read_coeffs`] already
17691/// refuse.
17692#[allow(clippy::too_many_arguments)]
17693/// lane-inter4 r1: 16-px-cell coordinates -> MI (4-px) coordinates, the unit
17694/// [`decode_inter_block`]'s `at` now takes.
17695const fn sub16_to_mi(t: (usize, usize)) -> (usize, usize) {
17696 (t.0 * (SUB / MI), t.1 * (SUB / MI))
17697}
17698
17699fn decode_inter_block(
17700 dec: &mut SymbolDecoder,
17701 cdfs: &mut Cdfs,
17702 neighbours: &mut Neighbours,
17703 grid: &mut MiGrid,
17704 at: (usize, usize),
17705 side: usize,
17706 mi_cols: u32,
17707 mi_rows: u32,
17708 y: &mut PlaneBuf,
17709 u: &mut PlaneBuf,
17710 v: &mut PlaneBuf,
17711 ref_y: &PlaneBuf,
17712 ref_u: &PlaneBuf,
17713 ref_v: &PlaneBuf,
17714 // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own
17715 // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]`
17716 // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME`
17717 // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the
17718 // slot's still empty (an error-resilient stream, or too early in the
17719 // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below.
17720 other_refs: &RefSlots,
17721 sign_bias_table: &SignBiasTable,
17722 // lane-gm r2: this frame header's own `global_motion` table (spec
17723 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` same as `sign_bias_table`
17724 // -- feeds `warp::gm_get_motion_vector` for `GLOBALMV`/`GLOBAL_GLOBALMV`
17725 // assignment and the mv-stack's neighbour substitution.
17726 global_motion: &[ec_av1_syntax::WarpParams; 7],
17727 base_q_idx: u8,
17728 luma_set_intra: TxbSet,
17729 luma_set_inter: TxbSet,
17730 chroma_set: TxbSet,
17731 luma_tx: usize,
17732 chroma_tx: usize,
17733 scan_luma: &[u16],
17734 scan_chroma: &[u16],
17735 // lane-inter4 r3: superseded by `size_group_wh(write_w, write_h)` at the
17736 // one site that read it (`y_mode`) -- a rect strip's group comes from its
17737 // true footprint, not the caller's square `side`. Kept in the signature
17738 // rather than editing twenty call sites.
17739 _size_group: usize,
17740 allow_high_precision_mv: bool,
17741 force_integer_mv: bool,
17742 interp_fixed: Option<mc::InterpFilterKind>,
17743 enable_dual_filter: bool,
17744 tpl_frame: Option<&TplFrameArgs>,
17745 // lane-av1comp: this frame header's own `reference_select` bit -- `false`
17746 // means every block is `SINGLE_REFERENCE` by construction and `comp_mode`
17747 // is never read (spec 5.11.25); `true` reads `comp_mode` per block and
17748 // refuses (rather than silently misdecoding) the ones that pick
17749 // `COMPOUND_REFERENCE`, since two-reference motion compensation is not
17750 // wired yet.
17751 reference_select: bool,
17752 // lane-av1comp: `seq_params`' own masked-compound/distance-weighted-
17753 // compound enable bits, gating `comp_group_idx`/`compound_idx`
17754 // (spec 5.11.25) -- always present (unlike `tpl_frame`), since the
17755 // compound blend weights need this frame's own order hint regardless
17756 // of `use_ref_frame_mvs`.
17757 enable_masked_compound: bool,
17758 // lane-sb128 r4: this sequence header's own `enable_interintra_compound`
17759 // bit (spec 5.11.24's `interintra` read, libaom `decodemv.c`
17760 // read_inter_block_mode_info ~1490-1510) -- read right after `assign_mv`
17761 // and before `read_motion_mode` on the single-ref path below, gated by
17762 // `is_interintra_allowed` (single-ref, `BLOCK_8X8..=BLOCK_32X32`, and
17763 // every mode this single-ref branch can produce is already in
17764 // `SINGLE_INTER_MODE_START..END`); `interintra == 1` is a named refusal
17765 // (inter+intra blended prediction unimplemented) rather than a
17766 // mis-decode.
17767 enable_interintra_compound: bool,
17768 enable_jnt_comp: bool,
17769 order_hint_bits: u32,
17770 order_hint: u32,
17771 ref_order_hints: [u32; 7],
17772 // lane-av1comp round 14: this frame header's own `skip_mode_present` bit
17773 // and `skip_mode_frame` reference pair (spec 5.9.22, `frame.rs`'s
17774 // `read_skip_mode_params`, already 1-based `MV_REFERENCE_FRAME`) --
17775 // `skip_mode` (spec 5.11.23 `read_skip_mode`) is read *before* `skip`
17776 // when this is `true` (every block this decoder reaches is >= 8x8, so
17777 // `is_comp_ref_allowed` never gates it further); a `true` result forces
17778 // `skip_txfm`, `is_inter`, `NEAREST_NEARESTMV` of this pair with no mode/
17779 // DRL symbol read, and a plain average blend with no `comp_group_idx`/
17780 // `compound_idx` read (libaom `decodemv.c` 1604-1619, 1382-1384, 1509).
17781 skip_mode_present: bool,
17782 skip_mode_frame: [u8; 2],
17783 // lane-motionmode round 1: this frame header's own `is_motion_mode_switchable`/
17784 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`).
17785 switchable_motion_mode: bool,
17786 allow_warped_motion: bool,
17787 // lane-warp r5: set by the HORZ_B arm -- the 32x16 top strip is decoded
17788 // as a square 32x32 block, which over-reads a residual unless coded
17789 // `skip`; a non-skip strip must refuse cleanly instead of desyncing.
17790 reject_residual: bool,
17791 // lane-partitions r1: the strip's own true width/height in pixels --
17792 // `side` keeps governing every syntax/CDF/prediction-buffer decision
17793 // (matching `HORZ_B`'s already-accepted square-context corner-cut), but
17794 // the final pixel write and this block's own neighbour-context stamp
17795 // (`record*`/`fill_*_grid`) use `write_w`/`write_h` instead, so a
17796 // PARTITION_HORZ/VERT strip only claims its own true footprint. `side`
17797 // for every existing (square) caller.
17798 write_w: usize,
17799 write_h: usize,
17800 // lane-screen r2: this frame header's own `allow_screen_content_tools`
17801 // bit, threaded to the intra-sub-block branch below -- libaom's
17802 // `read_intra_block_mode_info` (decodemv.c:1065-1107, the inter-frame
17803 // counterpart of `read_intra_frame_mode_info`) reads `y_mode_cdf`
17804 // (never `kf_y_mode_cdf`) and has NO `use_intrabc` call at all (that
17805 // symbol is intra-frame-only, spec `av1_read_mode_info` dispatches on
17806 // `frame_is_intra_only`), but it still calls `read_palette_mode_info`
17807 // under the same `av1_allow_palette` gate as the key-frame path.
17808 allow_screen_content_tools: bool,
17809 // lane-superres r9: this frame's own coded luma width (spec 7.11.3.3) --
17810 // compared against each reference's stored picture width to decide
17811 // whether a scaled-MC path (`mc::predict_scaled`) or the ordinary
17812 // stride-1 one (`mc::predict_with_filters`) applies per reference, and to
17813 // refuse (rather than mis-decode) the warp/OBMC/interintra/compound
17814 // combinations that don't implement scaled MC yet.
17815 frame_width: usize,
17816) -> Result<()> {
17817 // lane-inter4 r1: `at` is in MI units (4 px) so a 32-level 1:4 strip can
17818 // name an 8-px offset; `(r, c)` stays the enclosing 16-px cell for the
17819 // few 16-px-granular uses below.
17820 let (r, c) = (at.0 / (SUB / MI), at.1 / (SUB / MI));
17821 // lane-inter8 r2: the inter side bands are mi-granular; this block's own
17822 // above/left neighbour is the mi cell at its top-left corner (libaom
17823 // `above_mbmi` = mi(mi_row - 1, mi_col)), so a SUB-aligned block reads
17824 // exactly what it read before.
17825 let (rmi, cmi) = at;
17826 let (px, py) = (at.1 * MI, at.0 * MI);
17827 // lane-inter16ab r2: a 16x4 / 4x16 inter strip's chroma is the PAIR's
17828 // (8x4 / 4x8 at the even strip's origin) and is coded only by the odd
17829 // strip (`is_chroma_reference`); every other block keeps its own.
17830 let strip_chroma = INTER_STRIP_CHROMA.with(std::cell::Cell::take);
17831 INTER_LAST_MC.with(|c| c.set(None));
17832 let has_chroma = strip_chroma.is_none_or(|s| s.has_chroma);
17833 let (cpx, cpy) = match strip_chroma {
17834 Some(s) if s.has_chroma => (s.pair_mi.1 * MI / 2, s.pair_mi.0 * MI / 2),
17835 _ => (px / 2, py / 2),
17836 };
17837 let chroma_side = side / 2;
17838 let (write_chroma_w, write_chroma_h) = match strip_chroma {
17839 Some(s) if s.has_chroma => {
17840 if s.horz {
17841 (8, 4)
17842 } else {
17843 (4, 8)
17844 }
17845 }
17846 _ => (write_w / 2, write_h / 2),
17847 };
17848
17849 if std::env::var_os("EC_AV1_TELL").is_some() {
17850 eprintln!(
17851 "TELL mi_row={} mi_col={} label=block_entry side={side} tell={} range={}",
17852 rmi, cmi, dec.debug_bitpos(), dec.debug_state().0
17853 );
17854 }
17855 let skip_mode_ctx =
17856 usize::from(neighbours.above_skip_mode[cmi]) + usize::from(neighbours.left_skip_mode[rmi]);
17857 // lane-comppin r3: skip_mode desync isolation -- dump ctx + the pre-read
17858 // MSAC tell so it can be diffed against an equivalent hook in libaom's
17859 // own `read_skip_mode`/`av1_get_skip_mode_context`.
17860 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
17861 eprintln!(
17862 "EC_SKIPMODE r={r} c={c} ctx={skip_mode_ctx} skip_mode_present={skip_mode_present} tell_before={}",
17863 dec.debug_bitpos()
17864 );
17865 }
17866 // spec 5.11.5 `inter_frame_mode_info`: `inter_segment_id(1)` before
17867 // `skip_mode`/`skip`, `inter_segment_id(0)` after them.
17868 let (seg_mi_r, seg_mi_c) = (rmi, cmi);
17869 let (seg_w_mi, seg_h_mi) = (write_w / 4, write_h / 4);
17870 inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, false, true);
17871 // libaom `read_skip_mode` (decodemv.c): `if (!is_comp_ref_allowed(bsize))
17872 // return 0` -- a 16x4 / 4x16 strip (min(bw, bh) == 4, blockd.h:65) reads
17873 // no `skip_mode` symbol at all.
17874 let comp_allowed = write_w.min(write_h) >= 8;
17875 let skip_mode =
17876 skip_mode_present && comp_allowed && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
17877 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
17878 eprintln!(
17879 "EC_SKIPMODE r={r} c={c} result={skip_mode} tell_after={}",
17880 dec.debug_bitpos()
17881 );
17882 }
17883 if skip_mode {
17884 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
17885 }
17886
17887 let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]);
17888 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
17889 inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, skip, false);
17890 maybe_read_cdef_idx(dec, rmi, cmi, skip);
17891 // lane-inter4 r1: spec 5.11.6's `bSize == sbSize` -- a 64x32/64x16 strip
17892 // is NOT the whole superblock, so its `skip` never suppresses the read.
17893 let whole_sb = side == 64 && write_w == 64 && write_h == 64;
17894 maybe_read_delta_q(dec, cdfs, rmi, cmi, whole_sb, skip);
17895 maybe_read_delta_lf(dec, cdfs, rmi, cmi, whole_sb, skip);
17896 let (has_above, has_left) = (
17897 rmi > neighbours.tile_row0_mi,
17898 cmi > neighbours.tile_col0_mi,
17899 );
17900 let (above_inter, left_inter) = (neighbours.above_inter[cmi], neighbours.left_inter[rmi]);
17901 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
17902 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
17903 // lane-sb128c r1: this round wires the INTER half of a 128x128 block (four
17904 // TX_64X64 luma units and four TX_32X32 chroma units interleaved per mu
17905 // chunk). An INTRA block at that size inside an inter frame takes the
17906 // intra tail below, which still codes one whole-block chroma unit and one
17907 // `read_tx_size` at 128 -- refuse by name instead of mis-decoding it.
17908 if std::env::var_os("EC_TRACE_MODE").is_some() {
17909 eprintln!(
17910 "EC_MODE mi_row={} mi_col={} rng={} is_inter={} skip={} side={side}",
17911 rmi,
17912 cmi,
17913 dec.debug_state().0,
17914 u8::from(is_inter),
17915 u8::from(skip)
17916 );
17917 }
17918 // lane-warp r5: see `reject_residual` -- a square-block decode of a
17919 // HORZ_B strip is symbol-exact only for `skip` (no residual, no
17920 // motion_mode/warp symbol). lane-intrarect r1 MOVED this gate from just
17921 // after the `skip` read to here, past `is_inter` (class
17922 // [[refusal-short-circuits-its-own-code]]: at the old place it refused
17923 // 24/24 attempts of this lane's own gate before the intra arm below
17924 // could run). An INTRA strip with its true `write_w`x`write_h` footprint
17925 // now codes its residual rectangularly ([`decode_intra_rect_in_inter`]);
17926 // an INTER one, and a strip decoded with square dimensions anyway, still
17927 // cannot.
17928 // merge b51719f+lane-intrarect: main's `rect_inter_residual_supported`
17929 // term stays -- lane-inter4's 16x8/8x16 inter leaves DO code a
17930 // rectangular residual, and the lane's condition (written before that
17931 // landed) refused every one of them.
17932 if reject_residual
17933 && !skip
17934 && !rect_inter_residual_supported(write_w, write_h)
17935 && (is_inter || (write_w == side && write_h == side))
17936 {
17937 return Err(unsupported(
17938 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
17939 ));
17940 }
17941 if std::env::var_os("EC_AV1_TELL").is_some() {
17942 eprintln!(
17943 "TELL mi_row={} mi_col={} label=post_is_inter skip_mode={skip_mode} skip={skip} is_inter={is_inter} tell={} range={}",
17944 rmi, cmi, dec.debug_bitpos(), dec.debug_state().0
17945 );
17946 }
17947
17948 let mode_for_tx;
17949 let uv_predict_mode;
17950 let (luma_grid, u_grid, v_grid);
17951 let block_filter;
17952 let ref_frame_for_lf;
17953 let globalmv_for_lf;
17954 // lane-av1comp: `Some((comp_group_idx, compound_idx))` only for a real
17955 // `COMPOUND_REFERENCE` block -- applied to `neighbours` *after* the
17956 // common `record_inter` call below (which would otherwise stamp the
17957 // single-ref ALTREF-special-case default over it).
17958 let mut compound_ctx: Option<(i8, u8, u8)> = None;
17959 // lane-txselect: `read_block_tx_size`'s leaf transform units (spec
17960 // 5.11.17), `Some` only when this block's var-tx tree resolved to more
17961 // than one luma transform -- read back by the residual loop, the
17962 // coefficient-context write-back and the loop-filter grid fill below.
17963 let mut vartx_leaves: Option<Vec<(usize, usize, usize, usize)>> = None;
17964 let at_mi = at;
17965 if is_inter {
17966 let above_nbr = has_above.then(|| NeighbourRef {
17967 is_inter: above_inter,
17968 ref0: if above_inter {
17969 neighbours.above_ref[cmi]
17970 } else {
17971 0
17972 },
17973 ref1: neighbours.above_ref1[cmi],
17974 uni: neighbours.above_ref1[cmi]
17975 .is_some_and(|r1| is_uni_comp_ref(neighbours.above_ref[cmi], r1)),
17976 });
17977 let left_nbr = has_left.then(|| NeighbourRef {
17978 is_inter: left_inter,
17979 ref0: if left_inter {
17980 neighbours.left_ref[rmi]
17981 } else {
17982 0
17983 },
17984 ref1: neighbours.left_ref1[rmi],
17985 uni: neighbours.left_ref1[rmi]
17986 .is_some_and(|r1| is_uni_comp_ref(neighbours.left_ref[rmi], r1)),
17987 });
17988 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
17989 eprintln!(
17990 "EC_PRECOMP r={r} c={c} skip_mode={skip_mode} skip={skip} reference_select={reference_select} tell={}",
17991 dec.debug_bitpos()
17992 );
17993 }
17994 let is_compound =
17995 skip_mode
17996 || (reference_select
17997 // `is_comp_ref_allowed` (blockd.h:65) gates the
17998 // `comp_mode` read exactly as it gates `skip_mode`.
17999 && comp_allowed
18000 && read_comp_mode(dec, cdfs, above_nbr, left_nbr));
18001 if is_compound {
18002 let (ref0, ref1) = if skip_mode {
18003 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
18004 } else {
18005 read_compound_ref_frames(
18006 dec,
18007 cdfs,
18008 above_nbr,
18009 left_nbr,
18010 neighbours.above_ref[cmi],
18011 neighbours.left_ref[rmi],
18012 )
18013 };
18014 let (mi_row, mi_col) = (rmi, cmi);
18015 // lane-rect r2: true footprint, mirroring the single-ref path below.
18016 let bw4 = write_w / 4;
18017 let bh4 = write_h / 4;
18018 // spec 7.10.2.8, doubled per side (`CompoundTplArgs`): same
18019 // `use_ref_frame_mvs` gating as the single-ref `tpl` build
18020 // below, just one `get_relative_dist` per reference.
18021 let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs {
18022 field: t.field,
18023 cur_offset_0: crate::motion_field::get_relative_dist(
18024 t.order_hint_bits,
18025 t.order_hint,
18026 t.ref_order_hints[(ref0 - LAST_FRAME) as usize],
18027 ),
18028 cur_offset_1: crate::motion_field::get_relative_dist(
18029 t.order_hint_bits,
18030 t.order_hint,
18031 t.ref_order_hints[(ref1 - LAST_FRAME) as usize],
18032 ),
18033 allow_high_precision_mv,
18034 });
18035 let gm_table = build_gm_mv_table(
18036 global_motion,
18037 mi_row,
18038 mi_col,
18039 bw4,
18040 bh4,
18041 allow_high_precision_mv,
18042 force_integer_mv,
18043 );
18044 let comp_stack = crate::mvstack::find_mv_stack_compound(
18045 grid,
18046 mi_row,
18047 mi_col,
18048 bw4,
18049 bh4,
18050 (ref0, ref1),
18051 mi_cols as usize,
18052 mi_rows as usize,
18053 sign_bias_table,
18054 &gm_table,
18055 comp_tpl,
18056 );
18057 let compound_mode = if skip_mode {
18058 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
18059 } else {
18060 read_inter_compound_mode(dec, cdfs, comp_stack.new_mv_ctx, comp_stack.ref_mv_ctx)
18061 };
18062 let (mv0, mv1) = assign_compound_mv(
18063 dec,
18064 cdfs,
18065 &comp_stack,
18066 compound_mode,
18067 allow_high_precision_mv,
18068 force_integer_mv,
18069 (gm_table[(ref0 - LAST_FRAME) as usize], gm_table[(ref1 - LAST_FRAME) as usize]),
18070 );
18071 if std::env::var_os("EC_TRACE_MODE").is_some() {
18072 eprintln!(
18073 "EC_MODE_VAL mi_row={mi_row} mi_col={mi_col} mode={} ref0={ref0} ref1={ref1} mv0=({},{}) stack={} rng={}",
18074 compound_mode + 17,
18075 mv0.0,
18076 mv0.1,
18077 comp_stack.entries.len(),
18078 dec.debug_state().0
18079 );
18080 for (i, e) in comp_stack.entries.iter().enumerate() {
18081 eprintln!(
18082 "EC_STACK mi_row={mi_row} mi_col={mi_col} i={i} this=({},{}) comp=({},{}) w={}",
18083 e.mv0.0, e.mv0.1, e.mv1.0, e.mv1.1, e.weight
18084 );
18085 }
18086 }
18087 let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV
18088 // spec `is_nontrans_global_motion`: ALL active refs' models must
18089 // be non-TRANSLATION (IDENTITY counts) for the compound block's
18090 // interp-filter read to be suppressed.
18091 let gm_nontrans = is_globalmv
18092 && global_motion[(ref0 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation
18093 && global_motion[(ref1 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation;
18094 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
18095 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
18096 // lane-cwarp r1: `is_global_mv_block` (blockd.h:421-429) is
18097 // PER REFERENCE SLOT -- mode GLOBAL_GLOBALMV, block >= 8x8, and
18098 // THAT slot's own gm model > TRANSLATION. `bw4`/`bh4` come from
18099 // the write extent below, so recompute the size bound from
18100 // `side` here (the block's own size, what libaom's `bsize`
18101 // is).
18102 let is_global_mv0 = is_globalmv
18103 && side >= 8
18104 && global_motion[(ref0 - LAST_FRAME) as usize].model as u8 > 1;
18105 let is_global_mv1 = is_globalmv
18106 && side >= 8
18107 && global_motion[(ref1 - LAST_FRAME) as usize].model as u8 > 1;
18108 // libaom `av1_init_warp_params` + `allow_warp`'s
18109 // `global_warp_allowed` branch, run once per reference for a
18110 // compound block exactly as for a single-ref one (reconinter.c
18111 // `build_inter_predictors_8x8_and_bigger` loops over `ref` and
18112 // calls `av1_init_warp_params` inside the loop) -- WARPED_CAUSAL
18113 // never reaches here (spec 5.11.27 / libaom `read_motion_mode`:
18114 // `has_second_ref` returns SIMPLE_TRANSLATION), so the local-warp
18115 // arm of `allow_warp` is dead on this path and only the global
18116 // one applies. `force_integer_mv` short-circuits
18117 // `av1_init_warp_params` before `allow_warp`.
18118 let compound_warp = |ref_frame: i8, eligible: bool| {
18119 if eligible
18120 && !force_integer_mv
18121 && !global_motion[(ref_frame - LAST_FRAME) as usize].invalid
18122 {
18123 crate::warp::global_warp_params(
18124 global_motion[(ref_frame - LAST_FRAME) as usize].params,
18125 )
18126 } else {
18127 None
18128 }
18129 };
18130 let warp0 = compound_warp(ref0, is_global_mv0);
18131 let warp1 = compound_warp(ref1, is_global_mv1);
18132 if warp0.is_some() || warp1.is_some() {
18133 COMPOUND_WARP_HITS.with(|c| c.set(c.get() + 1));
18134 }
18135 // spec `get_ref_filter_type`: matches when EITHER of the
18136 // neighbour's two references equals this block's own ref0 --
18137 // `above_ref1`/`left_ref1` is the neighbour's real second
18138 // reference (`record_compound_ctx`) when it was itself a
18139 // compound block; checking `above_ref`/`left_ref` alone drops a
18140 // real filter match down to the "no neighbour" sentinel
18141 // whenever the shared reference sits in the neighbour's SECOND
18142 // slot (lane-av1idx r2).
18143 let above_filter_ctx = if neighbours.above_ref[cmi] == ref0
18144 || neighbours.above_ref1[cmi] == Some(ref0)
18145 {
18146 neighbours.above_filter[cmi]
18147 } else {
18148 [3, 3]
18149 };
18150 let left_filter_ctx = if neighbours.left_ref[rmi] == ref0
18151 || neighbours.left_ref1[rmi] == Some(ref0)
18152 {
18153 neighbours.left_filter[rmi]
18154 } else {
18155 [3, 3]
18156 };
18157 globalmv_for_lf = is_globalmv;
18158 ref_frame_for_lf = ref0;
18159 mode_for_tx = 0;
18160 uv_predict_mode = DC_PRED;
18161 // lane-rect r2: `grid` (mvstack.rs's own MiGrid, distinct from
18162 // `neighbours`) must be stamped with the block's true footprint
18163 // too -- a square `bw4`x`bw4` stamp here claims a rect strip's
18164 // NEXT strip's own rows/cols before it decodes, corrupting
18165 // every later mvstack scan that reads this cell back.
18166 for dr in 0..bh4 {
18167 for dc in 0..bw4 {
18168 grid.set(
18169 mi_row + dr,
18170 mi_col + dc,
18171 MiInfo {
18172 is_inter: true,
18173 ref_frame: ref0,
18174 ref_frame1: Some(ref1),
18175 mv1: Some(mv1),
18176 mv: mv0,
18177 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
18178 size: bw4,
18179 size_h: bh4,
18180 // libaom `is_global_mv_block`: per-ref-slot, mode
18181 // GLOBAL_GLOBALMV, block >= 8x8, and THAT slot's
18182 // own gm model > TRANSLATION (IDENTITY excluded
18183 // too -- the two-predicate trap, distinct from
18184 // `gm_nontrans` above which allows IDENTITY).
18185 is_global_mv0,
18186 is_global_mv1,
18187 },
18188 );
18189 }
18190 }
18191 // spec 5.11.25's `comp_group_idx`/`compound_idx`: only read when
18192 // masked compound / distance-weighted compound are actually
18193 // enabled for this stream -- `is_any_masked_compound_used_here`
18194 // is `true` for every block size this decoder ever reaches
18195 // (`min(side,side) >= 8`, `COMPOUND_DIFFWTD` always eligible
18196 // there), so the gate reduces to the sequence header bit; kept
18197 // as an explicit call so a future smaller block size is not
18198 // silently wrong (libaom `reconinter.h::is_any_masked_compound_used`).
18199 let group_ctx = get_comp_group_idx_context(neighbours, (rmi, cmi), side);
18200 let comp_group_idx = if !skip_mode
18201 && enable_masked_compound
18202 && is_any_masked_compound_used_here(write_w, write_h)
18203 {
18204 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
18205 } else {
18206 0
18207 };
18208 if std::env::var_os("EC_TRACE_MODE").is_some() {
18209 eprintln!(
18210 "EC_CGI mi_row={rmi} mi_col={cmi} ctx={group_ctx} val={comp_group_idx} rng={}",
18211 dec.debug_state().0
18212 );
18213 }
18214 // lane-maskcomp r2 / lane-wedge r3: `Some(mask_type)` for a
18215 // `COMPOUND_DIFFWTD` block, `Some(mask)` (wedge codebook lookup)
18216 // for a `COMPOUND_WEDGE` block -- exactly one of the two is set
18217 // when `comp_group_idx == 1`.
18218 let mut diffwtd_mask_type: Option<u8> = None;
18219 let mut wedge_mask: Option<&'static [u8]> = None;
18220 if comp_group_idx == 1 {
18221 // lane-maskcomp r1: `read_compound_type` (spec 5.11.25,
18222 // libaom `decodemv.c` 1634-1656). `is_interinter_compound_used
18223 // (COMPOUND_WEDGE, bsize)` (`av1_is_wedge_used`,
18224 // `av1_wedge_params_lookup`) is true for every square bsize
18225 // this leaf reaches (8x8/16x16/32x32 all have
18226 // `wedge_types > 0`), so `compound_type` always reads a real
18227 // symbol here -- no alphabet collapse to worry about at this
18228 // block-size family.
18229 // lane-mcomp64 r1: `av1_is_wedge_used` is false at 64x64
18230 // (`av1_wedge_params_lookup[BLOCK_64X64].wedge_types == 0`),
18231 // so libaom's `read_compound_type` (decodemv.c 1634-1656)
18232 // writes NO `compound_type` symbol there and INFERS
18233 // `COMPOUND_DIFFWTD` -- only the 1-bit `mask_type` literal
18234 // follows. `None` here is exactly that inferred arm.
18235 // lane-inter16ab r3: the row is this block's TRUE
18236 // `BLOCK_SIZES_ALL` index, not the enclosing square `side`'s
18237 // -- a 16x8 strip reads `compound_type_cdf[BLOCK_16X8]`.
18238 let wedge_bsize =
18239 bsize_all_index(write_w, write_h).filter(|_| wedge_used_bsize(write_w, write_h));
18240 let compound_type = match wedge_bsize {
18241 Some(b) => dec.symbol(&mut cdfs.compound_type[b]),
18242 None => 1,
18243 };
18244 if let Some(wedge_bsize) = wedge_bsize.filter(|_| compound_type == 0) {
18245 // COMPOUND_WEDGE: lane-wedge r3, codebook checksum-
18246 // verified vs independent C dump (wedge.rs).
18247 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
18248 let wedge_sign = dec.literal(1);
18249 WEDGE_HITS.with(|c| c.set(c.get() + 1));
18250 if let Some(k) = rect_wedge_slot(write_w, write_h) {
18251 RECT_WEDGE_HITS.with(|c| {
18252 let mut a = c.get();
18253 a[k] += 1;
18254 c.set(a);
18255 });
18256 }
18257 // lane-inter16ab r5: the codebook row is this block's TRUE
18258 // footprint (`av1_wedge_params_lookup[bsize]`: hgtw for
18259 // h>w, hltw for h<w, plus that bsize's own signflip row).
18260 // Masks are padded to stride `max(bw,bh) == side`, so the
18261 // square blend below indexes them unchanged and the
18262 // padding never reaches the frame (only `write_w x
18263 // write_h` is written out).
18264 wedge_mask = Some(
18265 crate::wedge::wedge_masks()
18266 .codebook(write_w, write_h)
18267 .mask(wedge_sign as usize, wedge_index as usize),
18268 );
18269 } else {
18270 // COMPOUND_DIFFWTD: `mask_type`, MAX_DIFFWTD_MASK_BITS==1.
18271 let mask_type = dec.literal(1);
18272 diffwtd_mask_type = Some(mask_type as u8);
18273 if wedge_bsize.is_none() {
18274 DIFFWTD_INFERRED_HITS.with(|c| c.set(c.get() + 1));
18275 }
18276 }
18277 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
18278 if write_w != write_h {
18279 RECT_MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
18280 }
18281 }
18282 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): r16/r17
18283 // called this a `predict_compound_intermediate`/`combine_compound`
18284 // reconstruction defect. r1 FALSIFIED that hypothesis outright:
18285 // unmasking and running the real gates
18286 // (a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly,
18287 // a_real_aomenc_stream_with_compound_references_decodes_pixel_exact)
18288 // shows the plain-average blend is bit-exact *most of the time*
18289 // -- `combine_compound`'s two-shift-in-one round2 was proven
18290 // algebraically identical to libaom's separate
18291 // `>>DIST_PRECISION_BITS`-then-`ROUND_POWER_OF_TWO` sequence
18292 // (av1_dist_wtd_convolve_2d_c, convolve.c:402-415) for every
18293 // input, and a whole-pel zero-MV compound block (mv0=mv1=(0,0),
18294 // the common case a lag-in-frames GOP's hidden altref frames
18295 // hit) reproduces aomdec's own pre-deblock dump byte-for-byte
18296 // for several consecutive frames.
18297 //
18298 // The real defect a live gate run isolated (seed 49,
18299 // `fixtures/av1blend-r1-mismatch.obu`): decode-order frame 0
18300 // (keyframe) and frame 1 (first hidden altref, `ref1 ==
18301 // ALTREF_FRAME`) match aomdec's own pre-deblock dump byte for
18302 // byte; decode-order frame 2 -- same shape, same zero MV, only
18303 // difference `ref1 == BWDREF_FRAME` instead of `ALTREF_FRAME` --
18304 // is the *first* frame to diverge (881/6144 luma+chroma bytes).
18305 // Every later frame up through decode-order 9 also mismatches,
18306 // *including* frame 8, whose four blocks are back to
18307 // `ref1 == ALTREF_FRAME` only -- ruling out "BWDREF_FRAME's MC
18308 // math is wrong" (that block's own math is proven exact) in
18309 // favour of "the picture sitting in some DPB slot is already
18310 // wrong by the time frame 2 reads it, and the corruption
18311 // propagates through refresh_frame_flags into every later
18312 // reference regardless of which named ref a later block picks".
18313 // Frames 10 through 18 (once the GOP's lineage stops tracing
18314 // back through the bad slot) are bit-exact again. This points at
18315 // reference-slot bookkeeping (`ref_slots`/`refresh_frame_flags`
18316 // in `stream.rs`'s `decode_stream`, or `ref_order_hints`/DPB
18317 // indexing feeding `dist_wtd_comp_weight_assign`) around
18318 // BWDREF_FRAME specifically, not at the MC/blend arithmetic in
18319 // mc.rs. Not isolated further within lane-av1blend's budget --
18320 // refuse by name rather than ship a blend that is right only
18321 // sometimes. Ceiling: r13/r14's MC plumbing above this line
18322 // stays -- only the plain-average reconstruct is masked off
18323 // again. Upgrade: instrument `ref_slots`/`refresh_frame_flags`
18324 // per decode-order frame (which slot each `Frame` OBU refreshes,
18325 // and which slot each `ref_frame_idx[BWDREF_FRAME - LAST_FRAME]`
18326 // reads) against aomdec's own `RefCntBuffer` bookkeeping on
18327 // `fixtures/av1blend-r1-mismatch.obu`, starting at decode-order
18328 // frame 2.
18329 //
18330 // r2 (fresh fixture, seed 45, same recipe -- the original r1
18331 // fixture is gitignored and could not be regenerated byte-exact):
18332 // static review of `stream.rs`'s `ref_slots`/`refresh_frame_flags`/
18333 // `cdf_slots` bookkeeping and the `show_existing_frame` refresh
18334 // arm (spec 7.21: only refreshes on a shown KEY frame, which the
18335 // parser already enforces at `frame.rs:791/815` -- `refresh_frame_flags`
18336 // is forced 0 on every non-key `show_existing_frame`) turned up
18337 // nothing wrong; `other_refs`/`ref_planes` slot indexing for
18338 // `BWDREF_FRAME` is spec-correct too. A live unmasked run
18339 // isolated a *different, smaller* shape than r1's: decode-order
18340 // frame 3 (a `ref1 == BWDREF_FRAME`, zero-MV, simple-average
18341 // compound block) is the first to diverge from ffmpeg (worst
18342 // delta 1, luma only, clustered at 32-pixel block edges) even
18343 // though BOTH its compound inputs -- the key frame and
18344 // decode-order frame 2's own picture (`ref1 == ALTREF_FRAME`,
18345 // itself proven bit-exact: it is later re-shown via
18346 // `show_existing_frame` and matches ffmpeg exactly) -- are
18347 // independently pixel-exact, and the blend arithmetic is the
18348 // same proven-exact formula. That rules out "wrong slot"/"stale
18349 // picture" for this fixture: the inputs are right, so the defect
18350 // is in decode-order frame 3's *own* per-block decode (entropy
18351 // desync from compound-CDF adaptation carried across a slot, or
18352 // the compound mode/MV read itself) -- not in `ref_slots`/
18353 // `refresh_frame_flags`. Not isolated further within budget.
18354 // Upgrade: bisect decode-order frame 3's tile decode against a
18355 // synced `EC_TOK`/`EC_PART` trace from the instrumented aomdec
18356 // build (`/tmp/libaom-src/build/decoder-debug/aomdec`) on
18357 // `fixtures/av1blend-r1-mismatch.obu` (seed 45 now, not seed 49)
18358 // -- the pre-deblock dump frame-index alignment between this
18359 // crate and that aomdec build is NOT 1:1 on this fixture (23
18360 // dumps here vs 24 there), so calibrate that first.
18361 // r3 (this round): pre-deblock buffers were bisected byte-for-byte
18362 // against an instrumented aomdec build (frame-index alignment
18363 // recalibrated via content-hash matching rather than the raw
18364 // dump count -- the keyframe never calls a pre-deblock dump at
18365 // all, since only `decode_inter_frame_tile` does, which is the
18366 // whole "23 vs 24" gap, not a real bug).
18367 // Decode-order frame 3 (`fixtures/av1blend-r1-mismatch.obu`,
18368 // seed 45) is still the first divergence: PRE-deblock differs
18369 // from aomdec's own pre-deblock dump by up to 1, on ~20% of
18370 // luma pixels, clustered where its two compound inputs' pixel
18371 // values disagree by more than a couple of levels -- both
18372 // inputs (the keyframe and decode-order frame 2's own picture)
18373 // are independently proven bit-exact (pre- and post-deblock)
18374 // against aomdec, and `decodemv`'s own EC_TRACE (mode/mv/skip)
18375 // matches this decoder's block loop exactly for every block in
18376 // this frame. Solving `aomval = (key*w0 + bwd*w1 + 8) >> 4` for
18377 // every mismatching pixel against `key`/`bwd` (both known-exact)
18378 // picks out `w0=9, w1=7` for the majority (525/846) with zero
18379 // matches for the plain average this decoder actually emits or
18380 // the reversed `w0=7, w1=9` -- i.e. `compound_idx` is being
18381 // decoded as `1` (simple average, spec `COMPOUND_AVERAGE`) when
18382 // the real bitstream encoded `0` (`COMPOUND_DISTWTD`,
18383 // `dist_wtd_comp_weight_assign`'s own weights for this frame's
18384 // order-hint distances 2/3 land on exactly `(9, 7)` -- this
18385 // decoder's own `dist_wtd_comp_weight_assign` was independently
18386 // re-verified against `QUANT_DIST_WEIGHT`/`QUANT_DIST_LOOKUP_TABLE`
18387 // by hand for these distances and gives the same `(9, 7)`).
18388 // `get_comp_index_context` was checked line-for-line against
18389 // libaom's `pred_common.h` (the `fwd`/`bck` distance halves, the
18390 // `above_mi`/`left_mi` `has_second_ref`/`ALTREF_FRAME` fallback,
18391 // the `3 * offset` term) and matches; `Default_Compound_Idx_Cdf`
18392 // (`cdf.rs`'s `COMPOUND_IDX`) matches `entropymode.c`'s
18393 // `default_compound_idx_cdfs` value-for-value; the read is
18394 // gated on `!skip_mode && enable_jnt_comp`, matching libaom's
18395 // `has_second_ref(mbmi) && !mbmi->skip_mode` outer guard plus
18396 // `order_hint_info.enable_dist_wtd_comp` inner guard. The
18397 // remaining 321/846 mismatched pixels do NOT fit `(9, 7)`
18398 // either -- some blocks in this frame plausibly decode a
18399 // genuinely different (correct, context-dependent) compound_idx
18400 // than block (0,0)'s own -- so this is not simply "always wrong
18401 // the same way": table/context/gate are all individually
18402 // verified correct, yet the decoded VALUE at this specific
18403 // symbol is wrong at least once in this frame. Not isolated
18404 // further within budget. Upgrade: instrument `dec.symbol`'s own
18405 // range/bit state (`rng`/`tell`, matching aomdec's own EC_PART
18406 // trace fields) immediately before and after the `compound_idx`
18407 // read specifically, not just the surrounding mode/mv/skip
18408 // trace which does match -- the desync (if any) is local to
18409 // this one read, not a wider stream desync.
18410 //
18411 // r5 (this round): the `resolve_interp_filter` call used to sit
18412 // right here, ahead of `comp_group_idx`/`compound_idx` -- spec
18413 // 5.11.19/libaom `decodemv.c:1575` reads `interp_filter` AFTER
18414 // `read_compound_type`, not before, so that was a genuine
18415 // ordering bug for a Switchable-filter frame (moved below, past
18416 // the `compound_ctx = Some(...)` line). It does NOT explain this
18417 // fixture's own mismatch, though: `av1blend-r1-mismatch.obu`'s
18418 // header carries a *fixed* interpolation filter
18419 // (`interp_fixed = Some(Regular)`, confirmed live via a
18420 // one-off dump), so `resolve_interp_filter` never read a symbol
18421 // in either position -- zero bits moved, decoded values
18422 // unchanged before and after the reorder. Kept anyway: it is a
18423 // real spec-order fix for the next Switchable-filter compound
18424 // stream, independently correct regardless of this fixture.
18425 //
18426 // Also ruled out this round: comparing this crate's own
18427 // `SymbolDecoder::debug_bitpos()` against aomdec's
18428 // `aom_reader_tell()` at the block boundary is NOT a valid
18429 // desync probe -- they are different quantities (raw consumed
18430 // input bits vs. an entropy-cost estimate that advances without
18431 // a literal byte fetch), so equal/unequal bitpos proves nothing
18432 // either way. Do not repeat that comparison; instead trace
18433 // `range`/`value` (this crate) against libaom's own internal
18434 // `dif`/`rng` (needs new instrumentation in both) immediately
18435 // after each read *upstream* of this one in the same block:
18436 // `read_comp_mode`, `read_compound_ref_frames` (comp_ref_type/
18437 // uni_comp_ref/comp_ref/comp_bwdref), `read_inter_compound_mode`,
18438 // and the DRL loop. All of those independently decoded the SAME
18439 // values this crate and aomdec both show (ref0=1, ref1=5, mode
18440 // NEAREST_NEARESTMV, mv=(0,0)) -- but an upstream *context*
18441 // miscomputation can still decode the identical symbol value off
18442 // a slightly different CDF, narrowing `range` by a different
18443 // amount than aomdec without changing the decoded value itself,
18444 // and only surface as a wrong decode a few reads later exactly
18445 // like this. `get_comp_index_context` and the `COMPOUND_IDX`
18446 // table were independently re-verified again this round and are
18447 // still correct; the four candidates above were not re-audited
18448 // this round. Refusing here (rather than shipping a value-exact-
18449 // most-of-the-time blend) until one of them is found wrong.
18450 // r6/r7: found and fixed one real bug (mvstack.rs ref_ctx family
18451 // undercounted compound neighbours in the single_ref_p*/comp_ref*/
18452 // comp_bwdref* context reads -- kept, real fix). Unmasking on
18453 // that fix alone and running the wide gate sweep (many seeds,
18454 // `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`/
18455 // `a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly`,
18456 // cq-level=45) still mismatches roughly half the time, at
18457 // different frames each run for the SAME seed -- aomenc's own
18458 // cpu-used=0 RD search is run-to-run nondeterministic (noted
18459 // above), so this is a second, still-unfound compound_idx defect,
18460 // not the one r6/r7 fixed. r6's own residual-mismatch note (321/
18461 // 846 pixels not fitting the (9,7)-vs-plain-average hypothesis
18462 // either) already flagged more than one bug here. Re-masking:
18463 // do not ship a blend that is right only sometimes.
18464 // lane-av1idx r1: fixed one real bug this round
18465 // (`switchable_interp_ctx` never folded in libaom's
18466 // `INTER_FILTER_COMP_OFFSET` for a compound block's own
18467 // interp_filter context -- kept). Pinned
18468 // `fixtures/av1idx-refsel-pin.obu` (seed 61, reference_select
18469 // gate) still mismatches after that fix (decode-order frame 8
18470 // first, small deltas, worst 1-2, propagating through later
18471 // frames via DPB reference) -- a second, still-unfound bug.
18472 // Re-masking: see that fixture + `scratch_isolate_pinned_mismatch`
18473 // (`EC_AV1_PIN=fixtures/av1idx-refsel-pin.obu EC_AV1_PIN_N=20`)
18474 // for the next round's starting point.
18475 // lane-maskcomp r2: `compound_idx` is only read when
18476 // `comp_group_idx == 0` (libaom `decodemv.c:1606`) -- a masked
18477 // (wedge/diffwtd) block never also carries a distance-weighted
18478 // split. This gate was missing before r2 (dead code: the masked
18479 // path always refused earlier, so it never executed with
18480 // `comp_group_idx == 1` in practice).
18481 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
18482 && !skip_mode
18483 && enable_jnt_comp
18484 {
18485 let idx_ctx = get_comp_index_context(
18486 neighbours,
18487 (rmi, cmi),
18488 side,
18489 order_hint_bits,
18490 order_hint,
18491 ref_order_hints[(ref0 - LAST_FRAME) as usize],
18492 ref_order_hints[(ref1 - LAST_FRAME) as usize],
18493 );
18494 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
18495 if std::env::var_os("EC_TRACE_MODE").is_some() {
18496 eprintln!(
18497 "EC_CIDX mi_row={rmi} mi_col={cmi} ctx={idx_ctx} val={idx} rng={}",
18498 dec.debug_state().0
18499 );
18500 }
18501 if idx == 1 {
18502 (8, 8, 1u8)
18503 } else {
18504 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
18505 order_hint_bits,
18506 order_hint,
18507 ref_order_hints[(ref0 - LAST_FRAME) as usize],
18508 ref_order_hints[(ref1 - LAST_FRAME) as usize],
18509 );
18510 (fwd, bck, 0u8)
18511 }
18512 } else {
18513 (8, 8, 1u8)
18514 };
18515 compound_ctx = Some((ref1, comp_group_idx as u8, compound_idx));
18516 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
18517 eprintln!(
18518 "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={}",
18519 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
18520 );
18521 }
18522
18523 // spec 5.11.19/libaom `decodemv.c` 1575: `read_mb_interp_filter`
18524 // comes AFTER `read_compound_type` (the `comp_group_idx`/
18525 // `compound_idx` reads just above), not before -- moved here
18526 // (lane-av1blend r5) from its old position ahead of those reads,
18527 // which stole their bits for a Switchable-filter compound block
18528 // and desynced every symbol read after it in the tile.
18529 // `av1_is_interp_needed` is also 0 for `skip_mode` blocks: the
18530 // filter is derived (Regular), never read -- same
18531 // conditional-read contract as the WARPED_CAUSAL suppression on
18532 // the single-ref path below.
18533 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
18534 dec,
18535 cdfs,
18536 interp_fixed,
18537 enable_dual_filter,
18538 gm_nontrans || skip_mode,
18539 above_filter_ctx,
18540 left_filter_ctx,
18541 true,
18542 );
18543 block_filter = resolved_filter;
18544
18545 // lane-scaledref r1: each compound tap scales INDEPENDENTLY off
18546 // its own stored reference's luma width (spec 7.11.3.3 derives
18547 // x_scale_fp per reference; libaom `av1_setup_pre_planes` builds
18548 // one `scale_factors` per `ref_frame`), so the two taps can carry
18549 // different ratios in the same block. `REF_NO_SCALE` reduces
18550 // `predict_compound_intermediate`'s walk to the ordinary
18551 // stride-1 one, so the unscaled case is unchanged.
18552 let scale0 = mc::scale_factor(py0.width, frame_width);
18553 let scale1 = mc::scale_factor(py1.width, frame_width);
18554 if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE {
18555 SCALED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
18556 }
18557 // lane-scaledref r2: the MIXED case -- one tap scaled, the other
18558 // not -- is the one an all-frames-scaled recipe never produces,
18559 // and the one a single shared scale factor would get wrong.
18560 if (scale0 == mc::REF_NO_SCALE) != (scale1 == mc::REF_NO_SCALE) {
18561 MIXED_SCALE_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
18562 }
18563
18564 let mut inter0_y = vec![0i32; side * side];
18565 mc::predict_compound_intermediate_kern(
18566 &py0.data,
18567 py0.width,
18568 py0.true_width,
18569 py0.true_height,
18570 mv_to_q4(px, mv0.1, true),
18571 mv_to_q4(py, mv0.0, true),
18572 scale0,
18573 side,
18574 side,
18575 write_w,
18576 write_h,
18577 h_filter,
18578 v_filter,
18579 &mut inter0_y,
18580 );
18581 // lane-cwarp r1: this reference's own GLOBAL warp replaces the
18582 // translational tap (libaom `av1_warp_plane` with
18583 // `conv_params->is_compound`); the blend below is unchanged.
18584 if let Some(wp) = &warp0 {
18585 crate::warp::warp_affine_compound(
18586 wp, &py0.data, py0.true_width as i32, py0.true_height as i32,
18587 py0.width as i32, &mut inter0_y, px as i32, py as i32, side as i32,
18588 side as i32, side as i32, 0, 0,
18589 );
18590 }
18591 let mut inter1_y = vec![0i32; side * side];
18592 mc::predict_compound_intermediate_kern(
18593 &py1.data,
18594 py1.width,
18595 py1.true_width,
18596 py1.true_height,
18597 mv_to_q4(px, mv1.1, true),
18598 mv_to_q4(py, mv1.0, true),
18599 scale1,
18600 side,
18601 side,
18602 write_w,
18603 write_h,
18604 h_filter,
18605 v_filter,
18606 &mut inter1_y,
18607 );
18608 // lane-cwarp r1: this reference's own GLOBAL warp replaces the
18609 // translational tap (libaom `av1_warp_plane` with
18610 // `conv_params->is_compound`); the blend below is unchanged.
18611 if let Some(wp) = &warp1 {
18612 crate::warp::warp_affine_compound(
18613 wp, &py1.data, py1.true_width as i32, py1.true_height as i32,
18614 py1.width as i32, &mut inter1_y, px as i32, py as i32, side as i32,
18615 side as i32, side as i32, 0, 0,
18616 );
18617 }
18618 let mut pred_y = vec![0u16; side * side];
18619 let mut diffwtd_mask_y = Vec::new();
18620 // lane-wedge r3: `mask_y` is the DIFFWTD buffer just computed OR
18621 // the wedge codebook lookup (comp_group_idx==1's two mutually
18622 // exclusive branches) -- same [`mc::blend_masked_compound`] call
18623 // either way, only the mask source differs.
18624 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
18625 diffwtd_mask_y = vec![0u8; side * side];
18626 DIFFWTD_HITS.with(|c| c.set(c.get() + 1));
18627 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
18628 Some(diffwtd_mask_y.as_slice())
18629 } else {
18630 wedge_mask
18631 };
18632 if let Some(mask_y) = mask_y {
18633 mc::blend_masked_compound(
18634 &inter0_y, &inter1_y, mask_y, side, side, side, false, &mut pred_y,
18635 );
18636 } else {
18637 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
18638 }
18639
18640 let mut inter0_u = vec![0i32; chroma_side * chroma_side];
18641 mc::predict_compound_intermediate_kern(
18642 &pu0.data,
18643 pu0.width,
18644 pu0.true_width,
18645 pu0.true_height,
18646 mv_to_q4(cpx, mv0.1, false),
18647 mv_to_q4(cpy, mv0.0, false),
18648 scale0,
18649 chroma_side,
18650 chroma_side,
18651 write_chroma_w,
18652 write_chroma_h,
18653 h_filter,
18654 v_filter,
18655 &mut inter0_u,
18656 );
18657 // `av1_init_warp_params` bails when the PLANE's block is
18658 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
18659 // block of an 8x8 luma block stays translational.
18660 if let Some(wp) = &warp0 {
18661 if chroma_side >= 8 {
18662 crate::warp::warp_affine_compound(
18663 wp, &pu0.data, pu0.true_width as i32, pu0.true_height as i32,
18664 pu0.width as i32, &mut inter0_u, cpx as i32, cpy as i32,
18665 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
18666 );
18667 }
18668 }
18669 let mut inter1_u = vec![0i32; chroma_side * chroma_side];
18670 mc::predict_compound_intermediate_kern(
18671 &pu1.data,
18672 pu1.width,
18673 pu1.true_width,
18674 pu1.true_height,
18675 mv_to_q4(cpx, mv1.1, false),
18676 mv_to_q4(cpy, mv1.0, false),
18677 scale1,
18678 chroma_side,
18679 chroma_side,
18680 write_chroma_w,
18681 write_chroma_h,
18682 h_filter,
18683 v_filter,
18684 &mut inter1_u,
18685 );
18686 // `av1_init_warp_params` bails when the PLANE's block is
18687 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
18688 // block of an 8x8 luma block stays translational.
18689 if let Some(wp) = &warp1 {
18690 if chroma_side >= 8 {
18691 crate::warp::warp_affine_compound(
18692 wp, &pu1.data, pu1.true_width as i32, pu1.true_height as i32,
18693 pu1.width as i32, &mut inter1_u, cpx as i32, cpy as i32,
18694 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
18695 );
18696 }
18697 }
18698 let mut pred_u = vec![0u16; chroma_side * chroma_side];
18699 if let Some(mask_y) = mask_y {
18700 mc::blend_masked_compound(
18701 &inter0_u,
18702 &inter1_u,
18703 mask_y,
18704 side,
18705 chroma_side,
18706 chroma_side,
18707 true,
18708 &mut pred_u,
18709 );
18710 } else {
18711 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
18712 }
18713
18714 let mut inter0_v = vec![0i32; chroma_side * chroma_side];
18715 mc::predict_compound_intermediate_kern(
18716 &pv0.data,
18717 pv0.width,
18718 pv0.true_width,
18719 pv0.true_height,
18720 mv_to_q4(cpx, mv0.1, false),
18721 mv_to_q4(cpy, mv0.0, false),
18722 scale0,
18723 chroma_side,
18724 chroma_side,
18725 write_chroma_w,
18726 write_chroma_h,
18727 h_filter,
18728 v_filter,
18729 &mut inter0_v,
18730 );
18731 // `av1_init_warp_params` bails when the PLANE's block is
18732 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
18733 // block of an 8x8 luma block stays translational.
18734 if let Some(wp) = &warp0 {
18735 if chroma_side >= 8 {
18736 crate::warp::warp_affine_compound(
18737 wp, &pv0.data, pv0.true_width as i32, pv0.true_height as i32,
18738 pv0.width as i32, &mut inter0_v, cpx as i32, cpy as i32,
18739 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
18740 );
18741 }
18742 }
18743 let mut inter1_v = vec![0i32; chroma_side * chroma_side];
18744 mc::predict_compound_intermediate_kern(
18745 &pv1.data,
18746 pv1.width,
18747 pv1.true_width,
18748 pv1.true_height,
18749 mv_to_q4(cpx, mv1.1, false),
18750 mv_to_q4(cpy, mv1.0, false),
18751 scale1,
18752 chroma_side,
18753 chroma_side,
18754 write_chroma_w,
18755 write_chroma_h,
18756 h_filter,
18757 v_filter,
18758 &mut inter1_v,
18759 );
18760 // `av1_init_warp_params` bails when the PLANE's block is
18761 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
18762 // block of an 8x8 luma block stays translational.
18763 if let Some(wp) = &warp1 {
18764 if chroma_side >= 8 {
18765 crate::warp::warp_affine_compound(
18766 wp, &pv1.data, pv1.true_width as i32, pv1.true_height as i32,
18767 pv1.width as i32, &mut inter1_v, cpx as i32, cpy as i32,
18768 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
18769 );
18770 }
18771 }
18772 let mut pred_v = vec![0u16; chroma_side * chroma_side];
18773 if let Some(mask_y) = mask_y {
18774 mc::blend_masked_compound(
18775 &inter0_v,
18776 &inter1_v,
18777 mask_y,
18778 side,
18779 chroma_side,
18780 chroma_side,
18781 true,
18782 &mut pred_v,
18783 );
18784 } else {
18785 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
18786 }
18787
18788 // lane-inter4 r2: a rectangular strip's transform tree starts from
18789 // its own rect `max_txsize_rect_lookup` entry, not a square one.
18790 let rect_tu = (write_w, write_h) != (side, side);
18791 vartx_leaves = if rect_tu {
18792 read_block_tx_size_rect(
18793 dec,
18794 cdfs,
18795 neighbours,
18796 at_mi,
18797 (write_w, write_h),
18798 (mi_cols as usize, mi_rows as usize),
18799 skip,
18800 )?
18801 } else {
18802 read_block_tx_size(
18803 dec,
18804 cdfs,
18805 neighbours,
18806 at_mi,
18807 side,
18808 (mi_cols as usize, mi_rows as usize),
18809 true,
18810 skip,
18811 )?
18812 .1
18813 };
18814 if skip {
18815 y.reconstruct_mc_rect(
18816 px,
18817 py,
18818 side,
18819 write_w,
18820 write_h,
18821 &pred_y,
18822 &vec![0i32; side * side],
18823 );
18824 u.reconstruct_mc_rect(
18825 cpx,
18826 cpy,
18827 chroma_side,
18828 write_chroma_w,
18829 write_chroma_h,
18830 &pred_u,
18831 &vec![0i32; chroma_side * chroma_side],
18832 );
18833 v.reconstruct_mc_rect(
18834 cpx,
18835 cpy,
18836 chroma_side,
18837 write_chroma_w,
18838 write_chroma_h,
18839 &pred_v,
18840 &vec![0i32; chroma_side * chroma_side],
18841 );
18842 luma_grid = vec![0i32; side * side];
18843 u_grid = vec![0i32; chroma_side * chroma_side];
18844 v_grid = vec![0i32; chroma_side * chroma_side];
18845 } else {
18846 // lane-inter4 r2: a rect strip's coefficient context spans its
18847 // OWN width above and height left -- reading `side` cells both
18848 // ways indexes past the tile's last mi row for a bottom strip.
18849 let around = if rect_tu {
18850 neighbours.around_mi_rect(at_mi, write_w, write_h)
18851 } else {
18852 neighbours.around_mi(at, side)
18853 };
18854 let luma_tx_type;
18855 // lane-sb128c r1: a 128x128 inter block's four chroma units
18856 // are read INSIDE the luma leaf loop (one per 64x64 mu chunk);
18857 // these collect them for the block-level neighbour write-back.
18858 let mut u_units = vec![0i32; chroma_side * chroma_side];
18859 let mut v_units = vec![0i32; chroma_side * chroma_side];
18860 if let Some(leaves) = vartx_leaves.clone() {
18861 // spec 5.11.17's transform tree, leaf by leaf in the order
18862 // `read_var_tx_size` coded it: each unit reads its own
18863 // coefficients against the neighbour magnitudes the
18864 // earlier units already wrote, and reconstructs over its
18865 // own slice of the block's motion-compensated predictor.
18866 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
18867 let mut first_tx_type = TxType::DctDct;
18868 for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() {
18869 let tu_mi = (at_mi.0 + row, at_mi.1 + col);
18870 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
18871 let (tu_grid, tu_tx_type) = if tw == th {
18872 let tx_px = tw;
18873 let mut tu_pred = Vec::with_capacity(tx_px * tx_px);
18874 for rr in 0..tx_px {
18875 let start = (row * MI + rr) * side + col * MI;
18876 tu_pred.extend_from_slice(&pred_y[start..start + tx_px]);
18877 }
18878 let scan = default_scan(tx_px.min(32));
18879 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI);
18880 read_inter_plane(
18881 dec,
18882 cdfs,
18883 inter_txbset_for(tx_px, reduced),
18884 &scan,
18885 0,
18886 neighbours.around_mi(tu_mi, tx_px)[0],
18887 mode_for_tx,
18888 y,
18889 tu_px,
18890 tu_py,
18891 tx_px,
18892 base_q_idx,
18893 &tu_pred,
18894 None,
18895 Some(tu_skip_ctx),
18896 )?
18897 } else {
18898 // lane-r14 r3: a 1:4 strip's `sub_tx_size_map`
18899 // sub-transform is RECTANGULAR (TX_64X16 ->
18900 // TX_32X16, TX_16X64 -> TX_16X32), so this leaf is
18901 // read with the rect coefficient machinery, at its
18902 // own `txb_skip_ctx`/neighbour spans -- the unit is
18903 // smaller than its block, so `get_txb_ctx_general`'s
18904 // neighbour table applies, not the lone-TU 0.
18905 vartx_rect_leaf_hit(tw, th);
18906 let tu_skip_ctx =
18907 neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI);
18908 let start = row * MI * side + col * MI;
18909 read_inter_plane_rect(
18910 dec,
18911 cdfs,
18912 rect_inter_luma_set(tw, th)?,
18913 (tw, th),
18914 side,
18915 0,
18916 neighbours.around_mi_rect(tu_mi, tw, th)[0],
18917 mode_for_tx,
18918 y,
18919 tu_px,
18920 tu_py,
18921 &pred_y[start..],
18922 None,
18923 Some(tu_skip_ctx),
18924 )?
18925 };
18926 if idx == 0 {
18927 first_tx_type = tu_tx_type;
18928 }
18929 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
18930 // lane-sb128c r1: libaom's `decode_token_recon_block`
18931 // walks 64x64 "mu" chunks (`mu_blocks_wide/high =
18932 // mi_size_wide[BLOCK_64X64]`) and codes EVERY PLANE of
18933 // a chunk before the next one, so a 128x128 block
18934 // interleaves Y,U,V per quadrant -- the same order the
18935 // intra 128 path reads (lane-sb128b r3, measured
18936 // against aomdec's `EC_TRACE_COEFF`). Below 128 a block
18937 // is a single chunk and this never fires.
18938 if side > 64 {
18939 let chunk = (row / 16, col / 16);
18940 let done = idx + 1 == leaves.len()
18941 || (leaves[idx + 1].0 / 16, leaves[idx + 1].1 / 16) != chunk;
18942 if done {
18943 let (cr, cc) = chunk;
18944 // `av1_get_max_uv_txsize(BLOCK_128X128)` =
18945 // `av1_get_adjusted_tx_size(TX_64X64)` =
18946 // TX_32X32: one 32x32 chroma unit per chunk.
18947 let cu_tx = 32usize;
18948 let luma_span = cu_tx * 2;
18949 let cu_mi = (at_mi.0 + cr * 16, at_mi.1 + cc * 16);
18950 let cu_around = neighbours.around_mi(cu_mi, luma_span);
18951 let (cu_x, cu_y) = (cpx + cc * cu_tx, cpy + cr * cu_tx);
18952 let cu_scan = default_scan(cu_tx);
18953 for plane_idx in 1..3 {
18954 let (src, buf) = if plane_idx == 1 {
18955 (&pred_u, &mut *u)
18956 } else {
18957 (&pred_v, &mut *v)
18958 };
18959 let mut cu_pred = Vec::with_capacity(cu_tx * cu_tx);
18960 for rr in 0..cu_tx {
18961 let start =
18962 (cr * cu_tx + rr) * chroma_side + cc * cu_tx;
18963 cu_pred.extend_from_slice(&src[start..start + cu_tx]);
18964 }
18965 let cu_grid = read_inter_plane(
18966 dec,
18967 cdfs,
18968 chroma_set,
18969 &cu_scan,
18970 plane_idx,
18971 cu_around[plane_idx],
18972 mode_for_tx,
18973 buf,
18974 cu_x,
18975 cu_y,
18976 cu_tx,
18977 base_q_idx,
18978 &cu_pred,
18979 Some(first_tx_type),
18980 Some(3),
18981 )?
18982 .0;
18983 // Immediately, so the NEXT chunk's unit
18984 // reads this one's coefficient context.
18985 neighbours.record_mi_chroma(
18986 cu_mi, luma_span, luma_span, plane_idx, &cu_grid,
18987 );
18988 CHROMA_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
18989 let dst = if plane_idx == 1 {
18990 &mut u_units
18991 } else {
18992 &mut v_units
18993 };
18994 for rr in 0..cu_tx {
18995 let start =
18996 (cr * cu_tx + rr) * chroma_side + cc * cu_tx;
18997 dst[start..start + cu_tx]
18998 .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]);
18999 }
19000 }
19001 }
19002 }
19003 }
19004 // `av1_get_tx_type`'s chroma lookup scales the chroma
19005 // position back to luma, so an inter block's chroma
19006 // inherits the *first* (top-left) luma unit's coded type.
19007 luma_tx_type = first_tx_type;
19008 luma_grid = vec![0i32; side * side];
19009 } else if rect_tu {
19010 // The whole-block rectangular transform unit
19011 // (`txfm_partition` said 0 at depth 0).
19012 let (grid, tx_type) = read_inter_plane_rect(
19013 dec,
19014 cdfs,
19015 rect_inter_luma_set(write_w, write_h)?,
19016 (write_w, write_h),
19017 side,
19018 0,
19019 around[0],
19020 mode_for_tx,
19021 y,
19022 px,
19023 py,
19024 &pred_y,
19025 None,
19026 None,
19027 )?;
19028 luma_tx_type = tx_type;
19029 luma_grid = embed_rect_grid(&grid, write_w, write_h, side);
19030 } else {
19031 (luma_grid, luma_tx_type) = read_inter_plane(
19032 dec,
19033 cdfs,
19034 luma_set_inter,
19035 scan_luma,
19036 0,
19037 around[0],
19038 mode_for_tx,
19039 y,
19040 px,
19041 py,
19042 side,
19043 base_q_idx,
19044 &pred_y,
19045 None,
19046 None,
19047 )?;
19048 }
19049 if rect_tu {
19050 // `av1_get_max_uv_txsize(bsize)`: the chroma transform of a
19051 // 2:1 strip is the strip's own rect chroma size (16x8 /
19052 // 8x16), one unit for the whole block, and it codes no
19053 // `tx_type` symbol -- it inherits the luma unit's.
19054 let (uw, uh) = (write_chroma_w, write_chroma_h);
19055 u_grid = embed_rect_grid(
19056 &read_inter_plane_rect(
19057 dec,
19058 cdfs,
19059 rect_inter_chroma_set(write_chroma_w, write_chroma_h)?,
19060 (uw, uh),
19061 chroma_side,
19062 1,
19063 around[1],
19064 mode_for_tx,
19065 u,
19066 cpx,
19067 cpy,
19068 &pred_u,
19069 Some(luma_tx_type),
19070 None,
19071 )?
19072 .0,
19073 uw,
19074 uh,
19075 chroma_side,
19076 );
19077 v_grid = embed_rect_grid(
19078 &read_inter_plane_rect(
19079 dec,
19080 cdfs,
19081 rect_inter_chroma_set(write_chroma_w, write_chroma_h)?,
19082 (uw, uh),
19083 chroma_side,
19084 2,
19085 around[2],
19086 mode_for_tx,
19087 v,
19088 cpx,
19089 cpy,
19090 &pred_v,
19091 Some(luma_tx_type),
19092 None,
19093 )?
19094 .0,
19095 uw,
19096 uh,
19097 chroma_side,
19098 );
19099 } else if side > 64 {
19100 // Already read inside the mu-chunk loop above.
19101 u_grid = std::mem::take(&mut u_units);
19102 v_grid = std::mem::take(&mut v_units);
19103 } else {
19104 u_grid = read_inter_plane(
19105 dec,
19106 cdfs,
19107 chroma_set,
19108 scan_chroma,
19109 1,
19110 around[1],
19111 mode_for_tx,
19112 u,
19113 cpx,
19114 cpy,
19115 chroma_side,
19116 base_q_idx,
19117 &pred_u,
19118 Some(luma_tx_type),
19119 None,
19120 )?
19121 .0;
19122 v_grid = read_inter_plane(
19123 dec,
19124 cdfs,
19125 chroma_set,
19126 scan_chroma,
19127 2,
19128 around[2],
19129 mode_for_tx,
19130 v,
19131 cpx,
19132 cpy,
19133 chroma_side,
19134 base_q_idx,
19135 &pred_v,
19136 Some(luma_tx_type),
19137 None,
19138 )?
19139 .0;
19140 }
19141 }
19142 } else {
19143 let ref_frame =
19144 read_single_ref(
19145 dec,
19146 cdfs,
19147 neighbours.above_ref[cmi],
19148 neighbours.above_ref1[cmi],
19149 neighbours.left_ref[rmi],
19150 neighbours.left_ref1[rmi],
19151 );
19152 ref_frame_for_lf = ref_frame;
19153 if std::env::var_os("EC_AV1_TELL").is_some() {
19154 let (mi_row, mi_col) = (rmi, cmi);
19155 eprintln!(
19156 "TELL mi_row={mi_row} mi_col={mi_col} label=post_ref_frame ref={ref_frame} tell={} range={}",
19157 dec.debug_bitpos(), dec.debug_state().0
19158 );
19159 }
19160 // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own
19161 // stacked defects (lf_level ref/mode-delta forwarding, the
19162 // switchable_interp ref-frame ctx gate, and a film-grain synthesis
19163 // gap that looked like a GOLDEN MC bug by survivor bias -- see the
19164 // ledger) are all closed; GOLDEN_FRAME decodes live via `other_refs`
19165 // below same as every other non-`LAST_FRAME` reference. lane-av1refs
19166 // widens this from GOLDEN alone to every reference `read_single_ref`
19167 // can name.
19168 let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME {
19169 (ref_y, ref_u, ref_v)
19170 } else {
19171 match other_refs[ref_frame as usize] {
19172 Some((ry, ru, rv)) => (ry, ru, rv),
19173 None => {
19174 return Err(unsupported(
19175 "a reference frame selected with no picture at this frame's own \
19176 ref_frame_idx slot for it",
19177 ));
19178 }
19179 }
19180 };
19181
19182 let (mi_row, mi_col) = (rmi, cmi);
19183 // lane-rect r2: the mv stack must be queried with the block's
19184 // REAL extent (libaom `av1_get_mv_refs` gets bw4/bh4 from
19185 // xd->width/xd->height, not a square guess) -- `write_w`/
19186 // `write_h` already name the true HORZ/VERT/HORZ_B strip
19187 // footprint (r1's plumbing), so derive bw4/bh4 from those
19188 // instead of the old `side`-square (HORZ_B-only) heuristic.
19189 let bw4 = write_w / 4;
19190 let bh4 = write_h / 4;
19191 // spec 7.10.2.8: only reached when the frame header set
19192 // `use_ref_frame_mvs` (`tpl_frame` is `Some` then, `None`
19193 // otherwise) -- `cur_offset_0` is this query block's own resolved
19194 // `ref_frame`'s distance from the current frame (spec 7.9.3),
19195 // recomputed per block since different blocks pick different refs.
19196 let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
19197 field: t.field,
19198 cur_offset_0: crate::motion_field::get_relative_dist(
19199 t.order_hint_bits,
19200 t.order_hint,
19201 t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
19202 ),
19203 allow_high_precision_mv,
19204 });
19205 let gm_table = build_gm_mv_table(
19206 global_motion,
19207 mi_row,
19208 mi_col,
19209 bw4,
19210 bh4,
19211 allow_high_precision_mv,
19212 force_integer_mv,
19213 );
19214 let stack = find_mv_stack_with_sign_bias(
19215 grid,
19216 mi_row,
19217 mi_col,
19218 bw4,
19219 bh4,
19220 ref_frame,
19221 mi_cols as usize,
19222 mi_rows as usize,
19223 sign_bias_table,
19224 &gm_table,
19225 tpl,
19226 );
19227 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
19228 let mut is_globalmv = false;
19229 // lane-interbis r1: which single-ref mode this block resolved to,
19230 // in the oracle's own numbering (NEARESTMV=13 .. NEWMV=16), for
19231 // the `EC_MODE_VAL` value ladder below.
19232 let mut dbg_mode = 16u32;
19233 let (mv, is_new_mv) = if !not_new {
19234 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
19235 // read at most two `drl_mode` bits, one per stack entry past the
19236 // first, stopping at the first `0`. The chosen index selects
19237 // which stack entry `read_mv`'s base predictor comes from
19238 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
19239 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
19240 let mut idx = 0usize;
19241 while idx < 2 && stack.entries.len() > idx + 1 {
19242 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
19243 break;
19244 }
19245 idx += 1;
19246 }
19247 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
19248 (
19249 read_mv(
19250 dec,
19251 &mut cdfs.mv_comp,
19252 &mut cdfs.mv_joint,
19253 base_mv,
19254 allow_high_precision_mv,
19255 force_integer_mv,
19256 ),
19257 true,
19258 )
19259 } else {
19260 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
19261 is_globalmv = !not_zero;
19262 let mv = if !not_zero {
19263 // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already
19264 // computed at this block's own position in `gm_table`.
19265 dbg_mode = 15;
19266 gm_table[(ref_frame - LAST_FRAME) as usize]
19267 } else {
19268 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
19269 dbg_mode = if nearest { 13 } else { 14 };
19270 if nearest {
19271 stack.nearest_mv
19272 } else {
19273 // NEARMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting
19274 // at 1): read at most two more `drl_mode` bits, one per stack
19275 // entry past the second, stopping at the first `0`.
19276 // `drl_ctx[idx]` is the context between `entries[idx]` and
19277 // `entries[idx + 1]` (`MvStack::drl_ctx`'s own doc), which is
19278 // exactly the pair this index is choosing between.
19279 let mut idx = 1usize;
19280 while idx < 3 && stack.entries.len() > idx + 1 {
19281 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
19282 break;
19283 }
19284 idx += 1;
19285 }
19286 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
19287 }
19288 };
19289 (mv, false)
19290 };
19291 if std::env::var_os("EC_TRACE_MODE").is_some() {
19292 for (i, e) in stack.entries.iter().enumerate() {
19293 eprintln!(
19294 "EC_STACK mi_row={mi_row} mi_col={mi_col} ref={ref_frame} i={i} this=({},{}) comp=(0,0) w={}",
19295 e.mv.0, e.mv.1, e.weight
19296 );
19297 }
19298 eprintln!(
19299 "EC_MODE_VAL mi_row={mi_row} mi_col={mi_col} mode={dbg_mode} ref0={ref_frame} ref1=-1 mv0=({},{}) stack={} rng={}",
19300 mv.0,
19301 mv.1,
19302 stack.entries.len(),
19303 dec.debug_state().0
19304 );
19305 }
19306 // lane-gm r2: the two libaom predicates single-ref GLOBALMV
19307 // blocks need -- `is_global_mv_block` (blockd.h:421-429, mode
19308 // GLOBAL* AND model > TRANSLATION AND min(bw,bh) >= 8px, gating
19309 // `motion_mode_eligible`/`MiInfo::is_global_mv0` below) and
19310 // `is_nontrans_global_motion` (reconinter.h:420-425, model !=
19311 // TRANSLATION -- IDENTITY counts here -- gating the interp
19312 // filter suppress below). Do NOT unify these.
19313 let gm_model = global_motion[(ref_frame - LAST_FRAME) as usize].model;
19314 let min_bw_bh4 = bw4.min(bh4);
19315 let is_global_mv_block = is_globalmv && gm_model as u8 > 1 && min_bw_bh4 >= 2;
19316 let gm_nontrans =
19317 is_globalmv && gm_model != ec_av1_syntax::WarpModel::Translation && min_bw_bh4 >= 2;
19318 if std::env::var_os("EC_AV1_TELL").is_some() {
19319 eprintln!(
19320 "TELL mi_row={mi_row} mi_col={mi_col} label=post_assign_mv tell={} range={}",
19321 dec.debug_bitpos(), dec.debug_state().0
19322 );
19323 }
19324 // lane-sb128 r4: `interintra` (spec 5.11.24; libaom
19325 // `decodemv.c` read_inter_block_mode_info ~1490-1510), placed
19326 // right after `assign_mv` and before `read_motion_mode` below --
19327 // libaom's own sequential order. `is_interintra_allowed_bsize`
19328 // (`BLOCK_8X8..=BLOCK_32X32`) is the only real gate on this
19329 // single-ref path: `is_interintra_allowed_ref` always holds here
19330 // (single ref, `ref_frame[1]` not yet `INTRA_FRAME`) and
19331 // `is_interintra_allowed_mode` always holds (every mode this
19332 // branch produces -- NEARESTMV/NEARMV/GLOBALMV/NEWMV -- is
19333 // `SINGLE_INTER_MODE_START..END` by construction).
19334 // `size_group_lookup`: BLOCK_16X16 -> 2, BLOCK_32X32 -> 3.
19335 let mut interintra_mode: Option<u8> = None;
19336 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
19337 // lane-inter4 r1: `is_interintra_allowed_bsize` is
19338 // `BLOCK_8X8..=BLOCK_32X32` in libaom's enum ORDER, which excludes
19339 // every 1:4 shape (BLOCK_8X32 = 18, BLOCK_32X8 = 19) even though
19340 // both dimensions are in range -- reading this symbol on a 1:4
19341 // strip is a symbol the reference never wrote.
19342 let interintra_shape =
19343 write_w.max(write_h) <= 32 && write_w.max(write_h) / write_w.min(write_h) <= 2;
19344 if enable_interintra_compound
19345 && !skip_mode
19346 && (side == 16 || side == 32)
19347 && interintra_shape
19348 {
19349 // lane-inter4 r3: `size_group_lookup` reads the block's
19350 // TRUE footprint -- a 16x8 strip is group 1, a 32x16 strip
19351 // group 2, not their square `side`'s 2/3.
19352 let bsize_group = size_group_wh(write_w, write_h);
19353 let interintra = dec.symbol(&mut cdfs.interintra[bsize_group]) == 1;
19354 if interintra {
19355 // lane-interintra r1 (decodemv.c 1540-1555): interintra_mode,
19356 // then -- gated on block size ALONE, never the
19357 // `enable_interintra_wedge` seq bit -- the wedge flag
19358 // (`av1_is_wedge_used(bsize)` holds for 16x16/32x32).
19359 let ii = dec.symbol(&mut cdfs.interintra_mode[bsize_group]) as u8;
19360 // lane-inter16ab r3 (same class as the compound
19361 // `compound_type` row below): the row is the block's TRUE
19362 // `BLOCK_SIZES_ALL` index -- a 16x8 / 32x16 interintra
19363 // strip is BLOCK_16X8 / BLOCK_32X16, not its square
19364 // `side`'s BLOCK_16X16 / BLOCK_32X32.
19365 let wedge_bsize = bsize_all_index(write_w, write_h)
19366 .expect("interintra shape is a BLOCK_SIZES_ALL size");
19367 let wedge = dec.symbol(&mut cdfs.wedge_interintra[wedge_bsize]) == 1;
19368 if wedge {
19369 // lane-wii r2 (spec 5.11.25): `wedge_index` is an
19370 // ADAPTING CDF symbol over the same `wedge_bsize` row;
19371 // NO sign symbol follows -- libaom fixes
19372 // INTERINTRA_WEDGE_SIGN 0 (blockd.h).
19373 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
19374 WII_HITS.with(|c| c.set(c.get() + 1));
19375 if let Some(k) = rect_wedge_slot(write_w, write_h) {
19376 RECT_WII_HITS.with(|c| {
19377 let mut a = c.get();
19378 a[k] += 1;
19379 c.set(a);
19380 });
19381 }
19382 // lane-inter16ab r5: true-footprint codebook row,
19383 // mask padded to stride `max(bw,bh) == side` -- see
19384 // the compound site's own comment.
19385 wedge_mask = Some((
19386 crate::wedge::wedge_masks()
19387 .codebook(write_w, write_h)
19388 .mask(0, wedge_index as usize),
19389 side,
19390 ));
19391 } else {
19392 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
19393 }
19394 interintra_mode = Some(ii);
19395 }
19396 }
19397 if std::env::var_os("EC_AV1_TELL").is_some() {
19398 eprintln!(
19399 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interintra tell={} range={}",
19400 dec.debug_bitpos(), dec.debug_state().0
19401 );
19402 }
19403 // lane-motionmode round 1: `read_motion_mode` (spec 5.11.24;
19404 // libaom `decodemv.c` read_inter_block_mode_info, ~1520-1528),
19405 // placed right after MV assignment and before the switchable
19406 // interp filter read below (`read_mb_interp_filter`, decodemv.c
19407 // ~1600) -- libaom's own sequential order. `motion_mode_allowed`
19408 // (`reconinter.h`) reduces, for every block this single-ref path
19409 // reaches, to "does an inter neighbour border the above row or
19410 // left column": `is_motion_variation_allowed_bsize` always holds
19411 // (`side` is never below 16px on this path), `ref_frame[1] !=
19412 // INTRA_FRAME` always holds (no interintra reader here),
19413 // `is_motion_variation_allowed_compound` always holds (this is
19414 // the single-ref branch), and `is_global_mv_block` never
19415 // triggers (this decoder's global motion is always `IDENTITY`,
19416 // so its warp `type` is never `> TRANSLATION`). A stream with
19417 // `allow_warped_motion=1` is refused right at an eligible block
19418 // rather than guessed at: `av1_findSamples`/`num_proj_ref` is
19419 // not ported, so this decoder cannot tell a real
19420 // `WARPED_CAUSAL`-eligible block (3-symbol `motion_mode_cdf`)
19421 // from an `OBMC_CAUSAL`-only one (2-symbol `obmc_cdf`) whenever
19422 // the header allows warp -- reading the wrong alphabet desyncs
19423 // the tile.
19424 // An interintra block has `ref_frame[1] == INTRA_FRAME`, which
19425 // fails libaom's `is_motion_variation_allowed_compound`: the
19426 // motion_mode symbol is NOT read (SIMPLE_TRANSLATION implied).
19427 let motion_mode_eligible = switchable_motion_mode
19428 && !skip_mode
19429 // `is_motion_variation_allowed_bsize` (blockd.h:1455):
19430 // min(bw, bh) >= 8, false for a 16x4 / 4x16 strip.
19431 && write_w.min(write_h) >= 8
19432 && interintra_mode.is_none()
19433 && (!overlappable_above(grid, mi_row, mi_col, bw4, mi_cols as usize, 1).is_empty()
19434 || !overlappable_left(grid, mi_row, mi_col, bh4, mi_rows as usize, 1)
19435 .is_empty())
19436 // libaom `motion_mode_allowed`: a GLOBALMV block whose model
19437 // is non-IDENTITY-non-TRANSLATION under free (non-integer)
19438 // mv reads no motion_mode/obmc symbol at all -- implicit
19439 // SIMPLE_TRANSLATION.
19440 && !(is_global_mv_block && !force_integer_mv);
19441 let mut obmc_selected = false;
19442 // lane-warp round 2: `Some` when motion_mode == WARPED_CAUSAL
19443 // *and* the local warp estimate is valid (`!wm_params.invalid`,
19444 // `av1_find_projection`) -- an invalid estimate falls back to
19445 // this block's own translational mv, same as any other block
19446 // (spec `allow_warp`/`reconinter.c` -- global warp is never the
19447 // fallback here since this decoder's global motion is always
19448 // IDENTITY).
19449 let mut warp_params: Option<crate::warp::WarpParams> = None;
19450 // Tracks the SYMBOL value, not projection validity: libaom's
19451 // `av1_is_interp_needed` suppresses the interp-filter read for
19452 // `motion_mode == WARPED_CAUSAL` even when the projection later
19453 // falls back to translation. Its third suppressor,
19454 // `is_nontrans_global_motion`, matches our unconditional
19455 // `is_globalmv` only because this decoder codes global motion as
19456 // IDENTITY (non-TRANSLATION) and never reads switchable filters
19457 // below 8x8 -- porting TRANSLATION global motion must add the
19458 // wmtype check here.
19459 let mut warped_selected = false;
19460 if motion_mode_eligible {
19461 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 ->
19462 // 0/1/2/3; lane-rect r2: a rect strip reads its OWN bsize row
19463 // (libaom `motion_mode_cdf[mbmi->bsize]`: BLOCK_16X32 -> 4,
19464 // BLOCK_32X16 -> 5 in our packed table) -- rect-flake-1's
19465 // strip motion_mode read diverged on the square row.
19466 // lane-inter4 r1: every rect shape this decoder can now
19467 // reach reads its OWN libaom bsize row (the packed order is
19468 // documented on `cdf::MOTION_MODE`); a wrong row is a wrong
19469 // interval narrowing, not a wrong value (class
19470 // wrong-alphabet-same-value).
19471 let bsize_idx = match (write_w, write_h) {
19472 // lane-sb128c r5: the 128 root's own rows come FIRST --
19473 // the square arm below maps 128 to row 4 (BLOCK_16X32).
19474 (64, 128) => 14,
19475 (128, 64) => 15,
19476 (128, 128) => 16,
19477 (w, h) if w == h => (w.trailing_zeros() - 3) as usize,
19478 (16, 32) => 4,
19479 (32, 16) => 5,
19480 (32, 64) => 6,
19481 (64, 32) => 7,
19482 (8, 32) => 8,
19483 (32, 8) => 9,
19484 (16, 64) => 10,
19485 (64, 16) => 11,
19486 // lane-inter4 r3: the 16x16-level rect inter leaves.
19487 (8, 16) => 12,
19488 (16, 8) => 13,
19489 _ => {
19490 return Err(unsupported(
19491 "a motion_mode symbol for a block shape with no CDF row here",
19492 ));
19493 }
19494 };
19495 // `motion_mode_allowed` reads the 3-symbol `motion_mode_cdf`
19496 // instead of the 2-symbol `obmc_cdf` exactly when
19497 // `num_proj_ref >= 1` under `allow_warped_motion`.
19498 // lane-scaledref r2 + lane-fimv r1: libaom
19499 // `motion_mode_allowed` (`blockd.h:1484`) requires BOTH
19500 // `!av1_is_scaled(block_ref_scale_factors[0])` and
19501 // `!xd->cur_frame_force_integer_mv` for WARPED_CAUSAL --
19502 // under a scaled reference (superres) OR on a frame whose
19503 // header set `force_integer_mv` (screen content) the block
19504 // reads the 2-symbol `obmc_cdf`, never the 3-symbol
19505 // `motion_mode_cdf`. Reading the wrong alphabet here narrows
19506 // the arithmetic coder by the wrong amount and predicts the
19507 // rest of the tile off a diverged state: silently wrong
19508 // pixels, not a desync error. `force_integer_mv` is the
19509 // per-frame value (spec 5.9.2: coded per frame only when
19510 // `seq_force_integer_mv == SELECT_INTEGER_MV`, threaded from
19511 // `FrameHeader::force_integer_mv`).
19512 // libaom `av1_is_scaled` is `x_scale_fp != REF_NO_SCALE ||
19513 // y_scale_fp != REF_NO_SCALE`; the y half is unreachable here
19514 // because a reference whose height differs from this frame's
19515 // true size is refused before any tile decodes ("a reference
19516 // picture whose height does not match this frame's own true
19517 // size", ~14681). Whoever lifts that refusal adds the y term.
19518 let ref_is_scaled =
19519 mc::scale_factor(py_ref.width, frame_width) != mc::REF_NO_SCALE;
19520 let proj_ok = num_proj_ref(
19521 grid,
19522 mi_row,
19523 mi_col,
19524 bw4,
19525 bh4,
19526 mi_cols as usize,
19527 mi_rows as usize,
19528 ref_frame,
19529 ) >= 1;
19530 let warp_eligible =
19531 allow_warped_motion && !ref_is_scaled && !force_integer_mv && proj_ok;
19532 if allow_warped_motion && proj_ok && ref_is_scaled {
19533 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.set(c.get() + 1));
19534 }
19535 if allow_warped_motion && proj_ok && !ref_is_scaled && force_integer_mv {
19536 FIMV_ALPHABET_HITS.with(|c| c.set(c.get() + 1));
19537 }
19538 if warp_eligible {
19539 let mode = dec.symbol(&mut cdfs.motion_mode[bsize_idx]);
19540 match mode {
19541 0 => {}
19542 1 => {
19543 obmc_selected = true;
19544 OBMC_HITS.with(|c| c.set(c.get() + 1));
19545 }
19546 _ => {
19547 warped_selected = true;
19548 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
19549 let mut samples = find_samples(
19550 grid,
19551 mi_row,
19552 mi_col,
19553 bw4,
19554 bh4,
19555 mi_cols as usize,
19556 mi_rows as usize,
19557 ref_frame,
19558 );
19559 if std::env::var_os("EC_WARP_DEBUG").is_some() {
19560 eprintln!(
19561 "EC_WARP_DEBUG findSamples mi_row={mi_row} mi_col={mi_col} bsize={side} num_proj_ref={}",
19562 samples.len()
19563 );
19564 for (i, s) in samples.iter().enumerate() {
19565 eprintln!("EC_WARP_DEBUG sample[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
19566 }
19567 }
19568 if samples.len() > 1 {
19569 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
19570 }
19571 warp_params = crate::warp::find_projection(
19572 &samples,
19573 // lane-rect r2: the block's TRUE dims -- a
19574 // 32x16 strip's model center is not a
19575 // 32x32's (aom av1_find_projection bw/bh).
19576 write_w as i32,
19577 write_h as i32,
19578 mv.1,
19579 mv.0,
19580 mi_row as i32,
19581 mi_col as i32,
19582 );
19583 if std::env::var_os("EC_WARP_DEBUG").is_some() {
19584 eprintln!(
19585 "EC_WARP_DEBUG projection mi_row={mi_row} mi_col={mi_col} num_proj_ref(final)={} mv=({},{}) params={:?}",
19586 samples.len(), mv.0, mv.1, warp_params
19587 );
19588 for (i, s) in samples.iter().enumerate() {
19589 eprintln!("EC_WARP_DEBUG sample_used[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
19590 }
19591 }
19592 }
19593 }
19594 } else {
19595 obmc_selected = dec.symbol(&mut cdfs.obmc[bsize_idx]) == 1;
19596 if obmc_selected {
19597 OBMC_HITS.with(|c| c.set(c.get() + 1));
19598 }
19599 }
19600 }
19601 // lane-gm r4: `allow_warp`'s `global_warp_allowed` branch
19602 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --
19603 // libaom's `av1_init_warp_params` runs for every inter
19604 // predictor build, not just a `WARPED_CAUSAL`-selected one. Only
19605 // reachable when `warp_params` is still `None` here: a block
19606 // that read (and got) local `WARPED_CAUSAL` above already has
19607 // `local_warp_allowed && !wm_params.invalid`, which `allow_warp`
19608 // checks FIRST and short-circuits on -- the global branch is an
19609 // `else if`, never layered on top. `is_global_mv_block` already
19610 // encodes `allow_warp`'s size bound (`min(bw4,bh4) >= 2`, i.e.
19611 // >=8px both dims, matching `av1_init_warp_params`'s
19612 // `block_height < 8 || block_width < 8` early return) and, via
19613 // `motion_mode_eligible`'s own suppression above, the
19614 // `force_integer_mv` case never reads a motion_mode symbol at
19615 // all -- checked again here directly since this branch fires
19616 // independent of `motion_mode_eligible`.
19617 let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
19618 if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid {
19619 warp_params = crate::warp::global_warp_params(gm_ref.params);
19620 if warp_params.is_some() && gm_ref.model == ec_av1_syntax::WarpModel::Affine {
19621 AFFINE_GM_HITS.with(|c| c.set(c.get() + 1));
19622 }
19623 }
19624 if std::env::var_os("EC_AV1_TELL").is_some() {
19625 eprintln!(
19626 "TELL mi_row={mi_row} mi_col={mi_col} label=post_motion_mode eligible={} tell={} range={}",
19627 motion_mode_eligible as u8, dec.debug_bitpos(), dec.debug_state().0
19628 );
19629 }
19630 // spec `get_ref_filter_type`: a neighbour's own filter only feeds
19631 // this block's switchable_interp context when that neighbour coded
19632 // the SAME reference frame this block is about to read -- a
19633 // different-ref neighbour reads as "no neighbour" ([3, 3], the
19634 // sentinel `Neighbours::new` already seeds unset slots with),
19635 // exactly like an intra neighbour. Without this gate, a GOLDEN_FRAME
19636 // block next to a LAST_FRAME one inherits that neighbour's filter
19637 // choice into its own context, corrupting the symbol it reads.
19638 // lane-av1idx r2: also match on the neighbour's SECOND reference
19639 // (`above_ref1`/`left_ref1`, real for a compound neighbour) --
19640 // see the 16x16 leaf's own comment above for the spec citation.
19641 let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame
19642 || neighbours.above_ref1[cmi] == Some(ref_frame)
19643 {
19644 neighbours.above_filter[cmi]
19645 } else {
19646 [3, 3]
19647 };
19648 let left_filter_ctx = if neighbours.left_ref[rmi] == ref_frame
19649 || neighbours.left_ref1[rmi] == Some(ref_frame)
19650 {
19651 neighbours.left_filter[rmi]
19652 } else {
19653 [3, 3]
19654 };
19655 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
19656 dec,
19657 cdfs,
19658 interp_fixed,
19659 enable_dual_filter,
19660 gm_nontrans || warped_selected,
19661 above_filter_ctx,
19662 left_filter_ctx,
19663 false,
19664 );
19665 block_filter = resolved_filter;
19666 globalmv_for_lf = is_globalmv;
19667 if std::env::var_os("EC_AV1_TELL").is_some() {
19668 eprintln!(
19669 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interp_filter tell={} range={}",
19670 dec.debug_bitpos(), dec.debug_state().0
19671 );
19672 }
19673 if std::env::var_os("EC_AV1_TRACE").is_some() {
19674 eprintln!(
19675 "EC_TRACE mi_row={mi_row} mi_col={mi_col} skip={} is_inter=1 mv=({},{}) is_new_mv={is_new_mv} bsize={side} ref={ref_frame} filter={:?} motion_mode_eligible={} obmc_selected={} warped={} tell={}",
19676 skip as u8, mv.0, mv.1, block_filter, motion_mode_eligible as u8, obmc_selected as u8, warp_params.is_some() as u8, dec.debug_bitpos()
19677 );
19678 }
19679 // lane-rect r2: see the compound path's matching comment above --
19680 // `grid` must be stamped with the block's true bh4/bw4 span, not
19681 // a square `bw4`x`bw4` guess.
19682 for dr in 0..bh4 {
19683 for dc in 0..bw4 {
19684 grid.set(
19685 mi_row + dr,
19686 mi_col + dc,
19687 MiInfo {
19688 is_inter: true,
19689 ref_frame,
19690 // An interintra block records ref_frame[1] ==
19691 // INTRA_FRAME (0): warp-sample gathering
19692 // (libaom av1_findSamples, mvref_common.c:1155)
19693 // requires ref_frame[1] == NONE_FRAME, so such a
19694 // neighbour must not donate samples or count in
19695 // num_proj_ref.
19696 ref_frame1: interintra_mode.map(|_| 0),
19697 mv1: None,
19698 mv,
19699 is_new_mv,
19700 size: bw4,
19701 size_h: bh4,
19702 is_global_mv0: is_global_mv_block,
19703 is_global_mv1: false,
19704 },
19705 );
19706 }
19707 }
19708 mode_for_tx = 0;
19709 uv_predict_mode = DC_PRED;
19710
19711 // lane-superres r9: spec 7.11.3.3's x_scale_fp comes from LUMA
19712 // widths only (r8's derivation) and applies unchanged to the
19713 // chroma calls below (their x_q4 is already in the chroma
19714 // plane's own pixel units). `mc::predict_scaled` has no warp/OBMC
19715 // /interintra counterpart -- those three combinations are refused
19716 // by name instead of silently sampling a scaled reference wrong
19717 // (warp_params/obmc_selected/interintra_mode are all resolved by
19718 // this point, every symbol for this block already read).
19719 let luma_scale = mc::scale_factor(py_ref.width, frame_width);
19720 if luma_scale != mc::REF_NO_SCALE {
19721 // lane-scaledref r1: libaom `allow_warp`
19722 // (av1/common/reconinter.c:41) suppresses BOTH local and
19723 // global warp under a scaled reference and predicts
19724 // translationally instead -- that fallback is implemented
19725 // below, but the one real aomenc stream this round found
19726 // that reaches it (`--enable-warped-motion=1`,
19727 // `--superres-denominator=16`, seed 47) still mismatches
19728 // ffmpeg at frame 2 luma, so the case stays refused by name
19729 // until it has a green gate rather than shipping wrong
19730 // pixels behind a lifted refusal.
19731 if warp_params.is_some() {
19732 SCALED_WARP_FALLBACK_HITS.with(|c| c.set(c.get() + 1));
19733 return Err(unsupported(
19734 "warp prediction with a scaled reference (superres, unimplemented)",
19735 ));
19736 }
19737 if obmc_selected {
19738 SCALED_OBMC_HITS.with(|c| c.set(c.get() + 1));
19739 }
19740 if interintra_mode.is_some() {
19741 SCALED_INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
19742 }
19743 }
19744
19745 // lane-inter16ab r2: `is_sub8x8_inter`'s neighbour walk reads the
19746 // PREVIOUS strip's `mv`/`ref_frame`/`interp_filters`
19747 // (reconinter_template.inc:75-82); record them for the next 1:4
19748 // strip, which is the only reader.
19749 INTER_LAST_MC.with(|c| c.set(Some((ref_frame, mv, h_filter, v_filter))));
19750 let mut pred_y = vec![0u16; side * side];
19751 let mut pred_u = vec![0u16; chroma_side * chroma_side];
19752 let mut pred_v = vec![0u16; chroma_side * chroma_side];
19753 if luma_scale == mc::REF_NO_SCALE {
19754 mc::predict_with_filters_kern(
19755 &py_ref.data,
19756 py_ref.width,
19757 py_ref.true_width,
19758 py_ref.true_height,
19759 mv_to_q4(px, mv.1, true),
19760 mv_to_q4(py, mv.0, true),
19761 side,
19762 side,
19763 write_w,
19764 write_h,
19765 h_filter,
19766 v_filter,
19767 &mut pred_y,
19768 );
19769 mc::predict_with_filters_kern(
19770 &pu_ref.data,
19771 pu_ref.width,
19772 pu_ref.true_width,
19773 pu_ref.true_height,
19774 mv_to_q4(cpx, mv.1, false),
19775 mv_to_q4(cpy, mv.0, false),
19776 chroma_side,
19777 chroma_side,
19778 write_chroma_w,
19779 write_chroma_h,
19780 h_filter,
19781 v_filter,
19782 &mut pred_u,
19783 );
19784 mc::predict_with_filters_kern(
19785 &pv_ref.data,
19786 pv_ref.width,
19787 pv_ref.true_width,
19788 pv_ref.true_height,
19789 mv_to_q4(cpx, mv.1, false),
19790 mv_to_q4(cpy, mv.0, false),
19791 chroma_side,
19792 chroma_side,
19793 write_chroma_w,
19794 write_chroma_h,
19795 h_filter,
19796 v_filter,
19797 &mut pred_v,
19798 );
19799 } else {
19800 mc::predict_scaled_kern(
19801 &py_ref.data,
19802 py_ref.width,
19803 py_ref.true_width,
19804 py_ref.true_height,
19805 mv_to_q4(px, mv.1, true),
19806 mv_to_q4(py, mv.0, true),
19807 luma_scale,
19808 side,
19809 side,
19810 write_w,
19811 write_h,
19812 h_filter,
19813 v_filter,
19814 &mut pred_y,
19815 );
19816 mc::predict_scaled_kern(
19817 &pu_ref.data,
19818 pu_ref.width,
19819 pu_ref.true_width,
19820 pu_ref.true_height,
19821 mv_to_q4(cpx, mv.1, false),
19822 mv_to_q4(cpy, mv.0, false),
19823 luma_scale,
19824 chroma_side,
19825 chroma_side,
19826 write_chroma_w,
19827 write_chroma_h,
19828 h_filter,
19829 v_filter,
19830 &mut pred_u,
19831 );
19832 mc::predict_scaled_kern(
19833 &pv_ref.data,
19834 pv_ref.width,
19835 pv_ref.true_width,
19836 pv_ref.true_height,
19837 mv_to_q4(cpx, mv.1, false),
19838 mv_to_q4(cpy, mv.0, false),
19839 luma_scale,
19840 chroma_side,
19841 chroma_side,
19842 write_chroma_w,
19843 write_chroma_h,
19844 h_filter,
19845 v_filter,
19846 &mut pred_v,
19847 );
19848 }
19849
19850 // lane-scaledref r1: libaom `allow_warp` (av1/common/reconinter.c:41)
19851 // opens with `if (av1_is_scaled(sf)) return 0;` -- BOTH local
19852 // (`wm_params`) and global warp fall back to the translational
19853 // prediction above when the reference is scaled, even though the
19854 // motion_mode symbol was still read and warp_params still
19855 // resolved. Suppress the warp, keep every symbol read.
19856 if let Some(params) = warp_params.as_ref().filter(|_| luma_scale == mc::REF_NO_SCALE) {
19857 crate::warp::warp_affine(
19858 params, &py_ref.data, py_ref.true_width as i32, py_ref.true_height as i32,
19859 py_ref.width as i32, &mut pred_y, px as i32, py as i32, side as i32,
19860 side as i32, side as i32, 0, 0,
19861 );
19862 // libaom `av1_init_warp_params` (reconinter.c): warp is
19863 // per PLANE and bails out at `block_width < 8 ||
19864 // block_height < 8`, so a plane whose own block is under
19865 // 8x8 keeps the translational prediction built above --
19866 // in 420 that is every chroma plane of a luma block below
19867 // 16x16 (lane-gmaffine r4: chroma-only mismatch of a few
19868 // levels on both 8x8-leaf motion gates).
19869 if chroma_side >= 8 {
19870 crate::warp::warp_affine(
19871 params, &pu_ref.data, pu_ref.true_width as i32, pu_ref.true_height as i32,
19872 pu_ref.width as i32, &mut pred_u, cpx as i32, cpy as i32, chroma_side as i32,
19873 chroma_side as i32, chroma_side as i32, 1, 1,
19874 );
19875 crate::warp::warp_affine(
19876 params, &pv_ref.data, pv_ref.true_width as i32, pv_ref.true_height as i32,
19877 pv_ref.width as i32, &mut pred_v, cpx as i32, cpy as i32, chroma_side as i32,
19878 chroma_side as i32, chroma_side as i32, 1, 1,
19879 );
19880 }
19881 }
19882
19883 if obmc_selected {
19884 obmc_blend(
19885 grid,
19886 neighbours,
19887 mi_row,
19888 mi_col,
19889 bw4,
19890 bh4,
19891 mi_rows as usize,
19892 mi_cols as usize,
19893 side,
19894 write_w,
19895 write_h,
19896 chroma_side,
19897 px,
19898 py,
19899 cpx,
19900 cpy,
19901 ref_y,
19902 ref_u,
19903 ref_v,
19904 other_refs,
19905 interp_fixed,
19906 frame_width,
19907 &mut pred_y,
19908 &mut pred_u,
19909 &mut pred_v,
19910 )?;
19911 }
19912
19913 // Mutually exclusive with warp/OBMC (motion_mode is not read for
19914 // an interintra block): blend the intra predictor over the MC
19915 // result, all planes (reconinter.c av1_build_interintra_predictor
19916 // plane loop).
19917 if let Some(ii) = interintra_mode {
19918 interintra_blend(y, px, py, side, ii, wedge_mask, &mut pred_y);
19919 interintra_blend(u, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_u);
19920 interintra_blend(v, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_v);
19921 }
19922
19923 // lane-inter16ab r2: libaom `build_inter_predictors_sub8x8`
19924 // (reconinter_template.inc:87-160). A 4:2:0 chroma block under a
19925 // 16x4 (4x16) luma pair covers TWO luma blocks, so it is built in
19926 // `b4_w x b4_h` = 8x2 (2x8) pieces, each from its own strip's
19927 // mv/ref/filters. The bottom (right) piece is this strip's own mv
19928 // over its own rows, which the whole-block prediction above
19929 // already wrote there (MC is position-invariant for a fixed mv),
19930 // so only the FIRST piece has to be rebuilt -- and only when
19931 // `is_sub8x8_inter` holds, i.e. the previous strip was itself a
19932 // single-reference inter block (`prev`), else libaom falls
19933 // through to the ordinary whole-block predictor.
19934 if let Some(s) = strip_chroma.filter(|s| s.has_chroma)
19935 && let Some((prev_ref, prev_mv, prev_h, prev_v)) = s.prev
19936 && luma_scale == mc::REF_NO_SCALE
19937 {
19938 let (piece_w, piece_h) = if s.horz { (8usize, 2usize) } else { (2usize, 8usize) };
19939 let (_, prev_u, prev_v_plane) = ref_planes(prev_ref, ref_y, ref_u, ref_v, other_refs)?;
19940 for (src, dst) in [(prev_u, &mut pred_u), (prev_v_plane, &mut pred_v)] {
19941 let mut piece = vec![0u16; piece_w * piece_h];
19942 mc::predict_with_filters(
19943 &src.data,
19944 src.width,
19945 src.true_width,
19946 src.true_height,
19947 mv_to_q4(cpx, prev_mv.1, false),
19948 mv_to_q4(cpy, prev_mv.0, false),
19949 piece_w,
19950 piece_h,
19951 prev_h,
19952 prev_v,
19953 &mut piece,
19954 );
19955 for row in 0..piece_h {
19956 dst[row * chroma_side..row * chroma_side + piece_w]
19957 .copy_from_slice(&piece[row * piece_w..(row + 1) * piece_w]);
19958 }
19959 }
19960 INTER16_SUB8_PIECE_HITS.with(|c| c.set(c.get() + 1));
19961 }
19962
19963 // lane-inter4 r2: a rectangular strip's transform tree starts from
19964 // its own rect `max_txsize_rect_lookup` entry, not a square one.
19965 let rect_tu = (write_w, write_h) != (side, side);
19966 vartx_leaves = if rect_tu {
19967 read_block_tx_size_rect(
19968 dec,
19969 cdfs,
19970 neighbours,
19971 at_mi,
19972 (write_w, write_h),
19973 (mi_cols as usize, mi_rows as usize),
19974 skip,
19975 )?
19976 } else {
19977 read_block_tx_size(
19978 dec,
19979 cdfs,
19980 neighbours,
19981 at_mi,
19982 side,
19983 (mi_cols as usize, mi_rows as usize),
19984 true,
19985 skip,
19986 )?
19987 .1
19988 };
19989 if skip {
19990 y.reconstruct_mc_rect(
19991 px,
19992 py,
19993 side,
19994 write_w,
19995 write_h,
19996 &pred_y,
19997 &vec![0i32; side * side],
19998 );
19999 if has_chroma {
20000 u.reconstruct_mc_rect(
20001 cpx,
20002 cpy,
20003 chroma_side,
20004 write_chroma_w,
20005 write_chroma_h,
20006 &pred_u,
20007 &vec![0i32; chroma_side * chroma_side],
20008 );
20009 v.reconstruct_mc_rect(
20010 cpx,
20011 cpy,
20012 chroma_side,
20013 write_chroma_w,
20014 write_chroma_h,
20015 &pred_v,
20016 &vec![0i32; chroma_side * chroma_side],
20017 );
20018 }
20019 luma_grid = vec![0i32; side * side];
20020 u_grid = vec![0i32; chroma_side * chroma_side];
20021 v_grid = vec![0i32; chroma_side * chroma_side];
20022 } else {
20023 // lane-inter4 r2: a rect strip's coefficient context spans its
20024 // OWN width above and height left -- reading `side` cells both
20025 // ways indexes past the tile's last mi row for a bottom strip.
20026 let around = if rect_tu {
20027 neighbours.around_mi_rect(at_mi, write_w, write_h)
20028 } else {
20029 neighbours.around_mi(at, side)
20030 };
20031 // lane-inter16ab r2: the pair's chroma transform sits at the
20032 // EVEN strip's mi origin and spans both strips, so its
20033 // above/left coefficient context is the pair's, not this
20034 // strip's row.
20035 let around_c = match strip_chroma {
20036 Some(s) if s.has_chroma => neighbours.around_mi_rect(
20037 s.pair_mi,
20038 if s.horz { 16 } else { 8 },
20039 if s.horz { 8 } else { 16 },
20040 ),
20041 _ => around,
20042 };
20043 let luma_tx_type;
20044 // lane-sb128c r1: a 128x128 inter block's four chroma units
20045 // are read INSIDE the luma leaf loop (one per 64x64 mu chunk);
20046 // these collect them for the block-level neighbour write-back.
20047 let mut u_units = vec![0i32; chroma_side * chroma_side];
20048 let mut v_units = vec![0i32; chroma_side * chroma_side];
20049 if let Some(leaves) = vartx_leaves.clone() {
20050 // spec 5.11.17's transform tree, leaf by leaf in the order
20051 // `read_var_tx_size` coded it: each unit reads its own
20052 // coefficients against the neighbour magnitudes the
20053 // earlier units already wrote, and reconstructs over its
20054 // own slice of the block's motion-compensated predictor.
20055 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
20056 let mut first_tx_type = TxType::DctDct;
20057 for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() {
20058 let tu_mi = (at_mi.0 + row, at_mi.1 + col);
20059 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
20060 let (tu_grid, tu_tx_type) = if tw == th {
20061 let tx_px = tw;
20062 let mut tu_pred = Vec::with_capacity(tx_px * tx_px);
20063 for rr in 0..tx_px {
20064 let start = (row * MI + rr) * side + col * MI;
20065 tu_pred.extend_from_slice(&pred_y[start..start + tx_px]);
20066 }
20067 let scan = default_scan(tx_px.min(32));
20068 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI);
20069 read_inter_plane(
20070 dec,
20071 cdfs,
20072 inter_txbset_for(tx_px, reduced),
20073 &scan,
20074 0,
20075 neighbours.around_mi(tu_mi, tx_px)[0],
20076 mode_for_tx,
20077 y,
20078 tu_px,
20079 tu_py,
20080 tx_px,
20081 base_q_idx,
20082 &tu_pred,
20083 None,
20084 Some(tu_skip_ctx),
20085 )?
20086 } else {
20087 // lane-r14 r3: a 1:4 strip's `sub_tx_size_map`
20088 // sub-transform is RECTANGULAR (TX_64X16 ->
20089 // TX_32X16, TX_16X64 -> TX_16X32), so this leaf is
20090 // read with the rect coefficient machinery, at its
20091 // own `txb_skip_ctx`/neighbour spans -- the unit is
20092 // smaller than its block, so `get_txb_ctx_general`'s
20093 // neighbour table applies, not the lone-TU 0.
20094 vartx_rect_leaf_hit(tw, th);
20095 let tu_skip_ctx =
20096 neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI);
20097 let start = row * MI * side + col * MI;
20098 read_inter_plane_rect(
20099 dec,
20100 cdfs,
20101 rect_inter_luma_set(tw, th)?,
20102 (tw, th),
20103 side,
20104 0,
20105 neighbours.around_mi_rect(tu_mi, tw, th)[0],
20106 mode_for_tx,
20107 y,
20108 tu_px,
20109 tu_py,
20110 &pred_y[start..],
20111 None,
20112 Some(tu_skip_ctx),
20113 )?
20114 };
20115 if idx == 0 {
20116 first_tx_type = tu_tx_type;
20117 }
20118 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
20119 // lane-sb128c r1: libaom's `decode_token_recon_block`
20120 // walks 64x64 "mu" chunks (`mu_blocks_wide/high =
20121 // mi_size_wide[BLOCK_64X64]`) and codes EVERY PLANE of
20122 // a chunk before the next one, so a 128x128 block
20123 // interleaves Y,U,V per quadrant -- the same order the
20124 // intra 128 path reads (lane-sb128b r3, measured
20125 // against aomdec's `EC_TRACE_COEFF`). Below 128 a block
20126 // is a single chunk and this never fires.
20127 if side > 64 {
20128 let chunk = (row / 16, col / 16);
20129 let done = idx + 1 == leaves.len()
20130 || (leaves[idx + 1].0 / 16, leaves[idx + 1].1 / 16) != chunk;
20131 if done {
20132 let (cr, cc) = chunk;
20133 // `av1_get_max_uv_txsize(BLOCK_128X128)` =
20134 // `av1_get_adjusted_tx_size(TX_64X64)` =
20135 // TX_32X32: one 32x32 chroma unit per chunk.
20136 let cu_tx = 32usize;
20137 let luma_span = cu_tx * 2;
20138 let cu_mi = (at_mi.0 + cr * 16, at_mi.1 + cc * 16);
20139 let cu_around = neighbours.around_mi(cu_mi, luma_span);
20140 let (cu_x, cu_y) = (cpx + cc * cu_tx, cpy + cr * cu_tx);
20141 let cu_scan = default_scan(cu_tx);
20142 for plane_idx in 1..3 {
20143 let (src, buf) = if plane_idx == 1 {
20144 (&pred_u, &mut *u)
20145 } else {
20146 (&pred_v, &mut *v)
20147 };
20148 let mut cu_pred = Vec::with_capacity(cu_tx * cu_tx);
20149 for rr in 0..cu_tx {
20150 let start =
20151 (cr * cu_tx + rr) * chroma_side + cc * cu_tx;
20152 cu_pred.extend_from_slice(&src[start..start + cu_tx]);
20153 }
20154 let cu_grid = read_inter_plane(
20155 dec,
20156 cdfs,
20157 chroma_set,
20158 &cu_scan,
20159 plane_idx,
20160 cu_around[plane_idx],
20161 mode_for_tx,
20162 buf,
20163 cu_x,
20164 cu_y,
20165 cu_tx,
20166 base_q_idx,
20167 &cu_pred,
20168 Some(first_tx_type),
20169 Some(3),
20170 )?
20171 .0;
20172 // Immediately, so the NEXT chunk's unit
20173 // reads this one's coefficient context.
20174 neighbours.record_mi_chroma(
20175 cu_mi, luma_span, luma_span, plane_idx, &cu_grid,
20176 );
20177 CHROMA_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
20178 let dst = if plane_idx == 1 {
20179 &mut u_units
20180 } else {
20181 &mut v_units
20182 };
20183 for rr in 0..cu_tx {
20184 let start =
20185 (cr * cu_tx + rr) * chroma_side + cc * cu_tx;
20186 dst[start..start + cu_tx]
20187 .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]);
20188 }
20189 }
20190 }
20191 }
20192 }
20193 // `av1_get_tx_type`'s chroma lookup scales the chroma
20194 // position back to luma, so an inter block's chroma
20195 // inherits the *first* (top-left) luma unit's coded type.
20196 luma_tx_type = first_tx_type;
20197 luma_grid = vec![0i32; side * side];
20198 } else if rect_tu {
20199 // The whole-block rectangular transform unit
20200 // (`txfm_partition` said 0 at depth 0).
20201 let (grid, tx_type) = read_inter_plane_rect(
20202 dec,
20203 cdfs,
20204 rect_inter_luma_set(write_w, write_h)?,
20205 (write_w, write_h),
20206 side,
20207 0,
20208 around[0],
20209 mode_for_tx,
20210 y,
20211 px,
20212 py,
20213 &pred_y,
20214 None,
20215 None,
20216 )?;
20217 luma_tx_type = tx_type;
20218 luma_grid = embed_rect_grid(&grid, write_w, write_h, side);
20219 } else {
20220 (luma_grid, luma_tx_type) = read_inter_plane(
20221 dec,
20222 cdfs,
20223 luma_set_inter,
20224 scan_luma,
20225 0,
20226 around[0],
20227 mode_for_tx,
20228 y,
20229 px,
20230 py,
20231 side,
20232 base_q_idx,
20233 &pred_y,
20234 None,
20235 None,
20236 )?;
20237 }
20238 if !has_chroma {
20239 // `is_chroma_reference` is false for this strip: libaom's
20240 // plane loop (decodeframe.c
20241 // `predict_and_reconstruct_intra_block`/
20242 // `reconstruct_inter_block`'s `for (plane...)` guarded by
20243 // `xd->is_chroma_ref`) codes NO chroma transform here, so
20244 // neither symbol nor context exists.
20245 u_grid = vec![0i32; chroma_side * chroma_side];
20246 v_grid = vec![0i32; chroma_side * chroma_side];
20247 } else if rect_tu {
20248 // `av1_get_max_uv_txsize(bsize)`: the chroma transform of a
20249 // 2:1 strip is the strip's own rect chroma size (16x8 /
20250 // 8x16), one unit for the whole block, and it codes no
20251 // `tx_type` symbol -- it inherits the luma unit's.
20252 let (uw, uh) = (write_chroma_w, write_chroma_h);
20253 u_grid = embed_rect_grid(
20254 &read_inter_plane_rect(
20255 dec,
20256 cdfs,
20257 rect_inter_chroma_set(write_chroma_w, write_chroma_h)?,
20258 (uw, uh),
20259 chroma_side,
20260 1,
20261 around_c[1],
20262 mode_for_tx,
20263 u,
20264 cpx,
20265 cpy,
20266 &pred_u,
20267 Some(luma_tx_type),
20268 None,
20269 )?
20270 .0,
20271 uw,
20272 uh,
20273 chroma_side,
20274 );
20275 v_grid = embed_rect_grid(
20276 &read_inter_plane_rect(
20277 dec,
20278 cdfs,
20279 rect_inter_chroma_set(write_chroma_w, write_chroma_h)?,
20280 (uw, uh),
20281 chroma_side,
20282 2,
20283 around_c[2],
20284 mode_for_tx,
20285 v,
20286 cpx,
20287 cpy,
20288 &pred_v,
20289 Some(luma_tx_type),
20290 None,
20291 )?
20292 .0,
20293 uw,
20294 uh,
20295 chroma_side,
20296 );
20297 } else if side > 64 {
20298 // Already read inside the mu-chunk loop above.
20299 u_grid = std::mem::take(&mut u_units);
20300 v_grid = std::mem::take(&mut v_units);
20301 } else {
20302 u_grid = read_inter_plane(
20303 dec,
20304 cdfs,
20305 chroma_set,
20306 scan_chroma,
20307 1,
20308 around[1],
20309 mode_for_tx,
20310 u,
20311 cpx,
20312 cpy,
20313 chroma_side,
20314 base_q_idx,
20315 &pred_u,
20316 Some(luma_tx_type),
20317 None,
20318 )?
20319 .0;
20320 v_grid = read_inter_plane(
20321 dec,
20322 cdfs,
20323 chroma_set,
20324 scan_chroma,
20325 2,
20326 around[2],
20327 mode_for_tx,
20328 v,
20329 cpx,
20330 cpy,
20331 chroma_side,
20332 base_q_idx,
20333 &pred_v,
20334 Some(luma_tx_type),
20335 None,
20336 )?
20337 .0;
20338 }
20339 }
20340 }
20341 } else {
20342 // lane-partitions r1: intra prediction (`PlaneBuf::reconstruct`) has
20343 // no rectangular counterpart -- an intra-coded HORZ/VERT strip needs
20344 // its own true-width/height edge/predict math, unlike the inter
20345 // skip path above (which only needed a clipped write of an
20346 // already-square-predicted buffer). Named refusal instead of a
20347 // silently wrong square-shaped intra prediction.
20348 // lane-inter16ab r2: `decode_intra_rect_in_inter` has no chroma-pair
20349 // path (it predicts and codes chroma at the strip's own halved
20350 // footprint), so an INTRA 16x4 / 4x16 strip inside a 1:4 partition is
20351 // refused by name rather than decoded with a 8x2 chroma transform
20352 // libaom never coded.
20353 if write_w.min(write_h) < 8 {
20354 return Err(unsupported(
20355 "an intra 16x4/4x16 strip inside an inter 16x16-level 1:4 partition (its 4:2:0 chroma pair is coded once for two strips; only the inter path implements that pairing)",
20356 ));
20357 }
20358 if write_w != side || write_h != side {
20359 // lane-intrarect r1: the strip decodes through its own rect
20360 // machinery ([`decode_intra_rect_in_inter`] -> the key-frame
20361 // paths' [`decode_rect_split`]) instead of refusing. That call
20362 // already writes everything the shared tail below would for a
20363 // square block EXCEPT the inter-side bands and the mi map, so
20364 // this arm returns rather than falling through (a second
20365 // `record_rect`/`fill_lf_grid_rect` at block granularity would
20366 // overwrite the per-transform-unit records it just made).
20367 decode_intra_rect_in_inter(
20368 dec,
20369 cdfs,
20370 neighbours,
20371 at,
20372 write_w,
20373 write_h,
20374 skip,
20375 allow_screen_content_tools,
20376 y,
20377 u,
20378 v,
20379 base_q_idx,
20380 )?;
20381 // merge b51719f+lane-intrarect: `at` is in MI units on this path
20382 // (lane-inter4), so the strip's mi origin is `at` itself -- the
20383 // lane's `r * SUB_MI` re-derivation would snap a sub-SUB strip to
20384 // its enclosing 16-px cell.
20385 let (mi_r0, mi_c0) = (rmi, cmi);
20386 for dr in 0..write_h / MI {
20387 for dc in 0..write_w / MI {
20388 grid.set(
20389 mi_r0 + dr,
20390 mi_c0 + dc,
20391 MiInfo {
20392 is_inter: false,
20393 ref_frame: -1,
20394 ref_frame1: None,
20395 mv1: None,
20396 mv: (0, 0),
20397 is_new_mv: false,
20398 size: write_w / MI,
20399 size_h: write_h / MI,
20400 is_global_mv0: false,
20401 is_global_mv1: false,
20402 },
20403 );
20404 }
20405 }
20406 neighbours.record_inter_rect_mi(
20407 at,
20408 write_w / MI,
20409 write_h / MI,
20410 skip,
20411 false,
20412 0,
20413 [3, 3],
20414 skip_mode,
20415 );
20416 return Ok(());
20417 }
20418 let mode = dec.symbol(&mut cdfs.y_mode[size_group_wh(write_w, write_h)]);
20419 if std::env::var_os("EC_IIS").is_some() {
20420 eprintln!(
20421 "TRACE iis px={px} py={py} side={side} w={write_w} h={write_h} sg={} mode={mode} skip={skip}",
20422 size_group_wh(write_w, write_h)
20423 );
20424 }
20425 if mode >= 13 {
20426 return Err(unsupported(
20427 "an intra mode this decoder does not code (round 2)",
20428 ));
20429 }
20430 // lane-angleinter r1: `read_intra_angle_info` (libaom `decodemv.c`,
20431 // inside `read_intra_block_mode_info`) -- an intra block in an inter
20432 // frame reads `angle_delta_y` off the same
20433 // `angle_delta_cdf[mode - V_PRED]` row a key-frame block does, and
20434 // the delta feeds the directional predictor (and the edge
20435 // filter/upsample decision derived from the delta'd angle) unchanged.
20436 // The symbol was read and then refused before this round even though
20437 // aomenc enables `--enable-angle-delta` by default.
20438 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
20439 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
20440 } else {
20441 0
20442 };
20443 if angle_delta_y != 0 {
20444 INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.set(c.get() + 1));
20445 }
20446 // The delta'd angle decides whether the intra edge filter runs at
20447 // all, so this block needs the same luma edge-filter-type neighbour
20448 // check a key-frame block does (`get_intra_edge_filter_type`, spec
20449 // 7.11.2) -- this arm passed a hardcoded `false` while every
20450 // directional intra-in-inter block was refused above.
20451 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
20452 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
20453 // lane-sbrect10 r1 (class wrong-alphabet-same-value, second instance
20454 // after lane-sbpart r3's rect strips): `is_cfl_allowed` (libaom
20455 // `blockd.h` -- `block_size_wide[bsize] <= 32 && block_size_high[bsize]
20456 // <= 32`, spec 5.11.5) caps CFL at 32x32, so a 64x64 intra block inside
20457 // an INTER frame reads the 13-symbol `uv_mode_no_cfl` alphabet. Reading
20458 // the 14-symbol CFL one gave the same DC_PRED VALUE but narrowed the
20459 // arithmetic coder by the wrong interval, desyncing the tile from this
20460 // block on.
20461 let cfl_allowed = write_w.max(write_h) <= 32;
20462 if !cfl_allowed {
20463 NOCFL_UV_MODE_HITS.with(|c| c.set(c.get() + 1));
20464 }
20465 let uv_mode = if cfl_allowed {
20466 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
20467 } else {
20468 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
20469 };
20470 if (9..=12).contains(&uv_mode) {
20471 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
20472 }
20473 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
20474 Some(read_cfl_alphas(dec, cdfs))
20475 } else {
20476 None
20477 };
20478 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for
20479 // the angle-delta question, same as [`read_intra_mode`]'s own copy
20480 // -- `uv_mode` (13) already falls outside `V_PRED..=D67_PRED` so the
20481 // `else` branch below is exact for it either way.
20482 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
20483 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
20484 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
20485 } else {
20486 0
20487 };
20488 if angle_delta_uv != 0 {
20489 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
20490 INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|c| c.set(c.get() + 1));
20491 }
20492 uv_predict_mode = if uv_mode == UV_CFL_PRED {
20493 DC_PRED
20494 } else {
20495 uv_mode
20496 };
20497 // lane-chroma r4: same chroma edge-filter-strength neighbour check
20498 // as [`read_intra_mode`]/[`read_intra_mode_rect`] -- the CHROMA
20499 // neighbour's own `uv_mode`, not the luma one.
20500 let smooth_neighbor_uv =
20501 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
20502 // `read_palette_mode_info` (decodemv.c:567, called from
20503 // `read_intra_block_mode_info` right after `xd->cfl.store_y`, same
20504 // gating and same corner-cut as `read_intra_mode`'s own copy above
20505 // -- `palette_mode_ctx`/`palette_uv_mode_ctx` hardcoded 0, provably
20506 // safe since a nonzero neighbour `palette_size` would already have
20507 // refused the decode that produced it.
20508 // lane-inter16ab r4 (class sweep): `av1_get_palette_bsize_ctx` is keyed
20509 // by the block's TRUE footprint -- a rect strip's row is not its
20510 // enclosing square's, and a 16x4 strip (64 pixels) reads no palette
20511 // symbol at all.
20512 if allow_screen_content_tools
20513 && let Some(bsize_ctx) = palette_bsize_ctx_wh(write_w, write_h)
20514 {
20515 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][0]) != 0 {
20516 return Err(unsupported(
20517 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
20518 ));
20519 }
20520 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
20521 return Err(unsupported(
20522 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
20523 ));
20524 }
20525 }
20526 // lane-fiinter r1: `read_filter_intra_mode_info` (libaom `decodemv.c`,
20527 // the tail of `read_intra_block_mode_info`) -- an intra block inside
20528 // an INTER frame reads `use_filter_intra` in exactly the same place a
20529 // key-frame block does, right after the palette syntax. Nothing read
20530 // it here before this round, and aomenc enables filter intra by
20531 // default, so every inter frame carrying one desynced at this symbol.
20532 // `av1_filter_intra_allowed`'s `palette_size[0] == 0` term is implied:
20533 // a real palette-Y block already returned above.
20534 let mut filter_intra = None;
20535 if mode == DC_PRED
20536 && ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get)
20537 // lane-inter16ab r4 (class sweep): `cdf::FILTER_INTRA`'s row is the
20538 // true `BLOCK_SIZES_ALL` class of this strip, not its square side's.
20539 && let Some(class) = filter_intra_size_class_rect(write_w, write_h)
20540 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
20541 {
20542 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
20543 INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
20544 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
20545 }
20546 mode_for_tx = mode;
20547 block_filter = [3, 3];
20548 ref_frame_for_lf = 0;
20549 globalmv_for_lf = false;
20550 let (mi_row, mi_col) = (rmi, cmi);
20551 for dr in 0..side / 4 {
20552 for dc in 0..side / 4 {
20553 grid.set(
20554 mi_row + dr,
20555 mi_col + dc,
20556 MiInfo {
20557 is_inter: false,
20558 ref_frame: -1,
20559 ref_frame1: None,
20560 mv1: None,
20561 mv: (0, 0),
20562 is_new_mv: false,
20563 size: side / 4,
20564 size_h: side / 4,
20565 is_global_mv0: false,
20566 is_global_mv1: false,
20567 },
20568 );
20569 }
20570 }
20571
20572 // lane-intrainter r1: an intra block in an inter frame reads the same
20573 // `tx_depth` symbol a key-frame block does, and when it splits, the
20574 // block codes one intra prediction + one coefficient set PER
20575 // transform unit (`decode_block`'s multi-TU branch), not one for the
20576 // whole block. The leaf list rides the existing `vartx_leaves` slot,
20577 // whose tail already does the split-block neighbour write-back
20578 // (`record_split_luma`) and the per-TU deblock edges.
20579 vartx_leaves = read_block_tx_size(
20580 dec,
20581 cdfs,
20582 neighbours,
20583 at_mi,
20584 side,
20585 (mi_cols as usize, mi_rows as usize),
20586 false,
20587 skip,
20588 )?
20589 .1;
20590 let reach = Reach::of(side, px, py, y.width, y.height);
20591 let split_luma = vartx_leaves.is_some();
20592 // lane-sb128c r3: a 128x128 INTRA block inside an inter frame codes
20593 // its chroma per 64x64 mu chunk, exactly as the inter half above --
20594 // `decode_token_recon_block` walks `mu_blocks_wide/high` and codes
20595 // every plane of a chunk before the next chunk's luma. These collect
20596 // the four TX_32X32 units per plane for the block-level write-back.
20597 let mut u_units = vec![0i32; chroma_side * chroma_side];
20598 let mut v_units = vec![0i32; chroma_side * chroma_side];
20599 if let Some(leaves) = vartx_leaves.clone() {
20600 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
20601 for (idx, &(row, col, tx_px, _)) in leaves.iter().enumerate() {
20602 let tu_mi = (at_mi.0 + row, at_mi.1 + col);
20603 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
20604 // A transform unit inside a block is not a block at that
20605 // position (class from lane-palette2 r12): top-right /
20606 // bottom-left availability is the block's, narrowed by the
20607 // unit's own offset inside it.
20608 let tu_reach = Reach::of_tu(side, side, col * MI, row * MI, tx_px, tx_px, reach);
20609 let tu_grid = if skip {
20610 y.reconstruct(
20611 tu_px,
20612 tu_py,
20613 tx_px,
20614 mode,
20615 angle_delta_y,
20616 tu_reach,
20617 &vec![0i32; tx_px * tx_px],
20618 None,
20619 filter_intra,
20620 smooth_neighbor,
20621 );
20622 vec![0i32; tx_px * tx_px]
20623 } else {
20624 // The unit's bsize is smaller than the block it sits in,
20625 // so `txb_skip_ctx` is the neighbour-magnitude table, not
20626 // the lone-TU 0 (`get_txb_ctx_general`).
20627 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI);
20628 read_plane(
20629 dec,
20630 cdfs,
20631 txbset_for(tx_px, reduced),
20632 // lane-sb128c r5: a TX_64X64 unit codes only its
20633 // top-left 32x32 of frequencies (spec 5.11.40), so
20634 // the scan and `tx_side` are the CODED corner while
20635 // `side` stays the transform's true 64.
20636 &default_scan(tx_px.min(32)),
20637 0,
20638 neighbours.around_mi(tu_mi, tx_px)[0],
20639 mode,
20640 mode,
20641 angle_delta_y,
20642 tu_reach,
20643 y,
20644 tu_px,
20645 tu_py,
20646 tx_px,
20647 tx_px.min(32),
20648 base_q_idx,
20649 None,
20650 filter_intra,
20651 Some(tu_skip_ctx),
20652 smooth_neighbor,
20653 )?
20654 };
20655 neighbours.record_mi_luma(tu_mi, tx_px, &tu_grid);
20656 if side > 64 {
20657 let chunk = (row / 16, col / 16);
20658 let done = idx + 1 == leaves.len()
20659 || (leaves[idx + 1].0 / 16, leaves[idx + 1].1 / 16) != chunk;
20660 if !done {
20661 continue;
20662 }
20663 let (cr, cc) = chunk;
20664 // `av1_get_max_uv_txsize(BLOCK_128X128)` =
20665 // `av1_get_adjusted_tx_size(TX_64X64)` = TX_32X32.
20666 let cu_tx = 32usize;
20667 let luma_span = cu_tx * 2;
20668 let cu_mi = (at_mi.0 + cr * 16, at_mi.1 + cc * 16);
20669 let cu_around = neighbours.around_mi(cu_mi, luma_span);
20670 let (cu_x, cu_y) = (cpx + cc * cu_tx, cpy + cr * cu_tx);
20671 let cu_reach = crate::decode::tu_reach(
20672 side, side,
20673 cc * luma_span, cr * luma_span, luma_span,
20674 reach, px, py, y.width, y.height,
20675 );
20676 let cu_scan = default_scan(cu_tx);
20677 for plane_idx in 1..3 {
20678 let buf: &mut PlaneBuf = if plane_idx == 1 { &mut *u } else { &mut *v };
20679 let cu_grid = if skip {
20680 buf.reconstruct(
20681 cu_x,
20682 cu_y,
20683 cu_tx,
20684 uv_predict_mode,
20685 angle_delta_uv,
20686 cu_reach,
20687 &vec![0i32; cu_tx * cu_tx],
20688 None,
20689 None,
20690 smooth_neighbor_uv,
20691 );
20692 vec![0i32; cu_tx * cu_tx]
20693 } else {
20694 read_plane(
20695 dec,
20696 cdfs,
20697 chroma_set,
20698 &cu_scan,
20699 plane_idx,
20700 cu_around[plane_idx],
20701 mode,
20702 uv_predict_mode,
20703 angle_delta_uv,
20704 cu_reach,
20705 buf,
20706 cu_x,
20707 cu_y,
20708 cu_tx,
20709 cu_tx,
20710 base_q_idx,
20711 // CfL is refused above 32x32
20712 // (`is_cfl_allowed`), so never here.
20713 None,
20714 None,
20715 // The uv plane block (64x64) is larger than
20716 // the unit (32x32): `get_txb_ctx`'s offset-10
20717 // rows, +3 on the `txb_skip_chroma_32` table
20718 // (lane-sb128b r3).
20719 Some(3),
20720 smooth_neighbor_uv,
20721 )?
20722 };
20723 // Immediately, so the NEXT chunk's unit reads this
20724 // one's coefficient context.
20725 neighbours.record_mi_chroma(
20726 cu_mi, luma_span, luma_span, plane_idx, &cu_grid,
20727 );
20728 CHROMA_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
20729 let dst = if plane_idx == 1 { &mut u_units } else { &mut v_units };
20730 for rr in 0..cu_tx {
20731 let start = (cr * cu_tx + rr) * chroma_side + cc * cu_tx;
20732 dst[start..start + cu_tx]
20733 .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]);
20734 }
20735 }
20736 }
20737 }
20738 }
20739 if side > 64 {
20740 // Chroma is already coded and reconstructed per mu chunk above.
20741 luma_grid = vec![0i32; side * side];
20742 u_grid = std::mem::take(&mut u_units);
20743 v_grid = std::mem::take(&mut v_units);
20744 INTRA_128_IN_INTER_HITS.with(|c| c.set(c.get() + 1));
20745 } else if skip {
20746 if !split_luma {
20747 y.reconstruct(
20748 px,
20749 py,
20750 side,
20751 mode,
20752 angle_delta_y,
20753 reach,
20754 &vec![0i32; side * side],
20755 None,
20756 filter_intra,
20757 smooth_neighbor,
20758 );
20759 }
20760 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
20761 u.reconstruct(
20762 cpx,
20763 cpy,
20764 chroma_side,
20765 uv_predict_mode,
20766 angle_delta_uv,
20767 reach,
20768 &vec![0i32; chroma_side * chroma_side],
20769 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
20770 None,
20771 smooth_neighbor_uv,
20772 );
20773 v.reconstruct(
20774 cpx,
20775 cpy,
20776 chroma_side,
20777 uv_predict_mode,
20778 angle_delta_uv,
20779 reach,
20780 &vec![0i32; chroma_side * chroma_side],
20781 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
20782 None,
20783 smooth_neighbor_uv,
20784 );
20785 luma_grid = vec![0i32; side * side];
20786 u_grid = vec![0i32; chroma_side * chroma_side];
20787 v_grid = vec![0i32; chroma_side * chroma_side];
20788 } else {
20789 let around = neighbours.around_mi(at, side);
20790 luma_grid = if split_luma {
20791 // Already coded and reconstructed unit by unit above; the
20792 // block-level grid is only the neighbour write-back's input,
20793 // which `record_split_luma` ignores for plane 0.
20794 vec![0i32; side * side]
20795 } else {
20796 read_plane(
20797 dec,
20798 cdfs,
20799 luma_set_intra,
20800 scan_luma,
20801 0,
20802 around[0],
20803 mode,
20804 mode,
20805 angle_delta_y,
20806 reach,
20807 y,
20808 px,
20809 py,
20810 side,
20811 luma_tx,
20812 base_q_idx,
20813 None,
20814 filter_intra,
20815 None,
20816 smooth_neighbor,
20817 )?
20818 };
20819 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
20820 u_grid = read_plane(
20821 dec,
20822 cdfs,
20823 chroma_set,
20824 scan_chroma,
20825 1,
20826 around[1],
20827 mode,
20828 uv_predict_mode,
20829 angle_delta_uv,
20830 reach,
20831 u,
20832 cpx,
20833 cpy,
20834 chroma_side,
20835 chroma_tx,
20836 base_q_idx,
20837 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
20838 None,
20839 None,
20840 smooth_neighbor_uv,
20841 )?;
20842 v_grid = read_plane(
20843 dec,
20844 cdfs,
20845 chroma_set,
20846 scan_chroma,
20847 2,
20848 around[2],
20849 mode,
20850 uv_predict_mode,
20851 angle_delta_uv,
20852 reach,
20853 v,
20854 cpx,
20855 cpy,
20856 chroma_side,
20857 chroma_tx,
20858 base_q_idx,
20859 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
20860 None,
20861 None,
20862 smooth_neighbor_uv,
20863 )?;
20864 }
20865 }
20866 // lane-comppin r9: end-of-block checkpoint -- everything between
20867 // post_assign_mv and here (interintra, motion_mode, interp_filter, then
20868 // every plane's coeffs) is unproven; a range mismatch here vs aomdec's
20869 // equivalent post-content point (added at the matching call site)
20870 // narrows the ladder to this block's own tail instead of the next
20871 // block's partition read.
20872 if std::env::var_os("EC_AV1_TELL").is_some() {
20873 eprintln!(
20874 "TELL mi_row={} mi_col={} label=block_end tell={} range={}",
20875 rmi, cmi, dec.debug_bitpos(), dec.debug_state().0
20876 );
20877 }
20878 // lane-inter16ab r2: the pair's chroma coefficient context spans BOTH
20879 // strips (mirroring the intra `decode_rect4_16` path), and the even
20880 // strip's own record wrote empty chroma state over those cells -- this
20881 // rewrite is what libaom's single `av1_set_contexts` call for the 8x4
20882 // (4x8) chroma unit leaves behind.
20883 let pair_chroma = strip_chroma
20884 .filter(|s| s.has_chroma)
20885 .map(|s| (s, neighbour_state(&u_grid), neighbour_state(&v_grid)));
20886 if vartx_leaves.is_some() {
20887 // Plane 0 is already correct per transform unit
20888 // ([`Neighbours::record_mi_luma`] above); this writes everything else
20889 // [`Neighbours::record_rect`] would (a var-tx block is always square,
20890 // so `write_w == write_h == side`).
20891 //
20892 // lane-mergefix r3 (class `tx-grid-published-block-side`, OPEN): that
20893 // premise is FALSE for a superblock-level PARTITION_VERT inter strip
20894 // (32x64 with `side == 64`), which stamps the PARENT's 64 into
20895 // `above_side_mi`/`left_side_mi` and makes the next superblock's
20896 // 64-level partition ctx read 0 where the oracle reads 1. Passing
20897 // `write_w, write_h` here (or republishing only the two side bands,
20898 // per piece or over the parent span) fixes that ladder AND turns two
20899 // attempts of `real_aomenc_1to4_streams_..._rect_vartx_leaves_fire`
20900 // into the named "non-skip rectangular strip needs rectangular
20901 // residual coding" refusal -- all three variants measured in r3, see
20902 // lanes/mergefix-r3.report.md. Left at the parent value until the
20903 // band write moves into the partition arms.
20904 neighbours.record_split_luma_rect_mi(at, side, side, mode_for_tx, uv_predict_mode, [&u_grid, &v_grid]);
20905 } else {
20906 neighbours.record_rect_mi(
20907 at,
20908 write_w,
20909 write_h,
20910 mode_for_tx,
20911 uv_predict_mode,
20912 &[luma_grid, u_grid, v_grid],
20913 );
20914 }
20915 if let Some((s, u_state, v_state)) = pair_chroma {
20916 let (pw, ph) = if s.horz { (16usize, 8usize) } else { (8, 16) };
20917 let round_up_even = |n: usize| n.div_ceil(2) * 2;
20918 let (bound_h, bound_w) = (
20919 round_up_even(neighbours.mi_rows),
20920 round_up_even(neighbours.mi_cols),
20921 );
20922 for cell in 0..(ph / MI) {
20923 if s.pair_mi.0 + cell < bound_h
20924 && let Some(slot) = neighbours.left.get_mut(s.pair_mi.0 + cell)
20925 {
20926 slot[1] = u_state;
20927 slot[2] = v_state;
20928 }
20929 }
20930 for cell in 0..(pw / MI) {
20931 if s.pair_mi.1 + cell < bound_w
20932 && let Some(slot) = neighbours.above.get_mut(s.pair_mi.1 + cell)
20933 {
20934 slot[1] = u_state;
20935 slot[2] = v_state;
20936 }
20937 }
20938 neighbours.record_uv_mode_mi(s.pair_mi.0, s.pair_mi.1, pw / MI, ph / MI, uv_predict_mode);
20939 INTER16_CHROMA_PAIR_HITS.with(|c| c.set(c.get() + 1));
20940 }
20941 neighbours.record_inter_rect_mi(
20942 at,
20943 write_w / MI,
20944 write_h / MI,
20945 skip,
20946 is_inter,
20947 ref_frame_for_lf,
20948 block_filter,
20949 skip_mode,
20950 );
20951 if let Some((ref1, group_idx, idx)) = compound_ctx {
20952 neighbours.record_compound_ctx_rect_mi(at, write_w / MI, write_h / MI, ref1, group_idx, idx);
20953 }
20954 neighbours.fill_skip_grid_rect(
20955 (rmi, cmi),
20956 write_w / MI,
20957 write_h / MI,
20958 skip,
20959 );
20960 neighbours.fill_lf_grid_rect(
20961 (rmi, cmi),
20962 write_w / MI,
20963 write_h / MI,
20964 // lane-rect r2: the strip's true TX_32X16/TX_16X32 dims -- the
20965 // single-scalar corner-cut deblocked the strip seam with the wrong
20966 // edge length (1-px chroma drift on rect-flake-1 f17+).
20967 write_w as u8,
20968 write_h as u8,
20969 // ref_grid's packed convention (lf_level): sign carries GLOBALMV,
20970 // whose mode_lf_lut row is 0, not the 1 every other inter mode gets.
20971 if globalmv_for_lf {
20972 -ref_frame_for_lf
20973 } else {
20974 ref_frame_for_lf
20975 },
20976 );
20977 // lane-txselect: a var-tx block's deblock edges follow its own transform
20978 // units, not the block -- for LUMA only (lane-golomb r6): the chroma
20979 // grids keep the block's own `av1_get_max_uv_txsize`, which is what
20980 // libaom's `get_transform_size` reads for `plane != AOM_PLANE_Y`.
20981 // lane-sb128c r4: libaom `set_one_param_for_line_luma` suppresses every
20982 // edge that is a TU edge but not a PU edge when
20983 // `curr_skipped = mbmi->skip_txfm && is_inter_block(mbmi)`, so a SKIP
20984 // inter block's internal transform edges are never filtered even though
20985 // `get_transform_size` still reports TX_64X64 for it. The only block that
20986 // reaches here skipped is the 128 root (`read_block_tx_size` hands back
20987 // four TX_64X64 leaves for `side > 64` regardless of `skip`); leaving its
20988 // block-level 128 publication in place is exactly that suppression.
20989 // lane-sb128c r6: narrowed to the 128 root. Below it `read_block_tx_size`
20990 // hands a skipped inter block a single leaf equal to the block, so the
20991 // per-leaf write is the block-level one and this branch is a no-op either
20992 // way; only the 128 root gets four TX_64X64 leaves regardless of `skip`.
20993 let skip_inter_128 = skip && is_inter && write_w.max(write_h) > 64;
20994 if skip_inter_128 {
20995 neighbours.suppress_internal_lf_edges((rmi, cmi), write_w / MI, write_h / MI);
20996 }
20997 if let Some(leaves) = (!skip_inter_128).then_some(()).and(vartx_leaves.as_ref()) {
20998 for &(row, col, tw, th) in leaves {
20999 // lane-r14's RECT leaf dims through lane-golomb r6's luma-only
21000 // writer: fill_lf_grid_rect would recompute CHROMA tx dims from
21001 // the leaf span, but libaom's `get_transform_size` splits only for
21002 // AOM_PLANE_Y (merge J, ledger constraint).
21003 neighbours.fill_lf_grid_leaf_luma(
21004 (at_mi.0 + row, at_mi.1 + col),
21005 tw / MI,
21006 th / MI,
21007 tw as u8,
21008 th as u8,
21009 );
21010 }
21011 }
21012 Ok(())
21013}
21014
21015/// Decodes one 8x8 group that an inter frame's `partition_w8` symbol split
21016/// into four `BLOCK_4X4` inter blocks (lane-intersub8: `PARTITION_SPLIT`
21017/// below 8x8 -- traced live against the oracle `aomdec`'s own `EC_PART_VAL`,
21018/// which reads `bsize=3 value=3` on real inter frames, so the refusal this
21019/// replaces was NOT our own desync).
21020///
21021/// The inter counterpart of [`decode_leaf_split4`], and a `BLOCK_4X4`-only
21022/// cut of [`decode_inter_block8`]: at `min(bw, bh) < 8` libaom switches off
21023/// half the inter syntax, and every one of those is a symbol NOT read here
21024/// (`decodemv.c` / `blockd.h`, oracle tree):
21025/// * `skip_mode`: `read_skip_mode` returns 0 without a symbol when
21026/// `!is_comp_ref_allowed(bsize)` (`AOMMIN(bw, bh) >= 8`, blockd.h).
21027/// * `comp_mode`: `read_block_reference_mode` returns `SINGLE_REFERENCE` on
21028/// the same predicate, so a sub-8x8 block is always single-reference.
21029/// * `interintra`: `is_interintra_allowed_bsize` starts at `BLOCK_8X8`.
21030/// * `motion_mode` / `obmc`: `motion_mode_allowed` returns
21031/// `SIMPLE_TRANSLATION` for `block_size_wide < 8 || block_size_high < 8`,
21032/// and `is_global_mv_block`'s own size term fails, so no warp either.
21033/// * tx size: `block_signals_txsize(bsize)` is `bsize > BLOCK_4X4`
21034/// (blockd.h:1027), so a `BLOCK_4X4` reads neither `tx_depth` nor a
21035/// `txfm_partition` bit even in `TX_MODE_SELECT` -- the transform is
21036/// `max_txsize_rect_lookup[BLOCK_4X4]` = `TX_4X4`
21037/// (`decodeframe.c:1164-1177`).
21038///
21039/// Chroma is coded ONCE for the whole 8x8 group, on the last sub-block
21040/// (`is_chroma_reference`: `(mi_row & 1) && (mi_col & 1)` in 4:2:0), as one
21041/// `TX_4X4` unit per plane -- same rule and same neighbour-context tail as
21042/// [`decode_leaf_split4`]. Its PREDICTION is the sub8x8 one
21043/// (`dec_build_inter_predictors`'s `is_sub8x8` branch, `decodeframe.c`; spec
21044/// 7.11.3.1's `candRow`/`candCol` loop): four 2x2 chroma pieces, each built
21045/// from its own luma sub-block's reference, motion vector and interpolation
21046/// filters, never from the last sub-block's mv alone.
21047#[allow(clippy::too_many_arguments)]
21048fn decode_inter_sub8_split4(
21049 dec: &mut SymbolDecoder,
21050 cdfs: &mut Cdfs,
21051 neighbours: &mut Neighbours,
21052 grid: &mut MiGrid,
21053 group_mi: (usize, usize),
21054 mi_cols: u32,
21055 mi_rows: u32,
21056 y: &mut PlaneBuf,
21057 u: &mut PlaneBuf,
21058 v: &mut PlaneBuf,
21059 ref_y: &PlaneBuf,
21060 ref_u: &PlaneBuf,
21061 ref_v: &PlaneBuf,
21062 other_refs: &RefSlots,
21063 sign_bias_table: &SignBiasTable,
21064 global_motion: &[ec_av1_syntax::WarpParams; 7],
21065 base_q_idx: u8,
21066 scan4: &[u16],
21067 allow_high_precision_mv: bool,
21068 force_integer_mv: bool,
21069 interp_fixed: Option<mc::InterpFilterKind>,
21070 enable_dual_filter: bool,
21071 tpl_frame: Option<&TplFrameArgs>,
21072 reduced_tx_set: bool,
21073 frame_width: usize,
21074) -> Result<()> {
21075 const LAST_FRAME: i8 = 1;
21076 const B4: usize = 4;
21077 SUB8_INTER_SPLIT_HITS.with(|c| c.set(c.get() + 1));
21078 let (gr, gc) = group_mi;
21079 let (gpx, gpy) = (gc * MI, gr * MI);
21080 let (cpx, cpy) = (gpx / 2, gpy / 2);
21081 // Per-sub-block state the group's chroma prediction needs (spec
21082 // 7.11.3.1's candRow/candCol loop reads each sub-block's OWN mv/ref/
21083 // filters), indexed `dr * 2 + dc`.
21084 let mut piece: [Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>; 4] =
21085 [None; 4];
21086 let mut first_tx_type = TxType::DctDct;
21087 let mut last_skip = true;
21088 for i in 0..4usize {
21089 let (dr, dc) = (i / 2, i % 2);
21090 let lmi = (gr + dr, gc + dc);
21091 if lmi.0 >= mi_rows as usize || lmi.1 >= mi_cols as usize {
21092 continue;
21093 }
21094 let (rmi, cmi) = lmi;
21095 let (px, py) = (cmi * MI, rmi * MI);
21096 inter_segment_id(dec, cdfs, rmi, cmi, 1, 1, false, true);
21097 // No `skip_mode` symbol: `is_comp_ref_allowed(BLOCK_4X4)` is false.
21098 let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]);
21099 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
21100 inter_segment_id(dec, cdfs, rmi, cmi, 1, 1, skip, false);
21101 maybe_read_cdef_idx(dec, rmi, cmi, skip);
21102 maybe_read_delta_q(dec, cdfs, rmi, cmi, false, skip);
21103 maybe_read_delta_lf(dec, cdfs, rmi, cmi, false, skip);
21104 let (has_above, has_left) = (
21105 rmi > neighbours.tile_row0_mi,
21106 cmi > neighbours.tile_col0_mi,
21107 );
21108 let ii_ctx = intra_inter_ctx(
21109 has_above,
21110 has_left,
21111 neighbours.above_inter[cmi],
21112 neighbours.left_inter[rmi],
21113 );
21114 let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
21115 if !is_inter {
21116 return Err(unsupported(
21117 "an intra 4x4 block inside an inter frame's sub-8x8 split (this decoder codes \
21118 only inter 4x4 sub-blocks there)",
21119 ));
21120 }
21121 // Same print point as the oracle's `EC_MODE` (entry of
21122 // `read_inter_block_mode_info`, i.e. after skip / is_inter), so the
21123 // two range ladders line up element for element.
21124 if std::env::var_os("EC_TRACE_MODE").is_some() {
21125 eprintln!(
21126 "EC_MODE mi_row={rmi} mi_col={cmi} rng={}",
21127 dec.debug_state().0
21128 );
21129 }
21130 let ref_frame = read_single_ref(
21131 dec,
21132 cdfs,
21133 neighbours.above_ref[cmi],
21134 neighbours.above_ref1[cmi],
21135 neighbours.left_ref[rmi],
21136 neighbours.left_ref1[rmi],
21137 );
21138 let (sref_y, sref_u, sref_v) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?;
21139 if mc::scale_factor(sref_y.width, frame_width) != mc::REF_NO_SCALE {
21140 return Err(unsupported(
21141 "a sub-8x8 inter block under a scaled reference (superres, unimplemented)",
21142 ));
21143 }
21144 let gm_table = build_gm_mv_table(
21145 global_motion,
21146 rmi,
21147 cmi,
21148 1,
21149 1,
21150 allow_high_precision_mv,
21151 force_integer_mv,
21152 );
21153 let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
21154 field: t.field,
21155 cur_offset_0: crate::motion_field::get_relative_dist(
21156 t.order_hint_bits,
21157 t.order_hint,
21158 t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
21159 ),
21160 allow_high_precision_mv,
21161 });
21162 let stack = crate::mvstack::find_mv_stack_with_sign_bias(
21163 grid,
21164 rmi,
21165 cmi,
21166 1,
21167 1,
21168 ref_frame,
21169 mi_cols as usize,
21170 mi_rows as usize,
21171 sign_bias_table,
21172 &gm_table,
21173 tpl,
21174 );
21175 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
21176 let mut is_globalmv = false;
21177 let (mv, is_new_mv) = if !not_new {
21178 let mut idx = 0usize;
21179 while idx < 2 && stack.entries.len() > idx + 1 {
21180 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
21181 break;
21182 }
21183 idx += 1;
21184 }
21185 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
21186 (
21187 read_mv(
21188 dec,
21189 &mut cdfs.mv_comp,
21190 &mut cdfs.mv_joint,
21191 base_mv,
21192 allow_high_precision_mv,
21193 force_integer_mv,
21194 ),
21195 true,
21196 )
21197 } else {
21198 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
21199 is_globalmv = !not_zero;
21200 let mv = if !not_zero {
21201 gm_table[(ref_frame - LAST_FRAME) as usize]
21202 } else {
21203 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
21204 if nearest {
21205 stack.nearest_mv
21206 } else {
21207 let mut idx = 1usize;
21208 while idx < 3 && stack.entries.len() > idx + 1 {
21209 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
21210 break;
21211 }
21212 idx += 1;
21213 }
21214 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
21215 }
21216 };
21217 (mv, false)
21218 };
21219 // Same print point as the oracle's `EC_MODE_MV` (right after
21220 // `assign_mv`), the second rung of the sub-8x8 range ladder.
21221 if std::env::var_os("EC_TRACE_MODE").is_some() {
21222 eprintln!(
21223 "EC_MODE_MV mi_row={rmi} mi_col={cmi} mv0=({},{}) rng={}",
21224 mv.0,
21225 mv.1,
21226 dec.debug_state().0
21227 );
21228 }
21229 // No `interintra` and no `motion_mode`/`obmc` symbol below 8x8 (see
21230 // this function's own doc); `read_mb_interp_filter` still runs.
21231 let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
21232 let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame
21233 || neighbours.above_ref1[cmi] == Some(ref_frame)
21234 {
21235 neighbours.above_filter[cmi]
21236 } else {
21237 [3, 3]
21238 };
21239 let left_filter_ctx = if neighbours.left_ref[rmi] == ref_frame
21240 || neighbours.left_ref1[rmi] == Some(ref_frame)
21241 {
21242 neighbours.left_filter[rmi]
21243 } else {
21244 [3, 3]
21245 };
21246 if std::env::var_os("EC_AV1_IFDBG").is_some() {
21247 eprintln!(
21248 "IFDBG4 mi=({rmi},{cmi}) ref={ref_frame} above_ref={} above_ref1={:?} \
21249 above_filt={:?} left_ref={} left_ref1={:?} left_filt={:?}",
21250 neighbours.above_ref[cmi],
21251 neighbours.above_ref1[cmi],
21252 neighbours.above_filter[cmi],
21253 neighbours.left_ref[rmi],
21254 neighbours.left_ref1[rmi],
21255 neighbours.left_filter[rmi],
21256 );
21257 }
21258 let gm_nontrans = is_globalmv && gm_ref.model != ec_av1_syntax::WarpModel::Translation;
21259 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
21260 dec,
21261 cdfs,
21262 interp_fixed,
21263 enable_dual_filter,
21264 gm_nontrans,
21265 above_filter_ctx,
21266 left_filter_ctx,
21267 false,
21268 );
21269 if std::env::var_os("EC_TRACE_MODE").is_some() {
21270 eprintln!(
21271 "EC_MODE_VAL4 mi_row={rmi} mi_col={cmi} newmv={is_new_mv} globalmv={is_globalmv} \
21272 ref0={ref_frame} mv0=({},{}) stack={} rng={}",
21273 mv.0,
21274 mv.1,
21275 stack.entries.len(),
21276 dec.debug_state().0
21277 );
21278 }
21279 grid.set(
21280 rmi,
21281 cmi,
21282 MiInfo {
21283 is_inter: true,
21284 ref_frame,
21285 ref_frame1: None,
21286 mv1: None,
21287 mv,
21288 is_new_mv,
21289 size: 1,
21290 size_h: 1,
21291 is_global_mv0: false,
21292 is_global_mv1: false,
21293 },
21294 );
21295 piece[i] = Some((ref_frame, mv, h_filter, v_filter));
21296 let mut pred_y = vec![0u16; B4 * B4];
21297 mc::predict_with_filters(
21298 &sref_y.data,
21299 sref_y.width,
21300 sref_y.true_width,
21301 sref_y.true_height,
21302 mv_to_q4(px, mv.1, true),
21303 mv_to_q4(py, mv.0, true),
21304 B4,
21305 B4,
21306 h_filter,
21307 v_filter,
21308 &mut pred_y,
21309 );
21310 // `BLOCK_4X4` never signals a transform size, so the luma unit is the
21311 // whole block and `get_txb_ctx` takes its `plane_bsize ==
21312 // txsize_to_bsize[tx_size]` branch (`txb_skip_ctx = 0`, which
21313 // `read_inter_plane`'s `plane_idx == 0` arm already assumes).
21314 if skip {
21315 y.reconstruct_mc(px, py, B4, &pred_y, &vec![0i32; B4 * B4]);
21316 neighbours.record_mi_luma_rect(lmi, B4, B4, &vec![0i32; B4 * B4]);
21317 } else {
21318 let around = neighbours.around_mi(lmi, B4);
21319 let (luma_grid, tx_type) = read_inter_plane(
21320 dec,
21321 cdfs,
21322 if reduced_tx_set {
21323 TxbSet::Luma4Inter
21324 } else {
21325 TxbSet::Luma4InterSet1
21326 },
21327 scan4,
21328 0,
21329 around[0],
21330 0,
21331 y,
21332 px,
21333 py,
21334 B4,
21335 base_q_idx,
21336 &pred_y,
21337 None,
21338 None,
21339 )?;
21340 if i == 0 {
21341 // `av1_get_tx_type`: an inter block's chroma inherits the
21342 // tx_type of the CO-LOCATED luma position, which for the
21343 // group's one chroma unit is luma (0, 0) -- the FIRST
21344 // sub-block, not the last.
21345 first_tx_type = tx_type;
21346 }
21347 neighbours.record_mi_luma_rect(lmi, B4, B4, &luma_grid);
21348 }
21349 neighbours.record_mode_mi(rmi, cmi, 1, 1, DC_PRED);
21350 neighbours.record_inter_rect_mi(lmi, 1, 1, skip, true, ref_frame, resolved_filter, false);
21351 neighbours.fill_skip_grid_rect(lmi, 1, 1, skip);
21352 neighbours.fill_lf_grid_rect(lmi, 1, 1, B4 as u8, B4 as u8, ref_frame.max(LAST_FRAME));
21353 last_skip = skip;
21354 }
21355 // Chroma, once for the whole group, on the last sub-block's own `skip`
21356 // flag -- prediction from all four sub-blocks (2x2 pieces), residual as
21357 // one TX_4X4 unit per plane.
21358 let mut pred_u = vec![0u16; B4 * B4];
21359 let mut pred_v = vec![0u16; B4 * B4];
21360 for i in 0..4usize {
21361 let (dr, dc) = (i / 2, i % 2);
21362 let Some((ref_frame, mv, h_filter, v_filter)) = piece[i] else {
21363 continue;
21364 };
21365 let (_, sref_u, sref_v) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?;
21366 let (ox, oy) = (cpx + dc * 2, cpy + dr * 2);
21367 for (plane, dst) in [(sref_u, &mut pred_u), (sref_v, &mut pred_v)] {
21368 let mut buf = vec![0u16; 4];
21369 mc::predict_with_filters(
21370 &plane.data,
21371 plane.width,
21372 plane.true_width,
21373 plane.true_height,
21374 mv_to_q4(ox, mv.1, false),
21375 mv_to_q4(oy, mv.0, false),
21376 2,
21377 2,
21378 h_filter,
21379 v_filter,
21380 &mut buf,
21381 );
21382 for row in 0..2 {
21383 for col in 0..2 {
21384 dst[(dr * 2 + row) * B4 + dc * 2 + col] = buf[row * 2 + col];
21385 }
21386 }
21387 }
21388 }
21389 let (u_grid, v_grid) = if last_skip {
21390 u.reconstruct_mc(cpx, cpy, B4, &pred_u, &vec![0i32; B4 * B4]);
21391 v.reconstruct_mc(cpx, cpy, B4, &pred_v, &vec![0i32; B4 * B4]);
21392 (vec![0i32; B4 * B4], vec![0i32; B4 * B4])
21393 } else {
21394 let around = neighbours.around_mi(group_mi, 8);
21395 let ug = read_inter_plane(
21396 dec, cdfs, TxbSet::Chroma4, scan4, 1, around[1], 0, u, cpx, cpy, B4, base_q_idx,
21397 &pred_u, Some(first_tx_type), None,
21398 )?
21399 .0;
21400 let vg = read_inter_plane(
21401 dec, cdfs, TxbSet::Chroma4, scan4, 2, around[2], 0, v, cpx, cpy, B4, base_q_idx,
21402 &pred_v, Some(first_tx_type), None,
21403 )?
21404 .0;
21405 (ug, vg)
21406 };
21407 neighbours.record_uv_mode_mi(gr, gc, 2, 2, DC_PRED);
21408 // Same two neighbour tails [`decode_leaf_split4`] runs: the partition
21409 // context of a `BLOCK_4X4` subsize (`partition_context_lookup` bit 0 = 1,
21410 // reached by `side_mi = 4` here) and the group's chroma coefficient state.
21411 for cell in 0..2usize {
21412 neighbours.left_side_mi[gr + cell] = 4;
21413 neighbours.above_side_mi[gc + cell] = 4;
21414 }
21415 let round_up_even = |n: usize| n.div_ceil(2) * 2;
21416 let bound_h = round_up_even(neighbours.mi_rows);
21417 let bound_w = round_up_even(neighbours.mi_cols);
21418 let u_state = neighbour_state(&u_grid);
21419 let v_state = neighbour_state(&v_grid);
21420 for cell in 0..2usize {
21421 if cell < 2usize.min(bound_h.saturating_sub(gr)) {
21422 neighbours.left[gr + cell][1] = u_state;
21423 neighbours.left[gr + cell][2] = v_state;
21424 }
21425 if cell < 2usize.min(bound_w.saturating_sub(gc)) {
21426 neighbours.above[gc + cell][1] = u_state;
21427 neighbours.above[gc + cell][2] = v_state;
21428 }
21429 }
21430 Ok(())
21431}
21432
21433/// Decodes a `PARTITION_HORZ`/`PARTITION_VERT` of one 8x8 INTER block into two
21434/// `BLOCK_8X4`/`BLOCK_4X8` inter leaves (lane-intersub8 r3) -- the inter twin of
21435/// [`decode_leaf_rect8`] and the rectangular sibling of
21436/// [`decode_inter_sub8_split4`], whose element order it follows exactly.
21437/// Per sub-block, in libaom `decodemv.c` `read_inter_frame_mode_info` order:
21438///
21439/// * `segment_id`, `skip`, `cdef`/`delta_q`/`delta_lf`, `intra_inter`;
21440/// * NO `skip_mode` symbol: `is_comp_ref_allowed(BLOCK_8X4)` is false
21441/// (`av1_is_comp_ref_allowed` needs both sides >= 8), so
21442/// `read_skip_mode` returns 0 without reading and `comp_mode` is never read
21443/// either (`read_ref_frames`' `is_comp_ref_allowed` guard) -- single
21444/// reference only;
21445/// * NO `interintra` and NO `motion_mode`/OBMC/warp symbol: every one of those
21446/// gates needs `block_size_wide >= 8 && block_size_high >= 8`
21447/// (`is_interintra_allowed_bsize`, `motion_mode_allowed`), and one side is 4;
21448/// * `read_mb_interp_filter` DOES run for both sub-blocks.
21449///
21450/// The shape's own differences from the four-way split:
21451///
21452/// * `block_signals_txsize(BLOCK_8X4)` is true (`bsize > BLOCK_4X4`,
21453/// blockd.h:1027), so a non-skipped sub-block reads ONE `txfm_partition`
21454/// symbol under `TX_MODE_SELECT` at `max_txsize_rect_lookup[BLOCK_8X4] ==
21455/// TX_8X4` ([`read_var_tx_size`]); split resolves to two `TX_4X4` units
21456/// (`sub_tx_size_map[TX_8X4] == TX_4X4`, libaom's early return), no split to
21457/// the whole-leaf `TX_8X4`;
21458/// * the luma coefficient set is [`TxbSet::LumaRect8x4Inter`] (the 8x8
21459/// coefficient class with a 32-position `eob_pt` and the INTER `TX_4X4`
21460/// `tx_type` row) for the whole-leaf unit, and the square
21461/// [`TxbSet::Luma4Inter`] for a split `TX_4X4` unit;
21462/// * chroma is coded ONCE, on the sub-block that is the chroma reference:
21463/// `is_chroma_reference` (`av1_common_int.h`) is
21464/// `((mi_row & 1) || !(bh4 & 1) || !ss_y) && ((mi_col & 1) || !(bw4 & 1) ||
21465/// !ss_x)`, i.e. under 4:2:0 the BOTTOM 8x4 (`bh4 == 1`, odd) and the RIGHT
21466/// 4x8 (`bw4 == 1`) -- always the second sub-block here;
21467/// * that chroma unit's prediction is the sub8x8 one (`reconinter.c`
21468/// `build_inter_predictors_sub8x8`: `row_start = -(block_size_high == 4 &&
21469/// ss_y)`, `col_start = -(block_size_wide == 4 && ss_x)`), two 4x2 (HORZ) or
21470/// 2x4 (VERT) chroma pieces, each from its OWN sub-block's reference, mv and
21471/// interpolation filters.
21472#[allow(clippy::too_many_arguments)]
21473fn decode_inter_sub8_rect2(
21474 dec: &mut SymbolDecoder,
21475 cdfs: &mut Cdfs,
21476 neighbours: &mut Neighbours,
21477 grid: &mut MiGrid,
21478 group_mi: (usize, usize),
21479 vert: bool,
21480 mi_cols: u32,
21481 mi_rows: u32,
21482 y: &mut PlaneBuf,
21483 u: &mut PlaneBuf,
21484 v: &mut PlaneBuf,
21485 ref_y: &PlaneBuf,
21486 ref_u: &PlaneBuf,
21487 ref_v: &PlaneBuf,
21488 other_refs: &RefSlots,
21489 sign_bias_table: &SignBiasTable,
21490 global_motion: &[ec_av1_syntax::WarpParams; 7],
21491 base_q_idx: u8,
21492 scan4: &[u16],
21493 allow_high_precision_mv: bool,
21494 force_integer_mv: bool,
21495 interp_fixed: Option<mc::InterpFilterKind>,
21496 enable_dual_filter: bool,
21497 tpl_frame: Option<&TplFrameArgs>,
21498 reduced_tx_set: bool,
21499 frame_width: usize,
21500) -> Result<()> {
21501 const LAST_FRAME: i8 = 1;
21502 // The 8x8 group's own square stride: both leaves' prediction buffers are
21503 // laid out at it, as every other rect inter unit here is.
21504 const SIDE: usize = 8;
21505 let (bw, bh) = if vert { (4usize, 8usize) } else { (8usize, 4usize) };
21506 let (w_mi, h_mi) = (bw / MI, bh / MI);
21507 SUB8_INTER_RECT_HITS.with(|c| {
21508 let mut h = c.get();
21509 h[usize::from(vert)] += 1;
21510 c.set(h);
21511 });
21512 let (gr, gc) = group_mi;
21513 let (gpx, gpy) = (gc * MI, gr * MI);
21514 let (cpx, cpy) = (gpx / 2, gpy / 2);
21515 // Per-sub-block state the group's one chroma unit predicts from.
21516 let mut piece: [Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>; 2] =
21517 [None; 2];
21518 let mut first_tx_type = TxType::DctDct;
21519 let mut last_skip = true;
21520 for i in 0..2usize {
21521 let lmi = if vert { (gr, gc + i) } else { (gr + i, gc) };
21522 if lmi.0 >= mi_rows as usize || lmi.1 >= mi_cols as usize {
21523 continue;
21524 }
21525 let (rmi, cmi) = lmi;
21526 let (px, py) = (cmi * MI, rmi * MI);
21527 inter_segment_id(dec, cdfs, rmi, cmi, w_mi, h_mi, false, true);
21528 let skip_ctx =
21529 usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]);
21530 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
21531 inter_segment_id(dec, cdfs, rmi, cmi, w_mi, h_mi, skip, false);
21532 maybe_read_cdef_idx(dec, rmi, cmi, skip);
21533 maybe_read_delta_q(dec, cdfs, rmi, cmi, false, skip);
21534 maybe_read_delta_lf(dec, cdfs, rmi, cmi, false, skip);
21535 let (has_above, has_left) = (
21536 rmi > neighbours.tile_row0_mi,
21537 cmi > neighbours.tile_col0_mi,
21538 );
21539 let ii_ctx = intra_inter_ctx(
21540 has_above,
21541 has_left,
21542 neighbours.above_inter[cmi],
21543 neighbours.left_inter[rmi],
21544 );
21545 let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
21546 if !is_inter {
21547 return Err(unsupported(
21548 "an intra 8x4/4x8 block inside an inter frame's sub-8x8 HORZ/VERT partition \
21549 (this decoder codes only inter sub-blocks there)",
21550 ));
21551 }
21552 if std::env::var_os("EC_TRACE_MODE").is_some() {
21553 eprintln!(
21554 "EC_MODE mi_row={rmi} mi_col={cmi} rng={}",
21555 dec.debug_state().0
21556 );
21557 }
21558 let ref_frame = read_single_ref(
21559 dec,
21560 cdfs,
21561 neighbours.above_ref[cmi],
21562 neighbours.above_ref1[cmi],
21563 neighbours.left_ref[rmi],
21564 neighbours.left_ref1[rmi],
21565 );
21566 let (sref_y, _, _) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?;
21567 if mc::scale_factor(sref_y.width, frame_width) != mc::REF_NO_SCALE {
21568 return Err(unsupported(
21569 "a sub-8x8 inter block under a scaled reference (superres, unimplemented)",
21570 ));
21571 }
21572 let gm_table = build_gm_mv_table(
21573 global_motion,
21574 rmi,
21575 cmi,
21576 w_mi,
21577 h_mi,
21578 allow_high_precision_mv,
21579 force_integer_mv,
21580 );
21581 let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
21582 field: t.field,
21583 cur_offset_0: crate::motion_field::get_relative_dist(
21584 t.order_hint_bits,
21585 t.order_hint,
21586 t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
21587 ),
21588 allow_high_precision_mv,
21589 });
21590 let stack = crate::mvstack::find_mv_stack_with_sign_bias(
21591 grid,
21592 rmi,
21593 cmi,
21594 w_mi,
21595 h_mi,
21596 ref_frame,
21597 mi_cols as usize,
21598 mi_rows as usize,
21599 sign_bias_table,
21600 &gm_table,
21601 tpl,
21602 );
21603 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
21604 let mut is_globalmv = false;
21605 let (mv, is_new_mv) = if !not_new {
21606 let mut idx = 0usize;
21607 while idx < 2 && stack.entries.len() > idx + 1 {
21608 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
21609 break;
21610 }
21611 idx += 1;
21612 }
21613 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
21614 (
21615 read_mv(
21616 dec,
21617 &mut cdfs.mv_comp,
21618 &mut cdfs.mv_joint,
21619 base_mv,
21620 allow_high_precision_mv,
21621 force_integer_mv,
21622 ),
21623 true,
21624 )
21625 } else {
21626 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
21627 is_globalmv = !not_zero;
21628 let mv = if !not_zero {
21629 gm_table[(ref_frame - LAST_FRAME) as usize]
21630 } else {
21631 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
21632 if nearest {
21633 stack.nearest_mv
21634 } else {
21635 let mut idx = 1usize;
21636 while idx < 3 && stack.entries.len() > idx + 1 {
21637 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
21638 break;
21639 }
21640 idx += 1;
21641 }
21642 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
21643 }
21644 };
21645 (mv, false)
21646 };
21647 if std::env::var_os("EC_TRACE_MODE").is_some() {
21648 eprintln!(
21649 "EC_MODE_MV mi_row={rmi} mi_col={cmi} mv0=({},{}) rng={}",
21650 mv.0,
21651 mv.1,
21652 dec.debug_state().0
21653 );
21654 }
21655 let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
21656 let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame
21657 || neighbours.above_ref1[cmi] == Some(ref_frame)
21658 {
21659 neighbours.above_filter[cmi]
21660 } else {
21661 [3, 3]
21662 };
21663 let left_filter_ctx = if neighbours.left_ref[rmi] == ref_frame
21664 || neighbours.left_ref1[rmi] == Some(ref_frame)
21665 {
21666 neighbours.left_filter[rmi]
21667 } else {
21668 [3, 3]
21669 };
21670 let gm_nontrans = is_globalmv && gm_ref.model != ec_av1_syntax::WarpModel::Translation;
21671 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
21672 dec,
21673 cdfs,
21674 interp_fixed,
21675 enable_dual_filter,
21676 gm_nontrans,
21677 above_filter_ctx,
21678 left_filter_ctx,
21679 false,
21680 );
21681 // `read_block_tx_size` (libaom `decodeframe.c`): unlike a `BLOCK_4X4`,
21682 // this shape signals its transform size. A non-skipped inter block
21683 // walks the var-tx tree from `max_txsize_rect_lookup[BLOCK_8X4]`; a
21684 // skipped one codes nothing and records its BLOCK size in both txfm
21685 // contexts (`set_txfm_ctxs`' `skip_inter` arm).
21686 let mut leaves: Vec<(usize, usize, usize, usize)> = Vec::new();
21687 if TX_SELECT_INTER.with(std::cell::Cell::get) && !skip {
21688 let max_w_mi = w_mi.min((mi_cols as usize).saturating_sub(cmi));
21689 let max_h_mi = h_mi.min((mi_rows as usize).saturating_sub(rmi));
21690 read_var_tx_size(
21691 dec,
21692 cdfs,
21693 neighbours,
21694 lmi,
21695 SIDE,
21696 (max_w_mi, max_h_mi),
21697 (bw, bh),
21698 0,
21699 0,
21700 0,
21701 &mut leaves,
21702 );
21703 } else {
21704 leaves.push((0, 0, bw, bh));
21705 set_txfm_ctxs(neighbours, lmi, bw.max(bh), w_mi, h_mi, skip);
21706 }
21707 if std::env::var_os("EC_TRACE_MODE").is_some() {
21708 eprintln!(
21709 "EC_MODE_VALR mi_row={rmi} mi_col={cmi} newmv={is_new_mv} globalmv={is_globalmv} \
21710 ref0={ref_frame} mv0=({},{}) stack={} leaves={} rng={}",
21711 mv.0,
21712 mv.1,
21713 stack.entries.len(),
21714 leaves.len(),
21715 dec.debug_state().0
21716 );
21717 }
21718 grid_stamp_rect(grid, rmi, cmi, w_mi, h_mi, ref_frame, mv, is_new_mv);
21719 piece[i] = Some((ref_frame, mv, h_filter, v_filter));
21720 // Prediction over the leaf's true footprint, laid out at the group's
21721 // square stride (what `reconstruct_mc_rect` and `read_inter_plane_rect`
21722 // index with).
21723 let mut pred_y = vec![0u16; SIDE * SIDE];
21724 {
21725 let mut dense = vec![0u16; bw * bh];
21726 mc::predict_with_filters(
21727 &sref_y.data,
21728 sref_y.width,
21729 sref_y.true_width,
21730 sref_y.true_height,
21731 mv_to_q4(px, mv.1, true),
21732 mv_to_q4(py, mv.0, true),
21733 bw,
21734 bh,
21735 h_filter,
21736 v_filter,
21737 &mut dense,
21738 );
21739 for row in 0..bh {
21740 pred_y[row * SIDE..][..bw].copy_from_slice(&dense[row * bw..][..bw]);
21741 }
21742 }
21743 if skip {
21744 y.reconstruct_mc_rect(px, py, SIDE, bw, bh, &pred_y, &vec![0i32; SIDE * SIDE]);
21745 neighbours.record_mi_luma_rect(lmi, bw, bh, &vec![0i32; bw * bh]);
21746 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, bw as u8, bh as u8, ref_frame.max(LAST_FRAME));
21747 } else {
21748 let (mut last_tw, mut last_th) = (bw, bh);
21749 for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() {
21750 let tu_mi = (rmi + row, cmi + col);
21751 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
21752 let (tu_grid, tu_tx_type) = if tw == th {
21753 // A split `TX_4X4` unit: square reader, its own
21754 // `get_txb_ctx_general` neighbour context (the unit is
21755 // smaller than its plane block, so the lone-TU 0 does not
21756 // apply).
21757 let mut tu_pred = Vec::with_capacity(tw * th);
21758 for rr in 0..th {
21759 let start = (row * MI + rr) * SIDE + col * MI;
21760 tu_pred.extend_from_slice(&pred_y[start..start + tw]);
21761 }
21762 let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI);
21763 read_inter_plane(
21764 dec,
21765 cdfs,
21766 if reduced_tx_set {
21767 TxbSet::Luma4Inter
21768 } else {
21769 TxbSet::Luma4InterSet1
21770 },
21771 scan4,
21772 0,
21773 neighbours.around_mi(tu_mi, tw)[0],
21774 0,
21775 y,
21776 tu_px,
21777 tu_py,
21778 tw,
21779 base_q_idx,
21780 &tu_pred,
21781 None,
21782 Some(tu_skip_ctx),
21783 )?
21784 } else {
21785 // The whole leaf as one `TX_8X4`/`TX_4X8` unit: it IS the
21786 // plane block, so `get_txb_ctx_general` fixes `txb_skip_ctx`
21787 // at 0 (`luma_skip_ctx: None`).
21788 let start = row * MI * SIDE + col * MI;
21789 read_inter_plane_rect(
21790 dec,
21791 cdfs,
21792 if reduced_tx_set {
21793 TxbSet::LumaRect8x4Inter
21794 } else {
21795 TxbSet::LumaRect8x4InterSet1
21796 },
21797 (tw, th),
21798 SIDE,
21799 0,
21800 neighbours.around_mi_rect(tu_mi, tw, th)[0],
21801 0,
21802 y,
21803 tu_px,
21804 tu_py,
21805 &pred_y[start..],
21806 None,
21807 None,
21808 )?
21809 };
21810 if idx == 0 {
21811 // `av1_get_tx_type`: the group's one chroma unit scales
21812 // back to luma (0, 0), i.e. the FIRST sub-block's first
21813 // transform unit.
21814 first_tx_type = tu_tx_type;
21815 }
21816 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
21817 (last_tw, last_th) = (tw, th);
21818 }
21819 neighbours.fill_lf_grid_rect(
21820 lmi,
21821 w_mi,
21822 h_mi,
21823 last_tw as u8,
21824 last_th as u8,
21825 ref_frame.max(LAST_FRAME),
21826 );
21827 }
21828 neighbours.record_mode_mi(rmi, cmi, w_mi, h_mi, DC_PRED);
21829 neighbours.record_inter_rect_mi(lmi, w_mi, h_mi, skip, true, ref_frame, resolved_filter, false);
21830 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
21831 last_skip = skip;
21832 }
21833 // The group's single 4x4 chroma unit per plane, on the chroma-reference
21834 // (second) sub-block's own skip flag.
21835 const B4: usize = 4;
21836 let mut pred_u = vec![0u16; B4 * B4];
21837 let mut pred_v = vec![0u16; B4 * B4];
21838 let (piece_w, piece_h) = if vert { (2usize, 4usize) } else { (4usize, 2usize) };
21839 for i in 0..2usize {
21840 let Some((ref_frame, mv, h_filter, v_filter)) = piece[i] else {
21841 continue;
21842 };
21843 let (_, sref_u, sref_v) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?;
21844 let (ox, oy) = if vert {
21845 (cpx + i * piece_w, cpy)
21846 } else {
21847 (cpx, cpy + i * piece_h)
21848 };
21849 let (dc, dr) = if vert { (i * piece_w, 0) } else { (0, i * piece_h) };
21850 for (plane, dst) in [(sref_u, &mut pred_u), (sref_v, &mut pred_v)] {
21851 let mut buf = vec![0u16; piece_w * piece_h];
21852 mc::predict_with_filters(
21853 &plane.data,
21854 plane.width,
21855 plane.true_width,
21856 plane.true_height,
21857 mv_to_q4(ox, mv.1, false),
21858 mv_to_q4(oy, mv.0, false),
21859 piece_w,
21860 piece_h,
21861 h_filter,
21862 v_filter,
21863 &mut buf,
21864 );
21865 for row in 0..piece_h {
21866 for col in 0..piece_w {
21867 dst[(dr + row) * B4 + dc + col] = buf[row * piece_w + col];
21868 }
21869 }
21870 }
21871 }
21872 let (u_grid, v_grid) = if last_skip {
21873 u.reconstruct_mc(cpx, cpy, B4, &pred_u, &vec![0i32; B4 * B4]);
21874 v.reconstruct_mc(cpx, cpy, B4, &pred_v, &vec![0i32; B4 * B4]);
21875 (vec![0i32; B4 * B4], vec![0i32; B4 * B4])
21876 } else {
21877 let around = neighbours.around_mi(group_mi, 8);
21878 let ug = read_inter_plane(
21879 dec, cdfs, TxbSet::Chroma4, scan4, 1, around[1], 0, u, cpx, cpy, B4, base_q_idx,
21880 &pred_u, Some(first_tx_type), None,
21881 )?
21882 .0;
21883 let vg = read_inter_plane(
21884 dec, cdfs, TxbSet::Chroma4, scan4, 2, around[2], 0, v, cpx, cpy, B4, base_q_idx,
21885 &pred_v, Some(first_tx_type), None,
21886 )?
21887 .0;
21888 (ug, vg)
21889 };
21890 neighbours.record_uv_mode_mi(gr, gc, 2, 2, DC_PRED);
21891 // `update_partition_context` writes `partition_context_lookup[subsize]`
21892 // over the whole 8x8 span -- BLOCK_4X8's width above and height left, the
21893 // same values [`decode_leaf_rect8`] writes for the intra shape.
21894 for cell in 0..2usize {
21895 neighbours.above_side_mi[gc + cell] = bw;
21896 neighbours.left_side_mi[gr + cell] = bh;
21897 }
21898 let round_up_even = |n: usize| n.div_ceil(2) * 2;
21899 let bound_h = round_up_even(neighbours.mi_rows);
21900 let bound_w = round_up_even(neighbours.mi_cols);
21901 let u_state = neighbour_state(&u_grid);
21902 let v_state = neighbour_state(&v_grid);
21903 for cell in 0..2usize {
21904 if cell < 2usize.min(bound_h.saturating_sub(gr)) {
21905 neighbours.left[gr + cell][1] = u_state;
21906 neighbours.left[gr + cell][2] = v_state;
21907 }
21908 if cell < 2usize.min(bound_w.saturating_sub(gc)) {
21909 neighbours.above[gc + cell][1] = u_state;
21910 neighbours.above[gc + cell][2] = v_state;
21911 }
21912 }
21913 Ok(())
21914}
21915
21916/// Stamps one sub-8x8 inter leaf into every mi cell of its true `w_mi`x`h_mi`
21917/// footprint (class: a rect block's grid span is its own, never a square guess).
21918fn grid_stamp_rect(
21919 grid: &mut MiGrid,
21920 mi_row: usize,
21921 mi_col: usize,
21922 w_mi: usize,
21923 h_mi: usize,
21924 ref_frame: i8,
21925 mv: (i32, i32),
21926 is_new_mv: bool,
21927) {
21928 for dr in 0..h_mi {
21929 for dc in 0..w_mi {
21930 grid.set(
21931 mi_row + dr,
21932 mi_col + dc,
21933 MiInfo {
21934 is_inter: true,
21935 ref_frame,
21936 ref_frame1: None,
21937 mv1: None,
21938 mv,
21939 is_new_mv,
21940 size: w_mi,
21941 size_h: h_mi,
21942 is_global_mv0: false,
21943 is_global_mv1: false,
21944 },
21945 );
21946 }
21947 }
21948}
21949
21950/// Decodes one 8x8 leaf of a straddling 16x16 inter-frame block
21951/// (lane-av1inter8), mirroring [`crate::tile::write_inter_frame_leaf8`]'s
21952/// exact symbol order: its own skip flag, intra/inter choice and (when
21953/// inter) `NEARESTMV`/`NEWMV` chain against this leaf's own 2x2-mi mv-stack
21954/// window, or (when intra) `Y_MODE`, then its own luma and two chroma
21955/// transform blocks through [`TxbSet::Luma8Inter`]/[`TxbSet::Chroma4`],
21956/// same as [`decode_leaf8`]'s coefficient layer but with
21957/// motion-compensated prediction instead of intra prediction when inter.
21958/// `outer_at` (in [`SUB`]-grid units) is the enclosing 16x16 slot's
21959/// skip/intra-inter context, overridden by `prev_leaf` exactly as
21960/// [`decode_leaf8`] overrides mode context: `Neighbours`' above/left arrays
21961/// only resolve to [`SUB`] granularity. Hands back this leaf's own skip flag
21962/// and intra/inter choice, for the next leaf or the caller's final
21963/// write-back.
21964#[allow(clippy::too_many_arguments)]
21965fn decode_inter_block8(
21966 dec: &mut SymbolDecoder,
21967 cdfs: &mut Cdfs,
21968 neighbours: &mut Neighbours,
21969 grid: &mut MiGrid,
21970 mi_cols: u32,
21971 mi_rows: u32,
21972 outer_at: (usize, usize),
21973 leaf_mi: (usize, usize),
21974 y: &mut PlaneBuf,
21975 u: &mut PlaneBuf,
21976 v: &mut PlaneBuf,
21977 ref_y: &PlaneBuf,
21978 ref_u: &PlaneBuf,
21979 ref_v: &PlaneBuf,
21980 other_refs: &RefSlots,
21981 base_q_idx: u8,
21982 scan8: &[u16],
21983 scan4: &[u16],
21984 allow_high_precision_mv: bool,
21985 force_integer_mv: bool,
21986 // lane-gmaffine r1: this frame header's own `global_motion` table (spec
21987 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` -- same table
21988 // [`decode_inter_block`] takes, threaded here so the 8x8 leaf can code
21989 // `GLOBALMV` (`gm_get_motion_vector`), fill its mv stack's missing
21990 // candidates with the gm mv (gm r6's root cause) and build a global
21991 // warp prediction.
21992 global_motion: &[ec_av1_syntax::WarpParams; 7],
21993 // lane-gmaffine r1: this sequence header's own `enable_dual_filter` bit,
21994 // for the leaf's own `read_mb_interp_filter` below.
21995 enable_dual_filter: bool,
21996 // lane-av1comp: see [`decode_inter_block`]'s own doc -- this leaf path
21997 // only ever tracks a coarse `LAST_FRAME`-or-intra neighbour shape (no
21998 // per-leaf `above_ref`/`left_ref` array exists here), so `comp_mode`'s
21999 // context uses that same approximation.
22000 reference_select: bool,
22001 enable_masked_compound: bool,
22002 // lane-sb128 r4: see [`decode_inter_block`]'s own doc -- `BLOCK_8X8` is
22003 // always `is_interintra_allowed_bsize`-eligible, so this leaf's own gate
22004 // drops the `side` check entirely.
22005 enable_interintra_compound: bool,
22006 enable_jnt_comp: bool,
22007 order_hint_bits: u32,
22008 order_hint: u32,
22009 ref_order_hints: [u32; 7],
22010 // lane-av1comp round 14: see [`decode_inter_block`]'s own doc -- this
22011 // leaf has no per-leaf `above_skip_mode`/`left_skip_mode` array either,
22012 // so its `skip_mode` context reuses the same [`SUB`]-grid
22013 // `above_skip_mode[cmi]`/`left_skip_mode[rmi]` the enclosing 16x16 slot
22014 // tracks (mirroring `above_skip`/`left_skip`'s own leaf approximation
22015 // just above).
22016 skip_mode_present: bool,
22017 skip_mode_frame: [u8; 2],
22018 // lane-cdffwd2: this frame header's own `reduced_tx_set` bit -- see
22019 // [`decode_inter_frame_tile_with_cdfs`]'s own doc.
22020 reduced_tx_set: bool,
22021 // lane-motionmode round 3: this frame header's own `is_motion_mode_switchable`/
22022 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`), plus
22023 // the fixed/switchable interp filter kind `obmc_blend`'s own neighbour
22024 // reads need (see [`decode_inter_block`]'s own doc) -- this leaf's own
22025 // prediction is always `Regular` (documented corner-cut, `mc::predict`
22026 // has no filter param), but an OBMC neighbour can be a real 16x16+
22027 // block that DID resolve a switchable filter.
22028 interp_fixed: Option<mc::InterpFilterKind>,
22029 switchable_motion_mode: bool,
22030 allow_warped_motion: bool,
22031 // lane-av1comp: `Some((ref1, comp_group_idx, compound_idx))` only for a
22032 // real `COMPOUND_REFERENCE` leaf, for the caller's own end-of-16x16
22033 // `record_compound_ctx` call -- mirrors [`decode_inter_block`]'s own
22034 // `compound_ctx` local, just handed back instead of applied here (this
22035 // fn's `neighbours` recording happens once for the whole straddling
22036 // 16x16 block, after every leaf).
22037 // lane-screen r2: see [`decode_inter_block`]'s own copy of this param --
22038 // `BLOCK_8X8` (this leaf's fixed size) is always `av1_allow_palette`-
22039 // eligible (`bsize >= BLOCK_8X8`).
22040 allow_screen_content_tools: bool,
22041 // lane-inter8 r1: the leaf's mv stacks used to be built without the
22042 // frame's sign-bias table (`NO_SIGN_BIAS`), while [`decode_inter_block`]
22043 // one level up passed it -- it changes the candidate list and with it
22044 // `new_mv_ctx`/`ref_mv_ctx`, `drl_ctx` and the number of symbols read.
22045 // Measured: an 8x8 compound NEAR_NEWMV leaf desynced against aomdec's
22046 // EC_MODE ladder at exactly this block (mi 4,14 of the mandelbrot
22047 // 8x8-split gate).
22048 sign_bias_table: &SignBiasTable,
22049 // lane-inter8 r2: the frame's temporal mv field (spec 7.10.2.8), which
22050 // [`decode_inter_block`] one level up has always passed and this leaf
22051 // passed `None` for -- a `use_ref_frame_mvs` frame's stack then holds
22052 // fewer candidates here than in the reference decoder, which changes the
22053 // mode contexts AND the number of `drl_mode` bits read (class parsed
22054 // then discarded).
22055 tpl_frame: Option<&TplFrameArgs>,
22056 // lane-scaledref r1: this frame's own coded luma width (spec 7.11.3.3),
22057 // for the scaled-reference MC this leaf's own single-ref/compound/OBMC
22058 // predictions take when a stored reference was coded at another width
22059 // (`use_superres`) -- mirrors [`decode_inter_block`]'s own param.
22060 frame_width: usize,
22061) -> Result<(bool, bool, bool, Option<(i8, i8, u8, u8)>, [u8; 2], (i8, Option<i8>))> {
22062 const LAST_FRAME: i8 = 1;
22063 // lane-gmaffine r2: the leaf's OWN switchable-filter symbols, handed back
22064 // so the caller stamps them into `Neighbours` instead of the `[3, 3]`
22065 // placeholder. `[3, 3]` is the "intra neighbour, no filter" sentinel: an
22066 // OBMC blend that picks such a neighbour up feeds it to
22067 // `neighbour_filter`, which PANICS on it (`from_switchable_symbol`) --
22068 // that was the warp gate's crash, not an entropy desync. Stays `[3, 3]`
22069 // on the intra and compound paths.
22070 let mut leaf_filter_syms = [3u8; 2];
22071 // lane-gmaffine r1: this leaf's GLOBALMV vector AND the mv stack's
22072 // missing-candidate fallback both come from the frame's global motion
22073 // evaluated at THIS block's centre (gm r6's root cause).
22074 let gm_table = build_gm_mv_table(
22075 global_motion,
22076 leaf_mi.0,
22077 leaf_mi.1,
22078 2,
22079 2,
22080 allow_high_precision_mv,
22081 force_integer_mv,
22082 );
22083 /// `Y_MODE`'s size group (`common_data.h`'s `size_group_lookup[BLOCK_8X8]`).
22084 const SIZE_GROUP_8: usize = 1;
22085
22086 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
22087 let (cpx, cpy) = (px / 2, py / 2);
22088 // lane-txselect: whether this leaf's `TxMode::Select` var-tx tree took
22089 // the one split a `BLOCK_8X8` can take (`read_block_tx_size` below) --
22090 // read back by the luma residual read and the tail's neighbour/loop-filter
22091 // bookkeeping. Always `false` outside a `TxMode::Select` inter frame.
22092 let mut split8 = false;
22093 const SIDE: usize = 8;
22094 const CHROMA_SIDE: usize = 4;
22095
22096 let (r, c) = outer_at;
22097 // lane-inter8 r2: this leaf's OWN mi cell, not the enclosing 16x16's --
22098 // leaf (mi_r, mi_c + 2)'s left neighbour is leaf (mi_r, mi_c), and the
22099 // left column of a 16x16's second leaf ROW is the previous 16x16 block's
22100 // bottom leaf, neither of which a SUB-grid slot can name.
22101 let (rmi, cmi) = leaf_mi;
22102 // lane-inter8 r2: no sibling-leaf override any more -- each leaf stamps
22103 // its own 2x2-mi span into the bands right after it decodes (the caller's
22104 // `record_inter_rect_mi`), so a plain mi read already names the correct
22105 // neighbour, including one belonging to the previous 16x16 block.
22106 let above_skip = neighbours.above_skip[cmi];
22107 let left_skip = neighbours.left_skip[rmi];
22108 let above_inter = neighbours.above_inter[cmi];
22109 let left_inter = neighbours.left_inter[rmi];
22110 let above_ref0 = neighbours.above_ref[cmi];
22111 let above_ref1 = neighbours.above_ref1[cmi];
22112 let left_ref0 = neighbours.left_ref[rmi];
22113 let left_ref1 = neighbours.left_ref1[rmi];
22114 let skip_mode_ctx =
22115 usize::from(neighbours.above_skip_mode[cmi]) + usize::from(neighbours.left_skip_mode[rmi]);
22116 // Same two `inter_segment_id` positions as [`decode_inter_block`]; this
22117 // leaf is always `BLOCK_8X8`, i.e. 2x2 mi.
22118 inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, false, true);
22119 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
22120 if skip_mode {
22121 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
22122 }
22123
22124 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
22125 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
22126 inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, skip, false);
22127 maybe_read_cdef_idx(dec, leaf_mi.0, leaf_mi.1, skip);
22128 // Always a `BLOCK_8X8` leaf here, never the whole superblock.
22129 maybe_read_delta_q(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip);
22130 maybe_read_delta_lf(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip);
22131
22132 let (has_above, has_left) = (
22133 leaf_mi.0 > neighbours.tile_row0_mi,
22134 leaf_mi.1 > neighbours.tile_col0_mi,
22135 );
22136 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
22137 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
22138 // lane-inter8 r1: mirrors the oracle's `EC_MODE` (instrument rung 4,
22139 // `read_inter_block_mode_info`) so an 8x8 leaf's mode-info range ladder
22140 // diffs line for line against a real aomdec.
22141 if std::env::var_os("EC_TRACE_MODE").is_some() {
22142 eprintln!(
22143 "EC_MODE mi_row={} mi_col={} rng={}",
22144 leaf_mi.0,
22145 leaf_mi.1,
22146 dec.debug_state().0
22147 );
22148 }
22149
22150 let mode_for_tx;
22151 // lane-uv8 r1: this leaf's chroma prediction mode (`get_uv_mode` of the
22152 // coded `uv_mode`), for the neighbour bands at the tail. An INTER leaf
22153 // stores `UV_DC_PRED`, exactly as [`decode_inter_block`] one level up.
22154 let mut uv_predict_mode = DC_PRED;
22155 let (luma_grid, u_grid, v_grid);
22156 let mut compound_ctx8: Option<(i8, i8, u8, u8)> = None;
22157 // lane-inter8 r1: this leaf's own resolved references, handed back so the
22158 // NEXT leaf of the same 16x16 can use them as its real above/left
22159 // neighbour (`Neighbours`' arrays only move once per 16x16 block).
22160 // `(0, None)` is intra.
22161 let mut leaf_refs: (i8, Option<i8>) = (0, None);
22162 if is_inter {
22163 if reference_select || skip_mode {
22164 // lane-inter8 r1: the REAL neighbour references, not a
22165 // `LAST_FRAME`-or-intra stand-in. `av1_get_reference_mode_context`
22166 // and `read_compound_ref_frames`' own contexts both ask whether a
22167 // neighbour is COMPOUND, so pretending every inter neighbour is
22168 // single-ref LAST picked the wrong `comp_mode` CDF row -- measured
22169 // as an 8x8 leaf reading single-ref where aomdec read compound
22170 // NEAR_NEWMV (mi 4,14).
22171 let above_nbr = has_above.then(|| NeighbourRef {
22172 is_inter: above_inter,
22173 ref0: if above_inter { above_ref0 } else { 0 },
22174 ref1: above_ref1,
22175 uni: above_ref1.is_some_and(|r1| is_uni_comp_ref(above_ref0, r1)),
22176 });
22177 let left_nbr = has_left.then(|| NeighbourRef {
22178 is_inter: left_inter,
22179 ref0: if left_inter { left_ref0 } else { 0 },
22180 ref1: left_ref1,
22181 uni: left_ref1.is_some_and(|r1| is_uni_comp_ref(left_ref0, r1)),
22182 });
22183 if skip_mode || read_comp_mode(dec, cdfs, above_nbr, left_nbr) {
22184 let (ref0, ref1) = if skip_mode {
22185 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
22186 } else {
22187 // lane-interp3 r2 (class twin-functions-drift): this leaf
22188 // passed a hard-coded `LAST_FRAME` for every inter
22189 // neighbour -- the old "coarse LAST_FRAME-or-intra"
22190 // approximation -- while the side bands have carried the
22191 // neighbour's REAL reference per mi since lane-inter8 r2.
22192 // Every `av1_collect_neighbors_ref_counts` vote below
22193 // (`uni_comp_ref_p1`, `comp_ref`, `comp_bwdref`, ...) was
22194 // therefore taken off the wrong CDF row. Same two args
22195 // [`decode_inter_block`]'s own compound arm passes
22196 // (`-1` when the band is unavailable is start_tile's /
22197 // start_row's own reset value, so no `has_above` guard).
22198 read_compound_ref_frames(
22199 dec,
22200 cdfs,
22201 above_nbr,
22202 left_nbr,
22203 above_ref0,
22204 left_ref0,
22205 )
22206 };
22207 leaf_refs = (ref0, Some(ref1));
22208 let (mi_row, mi_col) = leaf_mi;
22209 // spec 7.10.2.8, mirroring [`decode_inter_block`]'s own
22210 // `comp_tpl` build (`use_ref_frame_mvs` frames only).
22211 let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs {
22212 field: t.field,
22213 cur_offset_0: crate::motion_field::get_relative_dist(
22214 t.order_hint_bits,
22215 t.order_hint,
22216 t.ref_order_hints[(ref0 - LAST_FRAME) as usize],
22217 ),
22218 cur_offset_1: crate::motion_field::get_relative_dist(
22219 t.order_hint_bits,
22220 t.order_hint,
22221 t.ref_order_hints[(ref1 - LAST_FRAME) as usize],
22222 ),
22223 allow_high_precision_mv,
22224 });
22225 // lane-av1comp: this leaf path has neither a real sign-bias
22226 // table nor `tpl_frame` (see this function's own doc on the
22227 // coarse `LAST_FRAME`-or-intra neighbour approximation
22228 // already in force above), matching the plain `find_mv_stack`
22229 // (no bias, no tpl) the leaf's single-ref arm below already
22230 // uses.
22231 let comp_stack = crate::mvstack::find_mv_stack_compound(
22232 grid,
22233 mi_row,
22234 mi_col,
22235 2,
22236 2,
22237 (ref0, ref1),
22238 mi_cols as usize,
22239 mi_rows as usize,
22240 sign_bias_table,
22241 &gm_table,
22242 comp_tpl,
22243 );
22244 let compound_mode = if skip_mode {
22245 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
22246 } else {
22247 read_inter_compound_mode(
22248 dec,
22249 cdfs,
22250 comp_stack.new_mv_ctx,
22251 comp_stack.ref_mv_ctx,
22252 )
22253 };
22254 if std::env::var_os("EC_TRACE_MODE").is_some() {
22255 eprintln!(
22256 "EC_LEAFMODE mi_row={} mi_col={} cmode={} stack={} newmv_ctx={} refmv_ctx={} rng={}",
22257 leaf_mi.0,
22258 leaf_mi.1,
22259 compound_mode + 17,
22260 comp_stack.entries.len(),
22261 comp_stack.new_mv_ctx,
22262 comp_stack.ref_mv_ctx,
22263 dec.debug_state().0
22264 );
22265 }
22266 let (mv0, mv1) = assign_compound_mv(
22267 dec,
22268 cdfs,
22269 &comp_stack,
22270 compound_mode,
22271 allow_high_precision_mv,
22272 force_integer_mv,
22273 // lane-inter8 r1: the real per-ref gm mvs, same as
22274 // [`decode_inter_block`]'s own compound arm.
22275 (
22276 gm_table[(ref0 - LAST_FRAME) as usize],
22277 gm_table[(ref1 - LAST_FRAME) as usize],
22278 ),
22279 );
22280 // lane-inter8 r3: byte-format-identical to the oracle's
22281 // rung-4 `EC_MODE_VAL`, so the leaf's mode+mv VALUE ladder
22282 // diffs line for line against a real aomdec.
22283 if std::env::var_os("EC_TRACE_MODE").is_some() {
22284 eprintln!(
22285 "EC_MODE_VAL mi_row={} mi_col={} mode={} ref0={} ref1={} mv0=({},{}) rng={}",
22286 leaf_mi.0,
22287 leaf_mi.1,
22288 compound_mode + 17,
22289 ref0,
22290 ref1,
22291 mv0.0,
22292 mv0.1,
22293 dec.debug_state().0
22294 );
22295 }
22296
22297 // spec 5.11.25: same gating [`decode_inter_block`]'s own
22298 // compound arm uses, keyed off `outer_at`'s [`SUB`]-grid
22299 // slot -- the only granularity `Neighbours`' comp_group_idx/
22300 // compound_idx arrays track.
22301 let group_ctx = get_comp_group_idx_context(neighbours, leaf_mi, SIDE);
22302 let comp_group_idx = if !skip_mode
22303 && enable_masked_compound
22304 && is_any_masked_compound_used_here(SIDE, SIDE)
22305 {
22306 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
22307 } else {
22308 0
22309 };
22310 // lane-maskcomp r2 / lane-wedge r3: see the 16x16/32x32
22311 // leaf's own comment.
22312 let mut diffwtd_mask_type: Option<u8> = None;
22313 let mut wedge_mask: Option<&'static [u8]> = None;
22314 if comp_group_idx == 1 {
22315 // lane-maskcomp r1: see the 16x16 leaf's own comment
22316 // above -- SIDE==8 here, `wedge_bsize` index 3
22317 // (BLOCK_8X8, `wedge_types > 0`).
22318 let compound_type = dec.symbol(&mut cdfs.compound_type[3]);
22319 if compound_type == 0 {
22320 // COMPOUND_WEDGE: lane-wedge r3, see the 16x16/32x32
22321 // leaf's own comment.
22322 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]);
22323 let wedge_sign = dec.literal(1);
22324 WEDGE_HITS.with(|c| c.set(c.get() + 1));
22325 wedge_mask = Some(
22326 crate::wedge::wedge_masks()
22327 .codebook(SIDE, SIDE)
22328 .mask(wedge_sign as usize, wedge_index as usize),
22329 );
22330 } else {
22331 let mask_type = dec.literal(1);
22332 diffwtd_mask_type = Some(mask_type as u8);
22333 }
22334 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
22335 }
22336 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): same
22337 // reference-slot defect as the 16x16 leaf's own mask above
22338 // (r1: falsified as an MC/blend math bug, isolated to a DPB
22339 // slot/refresh_frame_flags issue around BWDREF_FRAME) -- see
22340 // that comment.
22341 // r3: same defect as the 16x16 leaf's own mask above -- see
22342 // that comment (compound_idx's decoded value, not the blend
22343 // math or reference-slot bookkeeping). r6/r7: same re-mask
22344 // as the 16x16 leaf above -- one real bug found and fixed
22345 // (mvstack.rs ref_ctx family), a second, still-unfound
22346 // compound_idx defect surfaces on the wide gate sweep.
22347 // lane-av1idx r1: same re-mask as the 16x16 leaf above --
22348 // see that comment.
22349 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
22350 && !skip_mode
22351 && enable_jnt_comp
22352 {
22353 let idx_ctx = get_comp_index_context(
22354 neighbours,
22355 leaf_mi,
22356 SIDE,
22357 order_hint_bits,
22358 order_hint,
22359 ref_order_hints[(ref0 - LAST_FRAME) as usize],
22360 ref_order_hints[(ref1 - LAST_FRAME) as usize],
22361 );
22362 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
22363 if idx == 1 {
22364 (8, 8, 1u8)
22365 } else {
22366 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
22367 order_hint_bits,
22368 order_hint,
22369 ref_order_hints[(ref0 - LAST_FRAME) as usize],
22370 ref_order_hints[(ref1 - LAST_FRAME) as usize],
22371 );
22372 (fwd, bck, 0u8)
22373 }
22374 } else {
22375 (8, 8, 1u8)
22376 };
22377 compound_ctx8 = Some((ref0, ref1, comp_group_idx as u8, compound_idx));
22378 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
22379 eprintln!(
22380 "EC_COMPIDX mi_row={mi_row} mi_col={mi_col} bsize=8 mode={compound_mode} mv0=({},{}) mv1=({},{}) ref0={ref0} ref1={ref1} comp_group_idx={comp_group_idx} compound_idx={compound_idx} tell={}",
22381 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
22382 );
22383 }
22384
22385 // lane-interp3 r1: `read_mb_interp_filter` (libaom
22386 // `decodemv.c` 1575, the tail of
22387 // `read_inter_block_mode_info`) runs for EVERY inter block,
22388 // compound included, right AFTER `read_compound_type` -- this
22389 // leaf read no filter symbol at all, so a SWITCHABLE-filter
22390 // stream lost one symbol (two under `enable_dual_filter`) at
22391 // every compound 8x8 leaf, and the leaf recorded the `[3, 3]`
22392 // "no filter" sentinel, which made a neighbouring OBMC block's
22393 // `neighbour_filter` PANIC instead of blending.
22394 // `av1_is_interp_needed` suppression terms for this arm:
22395 // `skip_mode`, and `is_nontrans_global_motion` (mode
22396 // GLOBAL_GLOBALMV with BOTH refs' models non-TRANSLATION) --
22397 // WARPED_CAUSAL cannot occur on a compound block.
22398 let gm_nontrans_c = compound_mode == 6
22399 && global_motion[(ref0 - LAST_FRAME) as usize].model
22400 != ec_av1_syntax::WarpModel::Translation
22401 && global_motion[(ref1 - LAST_FRAME) as usize].model
22402 != ec_av1_syntax::WarpModel::Translation;
22403 // spec `get_ref_filter_type`, keyed on this block's ref0 and
22404 // matching EITHER of the neighbour's references -- same shape
22405 // as [`decode_inter_block`]'s compound arm. Same corner-cut as
22406 // this leaf's single-ref arm below: the context comes from the
22407 // enclosing 16x16's coarse slot.
22408 let above_filter_ctx = if neighbours.above_ref[cmi] == ref0
22409 || neighbours.above_ref1[cmi] == Some(ref0)
22410 {
22411 neighbours.above_filter[cmi]
22412 } else {
22413 [3, 3]
22414 };
22415 let left_filter_ctx = if neighbours.left_ref[rmi] == ref0
22416 || neighbours.left_ref1[rmi] == Some(ref0)
22417 {
22418 neighbours.left_filter[rmi]
22419 } else {
22420 [3, 3]
22421 };
22422 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
22423 dec,
22424 cdfs,
22425 interp_fixed,
22426 enable_dual_filter,
22427 gm_nontrans_c || skip_mode,
22428 above_filter_ctx,
22429 left_filter_ctx,
22430 true,
22431 );
22432 leaf_filter_syms = resolved_filter;
22433 if interp_fixed.is_none() && !(gm_nontrans_c || skip_mode) {
22434 COMPOUND8_FILTER_HITS.with(|c| c.set(c.get() + 1));
22435 }
22436
22437 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
22438 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
22439 let scale0 = mc::scale_factor(py0.width, frame_width);
22440 let scale1 = mc::scale_factor(py1.width, frame_width);
22441 if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE {
22442 SCALED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
22443 SCALED_BLOCK8_HITS.with(|c| c.set(c.get() + 1));
22444 }
22445
22446 // lane-interp3 r2 (class twin-functions-drift): both slots
22447 // used to be stamped `false`, while [`decode_inter_block`]'s
22448 // compound arm computes libaom's PER-SLOT `is_global_mv_block`
22449 // (blockd.h:421-429 -- mode GLOBAL_GLOBALMV, block >= 8x8
22450 // (always true for this leaf) and THAT slot's own gm model >
22451 // TRANSLATION). A neighbour carrying the flag makes
22452 // `setup_ref_mv_list` substitute the READER's global mv for
22453 // the neighbour's stored one, so a cleared flag fed the next
22454 // block's stack a stored mv where libaom has the global
22455 // candidate -- a wrong mv stack, wrong mode contexts, and a
22456 // desync one block later.
22457 let is_globalmv_c = compound_mode == 6;
22458 let is_global_mv0_c = is_globalmv_c
22459 && global_motion[(ref0 - LAST_FRAME) as usize].model as u8 > 1;
22460 let is_global_mv1_c = is_globalmv_c
22461 && global_motion[(ref1 - LAST_FRAME) as usize].model as u8 > 1;
22462 // lane-interp3 r3 (class twin-functions-drift, second
22463 // instance): libaom applies `allow_warp`'s GLOBAL branch
22464 // (`reconinter.c:33-55`, reached from `av1_init_warp_params`
22465 // inside `build_inter_predictors_8x8_and_bigger`'s per-`ref`
22466 // loop) to EVERY `is_global_mv_block` slot, compound
22467 // included and independently of `motion_mode` -- the 16x16+
22468 // compound arm has done this since lane-cwarp r1, this leaf
22469 // predicted both taps translationally, so a GLOBAL_GLOBALMV
22470 // 8x8 compound leaf under a non-TRANSLATION model drifted by
22471 // a few luma levels, growing away from the block origin.
22472 // `force_integer_mv` short-circuits `av1_init_warp_params`
22473 // before `allow_warp`; chroma is 4x4 here, below
22474 // `av1_init_warp_params`'s own 8px per-plane bound, so only
22475 // luma warps (same rule as this leaf's single-ref arm).
22476 let leaf_compound_warp = |ref_frame: i8, eligible: bool| {
22477 if eligible
22478 && !force_integer_mv
22479 && !global_motion[(ref_frame - LAST_FRAME) as usize].invalid
22480 {
22481 crate::warp::global_warp_params(
22482 global_motion[(ref_frame - LAST_FRAME) as usize].params,
22483 )
22484 } else {
22485 None
22486 }
22487 };
22488 let warp0_c = leaf_compound_warp(ref0, is_global_mv0_c);
22489 let warp1_c = leaf_compound_warp(ref1, is_global_mv1_c);
22490 if warp0_c.is_some() || warp1_c.is_some() {
22491 COMPOUND_WARP_HITS.with(|c| c.set(c.get() + 1));
22492 COMPOUND_WARP_HITS_8.with(|c| c.set(c.get() + 1));
22493 }
22494 for dr in 0..2 {
22495 for dc in 0..2 {
22496 grid.set(
22497 mi_row + dr,
22498 mi_col + dc,
22499 MiInfo {
22500 is_inter: true,
22501 ref_frame: ref0,
22502 ref_frame1: Some(ref1),
22503 mv1: Some(mv1),
22504 mv: mv0,
22505 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
22506 size: 2,
22507 size_h: 2,
22508 is_global_mv0: is_global_mv0_c,
22509 is_global_mv1: is_global_mv1_c,
22510 },
22511 );
22512 }
22513 }
22514 mode_for_tx = 0;
22515
22516 let mut inter0_y = vec![0i32; SIDE * SIDE];
22517 mc::predict_compound_intermediate(
22518 &py0.data,
22519 py0.width,
22520 py0.true_width,
22521 py0.true_height,
22522 mv_to_q4(px, mv0.1, true),
22523 mv_to_q4(py, mv0.0, true),
22524 scale0,
22525 SIDE,
22526 SIDE,
22527 h_filter,
22528 v_filter,
22529 &mut inter0_y,
22530 );
22531 if let Some(wp) = &warp0_c {
22532 crate::warp::warp_affine_compound(
22533 wp, &py0.data, py0.true_width as i32, py0.true_height as i32,
22534 py0.width as i32, &mut inter0_y, px as i32, py as i32, SIDE as i32,
22535 SIDE as i32, SIDE as i32, 0, 0,
22536 );
22537 }
22538 let mut inter1_y = vec![0i32; SIDE * SIDE];
22539 mc::predict_compound_intermediate(
22540 &py1.data,
22541 py1.width,
22542 py1.true_width,
22543 py1.true_height,
22544 mv_to_q4(px, mv1.1, true),
22545 mv_to_q4(py, mv1.0, true),
22546 scale1,
22547 SIDE,
22548 SIDE,
22549 h_filter,
22550 v_filter,
22551 &mut inter1_y,
22552 );
22553 if let Some(wp) = &warp1_c {
22554 crate::warp::warp_affine_compound(
22555 wp, &py1.data, py1.true_width as i32, py1.true_height as i32,
22556 py1.width as i32, &mut inter1_y, px as i32, py as i32, SIDE as i32,
22557 SIDE as i32, SIDE as i32, 0, 0,
22558 );
22559 }
22560 let mut pred_y = vec![0u16; SIDE * SIDE];
22561 let mut diffwtd_mask_y = Vec::new();
22562 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
22563 diffwtd_mask_y = vec![0u8; SIDE * SIDE];
22564 DIFFWTD_HITS.with(|c| c.set(c.get() + 1));
22565 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
22566 Some(diffwtd_mask_y.as_slice())
22567 } else {
22568 wedge_mask
22569 };
22570 if let Some(mask_y) = mask_y {
22571 mc::blend_masked_compound(
22572 &inter0_y, &inter1_y, mask_y, SIDE, SIDE, SIDE, false, &mut pred_y,
22573 );
22574 } else {
22575 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
22576 }
22577
22578 let mut inter0_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
22579 mc::predict_compound_intermediate(
22580 &pu0.data,
22581 pu0.width,
22582 pu0.true_width,
22583 pu0.true_height,
22584 mv_to_q4(cpx, mv0.1, false),
22585 mv_to_q4(cpy, mv0.0, false),
22586 scale0,
22587 CHROMA_SIDE,
22588 CHROMA_SIDE,
22589 h_filter,
22590 v_filter,
22591 &mut inter0_u,
22592 );
22593 let mut inter1_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
22594 mc::predict_compound_intermediate(
22595 &pu1.data,
22596 pu1.width,
22597 pu1.true_width,
22598 pu1.true_height,
22599 mv_to_q4(cpx, mv1.1, false),
22600 mv_to_q4(cpy, mv1.0, false),
22601 scale1,
22602 CHROMA_SIDE,
22603 CHROMA_SIDE,
22604 h_filter,
22605 v_filter,
22606 &mut inter1_u,
22607 );
22608 let mut pred_u = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
22609 if let Some(mask_y) = mask_y {
22610 mc::blend_masked_compound(
22611 &inter0_u,
22612 &inter1_u,
22613 mask_y,
22614 SIDE,
22615 CHROMA_SIDE,
22616 CHROMA_SIDE,
22617 true,
22618 &mut pred_u,
22619 );
22620 } else {
22621 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
22622 }
22623
22624 let mut inter0_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
22625 mc::predict_compound_intermediate(
22626 &pv0.data,
22627 pv0.width,
22628 pv0.true_width,
22629 pv0.true_height,
22630 mv_to_q4(cpx, mv0.1, false),
22631 mv_to_q4(cpy, mv0.0, false),
22632 scale0,
22633 CHROMA_SIDE,
22634 CHROMA_SIDE,
22635 h_filter,
22636 v_filter,
22637 &mut inter0_v,
22638 );
22639 let mut inter1_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
22640 mc::predict_compound_intermediate(
22641 &pv1.data,
22642 pv1.width,
22643 pv1.true_width,
22644 pv1.true_height,
22645 mv_to_q4(cpx, mv1.1, false),
22646 mv_to_q4(cpy, mv1.0, false),
22647 scale1,
22648 CHROMA_SIDE,
22649 CHROMA_SIDE,
22650 h_filter,
22651 v_filter,
22652 &mut inter1_v,
22653 );
22654 let mut pred_v = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
22655 if let Some(mask_y) = mask_y {
22656 mc::blend_masked_compound(
22657 &inter0_v,
22658 &inter1_v,
22659 mask_y,
22660 SIDE,
22661 CHROMA_SIDE,
22662 CHROMA_SIDE,
22663 true,
22664 &mut pred_v,
22665 );
22666 } else {
22667 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
22668 }
22669
22670 split8 = read_block_tx_size(
22671 dec,
22672 cdfs,
22673 neighbours,
22674 leaf_mi,
22675 SIDE,
22676 (mi_cols as usize, mi_rows as usize),
22677 true,
22678 skip,
22679 )?
22680 .1
22681 .is_some();
22682 if skip {
22683 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
22684 u.reconstruct_mc(
22685 cpx,
22686 cpy,
22687 CHROMA_SIDE,
22688 &pred_u,
22689 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
22690 );
22691 v.reconstruct_mc(
22692 cpx,
22693 cpy,
22694 CHROMA_SIDE,
22695 &pred_v,
22696 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
22697 );
22698 luma_grid = vec![0i32; SIDE * SIDE];
22699 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
22700 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
22701 } else {
22702 let around = neighbours.around_mi(leaf_mi, 8);
22703 let (grid8, luma_tx_type) = read_inter_luma8(
22704 dec,
22705 cdfs,
22706 neighbours,
22707 leaf_mi,
22708 y,
22709 px,
22710 py,
22711 &pred_y,
22712 mode_for_tx,
22713 base_q_idx,
22714 scan8,
22715 scan4,
22716 reduced_tx_set,
22717 split8,
22718 )?;
22719 luma_grid = grid8;
22720 u_grid = read_inter_plane(
22721 dec,
22722 cdfs,
22723 TxbSet::Chroma4,
22724 scan4,
22725 1,
22726 around[1],
22727 mode_for_tx,
22728 u,
22729 cpx,
22730 cpy,
22731 CHROMA_SIDE,
22732 base_q_idx,
22733 &pred_u,
22734 Some(luma_tx_type),
22735 None,
22736 )?
22737 .0;
22738 v_grid = read_inter_plane(
22739 dec,
22740 cdfs,
22741 TxbSet::Chroma4,
22742 scan4,
22743 2,
22744 around[2],
22745 mode_for_tx,
22746 v,
22747 cpx,
22748 cpy,
22749 CHROMA_SIDE,
22750 base_q_idx,
22751 &pred_v,
22752 Some(luma_tx_type),
22753 None,
22754 )?
22755 .0;
22756 }
22757 // lane-inter8 r2: the COMPOUND leaf used to return here
22758 // WITHOUT the end-of-function `record_mi`/`fill_lf_grid` the
22759 // single-ref path falls through to -- so a compound 8x8 leaf
22760 // left `above_side_mi`/`left_side_mi` (the next block's
22761 // partition context), the per-plane coefficient level state
22762 // and the loop-filter grid describing whatever block was
22763 // there before. Every leaf of the gate's stream is compound,
22764 // so the 16x16 below a split block read partition ctx 0
22765 // instead of 1 and mis-read PARTITION_SPLIT as NONE.
22766 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
22767 // lane-cdef r1: ... and the CDEF skip band too. `apply_cdef`'s
22768 // `is_8x8_block_skip` (libaom `cdef.c:29-38`) reads all four mi
22769 // cells of the 8x8; this leaf wrote none of them, so a 64x64
22770 // whose bottom-right 16x16 is an all-skip 8x8-leaf group kept
22771 // the PREVIOUS frame's flags and got filtered where libaom's
22772 // dlist excludes it (3 luma samples on a 192x128 inter frame).
22773 INTER8_SKIP_BAND_HITS.with(|c| c.set(c.get() + 1));
22774 neighbours.fill_skip_grid(leaf_mi, 2, skip);
22775 neighbours.fill_lf_grid(
22776 leaf_mi,
22777 2,
22778 8,
22779 if is_inter { leaf_refs.0.max(LAST_FRAME) } else { 0 },
22780 );
22781 return Ok((
22782 skip,
22783 is_inter,
22784 skip_mode,
22785 compound_ctx8,
22786 leaf_filter_syms,
22787 leaf_refs,
22788 ));
22789 }
22790 }
22791 // lane-gmaffine r1: the leaf reads the FULL `single_ref` tree
22792 // ([`read_single_ref`], the same one the 16x16+ leaf uses, with the
22793 // real per-neighbour p1..p6 contexts) instead of the old three-symbol
22794 // LAST-only probe plus a refusal -- aomenc picks GOLDEN/ALTREF for
22795 // 8x8 leaves constantly, so that refusal was what every 8x8 gate
22796 // actually stopped at.
22797 let ref_frame = read_single_ref(
22798 dec,
22799 cdfs,
22800 neighbours.above_ref[cmi],
22801 neighbours.above_ref1[cmi],
22802 neighbours.left_ref[rmi],
22803 neighbours.left_ref1[rmi],
22804 );
22805 leaf_refs = (ref_frame, None);
22806 let (sref_y, sref_u, sref_v) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?;
22807
22808 let (mi_row, mi_col) = leaf_mi;
22809 // lane-inter8 r2: the frame's temporal mv candidates, keyed on THIS
22810 // leaf's own reference (lane-gmaffine r1 taught it non-LAST refs).
22811 let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
22812 field: t.field,
22813 cur_offset_0: crate::motion_field::get_relative_dist(
22814 t.order_hint_bits,
22815 t.order_hint,
22816 t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
22817 ),
22818 allow_high_precision_mv,
22819 });
22820 let stack = crate::mvstack::find_mv_stack_with_sign_bias(
22821 grid,
22822 mi_row,
22823 mi_col,
22824 2,
22825 2,
22826 ref_frame,
22827 mi_cols as usize,
22828 mi_rows as usize,
22829 sign_bias_table,
22830 &gm_table,
22831 tpl,
22832 );
22833 // lane-interp3 r2: same per-entry EC_STACK ladder
22834 // [`decode_inter_block`]'s single-ref arm prints, so this leaf's stack
22835 // diffs line for line against the oracle's.
22836 if std::env::var_os("EC_TRACE_MODE").is_some() {
22837 for (i, e) in stack.entries.iter().enumerate() {
22838 eprintln!(
22839 "EC_STACK mi_row={mi_row} mi_col={mi_col} ref={ref_frame} i={i} this=({},{}) comp=(0,0) w={}",
22840 e.mv.0, e.mv.1, e.weight
22841 );
22842 }
22843 }
22844
22845 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
22846 let mut is_globalmv = false;
22847 let (mv, is_new_mv) = if !not_new {
22848 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
22849 // read at most two `drl_mode` bits, one per stack entry past the
22850 // first, stopping at the first `0`. The chosen index selects
22851 // which stack entry `read_mv`'s base predictor comes from
22852 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
22853 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
22854 let mut idx = 0usize;
22855 while idx < 2 && stack.entries.len() > idx + 1 {
22856 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
22857 break;
22858 }
22859 idx += 1;
22860 }
22861 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
22862 (
22863 read_mv(
22864 dec,
22865 &mut cdfs.mv_comp,
22866 &mut cdfs.mv_joint,
22867 base_mv,
22868 allow_high_precision_mv,
22869 force_integer_mv,
22870 ),
22871 true,
22872 )
22873 } else {
22874 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
22875 is_globalmv = !not_zero;
22876 let mv = if !not_zero {
22877 // lane-gmaffine r1: GLOBALMV (spec 7.10.2.1) -- the same
22878 // `gm_get_motion_vector` value the 16x16+ leaf reads out of
22879 // its own `gm_table`, computed at this block's centre.
22880 GLOBALMV_HITS_8.with(|c| c.set(c.get() + 1));
22881 gm_table[(ref_frame - LAST_FRAME) as usize]
22882 } else {
22883 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
22884 if nearest {
22885 stack.nearest_mv
22886 } else {
22887 let mut idx = 1usize;
22888 while idx < 3 && stack.entries.len() > idx + 1 {
22889 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
22890 break;
22891 }
22892 idx += 1;
22893 }
22894 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
22895 }
22896 };
22897 (mv, false)
22898 };
22899 // lane-sb128 r4: `interintra` (spec 5.11.24) at the 8x8 leaf too --
22900 // see [`decode_inter_block`]'s own doc; `BLOCK_8X8` is always
22901 // `is_interintra_allowed_bsize`-eligible, single-ref-only branch
22902 // (compound already returned above), GLOBALMV already refused
22903 // (round 3), so the only real gate left is the header enable bit.
22904 let mut interintra_mode: Option<u8> = None;
22905 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
22906 if enable_interintra_compound && !skip_mode {
22907 let interintra = dec.symbol(&mut cdfs.interintra[SIZE_GROUP_8]) == 1;
22908 if interintra {
22909 // lane-interintra r1: same read pair as the 16/32 site;
22910 // wedge cdf row = BLOCK_8X8 (index 3), read on block size
22911 // alone, never the `enable_interintra_wedge` seq bit.
22912 let ii = dec.symbol(&mut cdfs.interintra_mode[SIZE_GROUP_8]) as u8;
22913 let wedge = dec.symbol(&mut cdfs.wedge_interintra[3]) == 1;
22914 if wedge {
22915 // lane-wii r2: same adapting `wedge_index` symbol as the
22916 // 16/32 leaf, fixed sign 0 -- see that site's comment.
22917 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]);
22918 WII_HITS.with(|c| c.set(c.get() + 1));
22919 wedge_mask = Some((
22920 crate::wedge::wedge_masks()
22921 .codebook(SIDE, SIDE)
22922 .mask(0, wedge_index as usize),
22923 SIDE,
22924 ));
22925 } else {
22926 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
22927 }
22928 interintra_mode = Some(ii);
22929 }
22930 }
22931 // lane-motionmode round 3: `read_motion_mode` (spec 5.11.24) at the
22932 // 8x8 leaf too -- `motion_mode_allowed` still holds here (BLOCK_8X8
22933 // is the spec's own minimum eligible size, single-ref-only branch,
22934 // no interintra reader, `IDENTITY`-only global motion). Mirrors the
22935 // 16x16 leaf's own `decode_inter_block` read (see its doc above) --
22936 // same 2-symbol `obmc_cdf` alphabet, same `allow_warped_motion=1`
22937 // refusal (warp needs `av1_findSamples`, not ported at either leaf).
22938 // lane-gmaffine r1: the two libaom predicates, exactly as the
22939 // 16x16+ leaf resolves them (see [`decode_inter_block`]'s own doc):
22940 // `is_global_mv_block` (mode GLOBAL*, model > TRANSLATION, block
22941 // >= 8x8 -- BLOCK_8X8 IS the 8px minimum, so the size predicate is
22942 // always true here) suppresses the motion_mode read entirely and
22943 // turns on the global warp below.
22944 let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
22945 let is_global_mv_block = is_globalmv && gm_ref.model as u8 > 1;
22946 let motion_mode_eligible = switchable_motion_mode
22947 && !skip_mode
22948 && interintra_mode.is_none()
22949 && !(is_global_mv_block && !force_integer_mv)
22950 && (!overlappable_above(grid, mi_row, mi_col, 2, mi_cols as usize, 1).is_empty()
22951 || !overlappable_left(grid, mi_row, mi_col, 2, mi_rows as usize, 1).is_empty());
22952 let mut warp_params: Option<crate::warp::WarpParams> = None;
22953 let mut warped_selected = false;
22954 let mut obmc_selected = false;
22955 if motion_mode_eligible {
22956 // lane-warp round 1: same 3-vs-2-symbol split as the 16x16+ leaf
22957 // (see its own doc) -- this leaf is always `LAST_FRAME`-only
22958 // (grid.set below hardcodes it).
22959 // lane-scaledref r2 sibling of the 16x16+ leaf's fix: libaom
22960 // drops WARPED_CAUSAL eligibility (so this reads `obmc_cdf`)
22961 // when the reference is scaled. Not gated here because an 8x8
22962 // leaf under a scaled reference is refused before this function
22963 // runs (see the block8 refusal below, ~12500) -- whoever lifts
22964 // that refusal must add `&& !ref_is_scaled` here too.
22965 // lane-fimv r1: libaom `motion_mode_allowed` also requires
22966 // `!xd->cur_frame_force_integer_mv`, so a screen-content frame
22967 // that set `force_integer_mv` reads the 2-symbol `obmc_cdf` here
22968 // (class wrong-alphabet-same-value).
22969 let proj_ok =
22970 num_proj_ref(grid, mi_row, mi_col, 2, 2, mi_cols as usize, mi_rows as usize, ref_frame) >= 1;
22971 let warp_eligible = allow_warped_motion && !force_integer_mv && proj_ok;
22972 if allow_warped_motion && proj_ok && force_integer_mv {
22973 FIMV_ALPHABET_HITS.with(|c| c.set(c.get() + 1));
22974 }
22975 if warp_eligible {
22976 let mode = dec.symbol(&mut cdfs.motion_mode[0]);
22977 match mode {
22978 0 => {}
22979 1 => {
22980 obmc_selected = true;
22981 OBMC_HITS.with(|c| c.set(c.get() + 1));
22982 OBMC_HITS_8.with(|c| c.set(c.get() + 1));
22983 }
22984 _ => {
22985 // lane-gmaffine r1: WARPED_CAUSAL at the 8x8 leaf --
22986 // the same findSamples -> select_samples ->
22987 // av1_find_projection chain the 16x16+ leaf runs,
22988 // with BLOCK_8X8's own 8x8 model centre; an
22989 // unusable projection falls back to the block's
22990 // translational mv (libaom `av1_find_projection`
22991 // returning 1 leaves `wm_params` invalid and
22992 // `build_inter_predictors` skips the warp).
22993 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
22994 let mut samples = find_samples(
22995 grid,
22996 mi_row,
22997 mi_col,
22998 2,
22999 2,
23000 mi_cols as usize,
23001 mi_rows as usize,
23002 ref_frame,
23003 );
23004 if samples.len() > 1 {
23005 crate::warp::select_samples(mv, &mut samples, SIDE as i32, SIDE as i32);
23006 }
23007 warp_params = crate::warp::find_projection(
23008 &samples,
23009 SIDE as i32,
23010 SIDE as i32,
23011 mv.1,
23012 mv.0,
23013 mi_row as i32,
23014 mi_col as i32,
23015 );
23016 warped_selected = true;
23017 if warp_params.is_some() {
23018 WARP_HITS_8.with(|c| c.set(c.get() + 1));
23019 }
23020 }
23021 }
23022 } else {
23023 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 -> 0/1/2/3.
23024 obmc_selected = dec.symbol(&mut cdfs.obmc[0]) == 1;
23025 if obmc_selected {
23026 OBMC_HITS.with(|c| c.set(c.get() + 1));
23027 OBMC_HITS_8.with(|c| c.set(c.get() + 1));
23028 }
23029 }
23030 }
23031 // lane-gmaffine r1: `read_mb_interp_filter` (spec 5.11.26) at the 8x8
23032 // leaf, in libaom's own order (interintra, motion_mode, THEN the
23033 // filter). Until this round the leaf read no filter symbol at all and
23034 // predicted Regular unconditionally -- correct only for a frame with a
23035 // fixed `interp_filter`, and a silent entropy DESYNC for every
23036 // SWITCHABLE-filter stream that reaches an 8x8 leaf (which is what
23037 // made the interior-split wiring above unusable at first).
23038 // corner-cut: the neighbour filter context is the enclosing 16x16
23039 // block's own coarse `above_filter`/`left_filter` entry (this leaf
23040 // path keeps no per-leaf neighbour array), so all four siblings read
23041 // the same context row. Ceiling: a stream whose 8x8 siblings pick
23042 // DIFFERENT filters decodes the second..fourth leaf's symbol from the
23043 // wrong CDF row. Upgrade: give `Neighbours` a real 8x8-granular
23044 // filter array, same shape as the `[3, 3]` approximation the caller
23045 // records after the leaf loop.
23046 let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame
23047 || neighbours.above_ref1[cmi] == Some(ref_frame)
23048 {
23049 neighbours.above_filter[cmi]
23050 } else {
23051 [3, 3]
23052 };
23053 let left_filter_ctx = if neighbours.left_ref[rmi] == ref_frame
23054 || neighbours.left_ref1[rmi] == Some(ref_frame)
23055 {
23056 neighbours.left_filter[rmi]
23057 } else {
23058 [3, 3]
23059 };
23060 let gm_nontrans =
23061 is_globalmv && gm_ref.model != ec_av1_syntax::WarpModel::Translation;
23062 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
23063 dec,
23064 cdfs,
23065 interp_fixed,
23066 enable_dual_filter,
23067 gm_nontrans || warped_selected || skip_mode,
23068 above_filter_ctx,
23069 left_filter_ctx,
23070 false,
23071 );
23072 leaf_filter_syms = resolved_filter;
23073 if std::env::var_os("EC_TRACE_MODE").is_some() {
23074 eprintln!(
23075 "EC_MODE_VAL8 mi_row={} mi_col={} newmv={is_new_mv} globalmv={is_globalmv} ref0={ref_frame} mv0=({},{}) stack={} rng={}",
23076 leaf_mi.0,
23077 leaf_mi.1,
23078 mv.0,
23079 mv.1,
23080 stack.entries.len(),
23081 dec.debug_state().0
23082 );
23083 }
23084 // lane-gmaffine r1: `allow_warp`'s `global_warp_allowed` branch
23085 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --
23086 // see [`decode_inter_block`]'s own copy. A local WARPED_CAUSAL model
23087 // wins (`is_none()` guard); BLOCK_8X8 already satisfies the >=8px
23088 // size predicate baked into `is_global_mv_block`.
23089 if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid {
23090 warp_params = crate::warp::global_warp_params(gm_ref.params);
23091 if warp_params.is_some() && gm_ref.model == ec_av1_syntax::WarpModel::Affine {
23092 AFFINE_GM_HITS.with(|c| c.set(c.get() + 1));
23093 }
23094 }
23095 if std::env::var_os("EC_TRACE_MODE").is_some() {
23096 eprintln!(
23097 "EC_WARP8 mi_row={} mi_col={} warp={} globalblk={is_global_mv_block}",
23098 leaf_mi.0,
23099 leaf_mi.1,
23100 warp_params.is_some(),
23101 );
23102 }
23103 for dr in 0..2 {
23104 for dc in 0..2 {
23105 grid.set(
23106 mi_row + dr,
23107 mi_col + dc,
23108 MiInfo {
23109 is_inter: true,
23110 ref_frame,
23111 // INTRA_FRAME marker for interintra blocks -- keeps
23112 // them out of warp-sample gathering (see 16/32 site).
23113 ref_frame1: interintra_mode.map(|_| 0),
23114 mv1: None,
23115 mv,
23116 is_new_mv,
23117 size: 2,
23118 size_h: 2,
23119 is_global_mv0: is_global_mv_block,
23120 is_global_mv1: false,
23121 },
23122 );
23123 }
23124 }
23125 mode_for_tx = 0;
23126
23127 // lane-scaledref r1: this leaf's own prediction is always `Regular`
23128 // (documented corner-cut above); under a scaled reference the same
23129 // fixed kernel runs through spec 7.11.3.3's scaled walk instead.
23130 let luma_scale = mc::scale_factor(sref_y.width, frame_width);
23131 if luma_scale != mc::REF_NO_SCALE {
23132 SCALED_BLOCK8_HITS.with(|c| c.set(c.get() + 1));
23133 }
23134 let mut pred_y = vec![0u16; SIDE * SIDE];
23135 let mut pred_u = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
23136 let mut pred_v = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
23137 // Merge of lane-gmaffine (this leaf's own switchable filters) with
23138 // lane-scaledref (spec 7.11.3.3's scaled walk): same kernels either
23139 // way, only the sample walk differs.
23140 for (plane, x, y, dim, dst) in [
23141 (sref_y, px, py, SIDE, &mut pred_y),
23142 (sref_u, cpx, cpy, CHROMA_SIDE, &mut pred_u),
23143 (sref_v, cpx, cpy, CHROMA_SIDE, &mut pred_v),
23144 ] {
23145 let luma = std::ptr::eq(plane, sref_y);
23146 if luma_scale == mc::REF_NO_SCALE {
23147 mc::predict_with_filters(
23148 &plane.data,
23149 plane.width,
23150 plane.true_width,
23151 plane.true_height,
23152 mv_to_q4(x, mv.1, luma),
23153 mv_to_q4(y, mv.0, luma),
23154 dim,
23155 dim,
23156 h_filter,
23157 v_filter,
23158 dst,
23159 );
23160 } else {
23161 mc::predict_scaled(
23162 &plane.data,
23163 plane.width,
23164 plane.true_width,
23165 plane.true_height,
23166 mv_to_q4(x, mv.1, luma),
23167 mv_to_q4(y, mv.0, luma),
23168 luma_scale,
23169 dim,
23170 dim,
23171 h_filter,
23172 v_filter,
23173 dst,
23174 );
23175 }
23176 }
23177
23178 // lane-gmaffine r1: the warp filter REPLACES the translational
23179 // prediction just built (libaom builds one or the other), same as
23180 // the 16x16+ leaf's own call trio.
23181 if let Some(params) = &warp_params {
23182 crate::warp::warp_affine(
23183 params, &sref_y.data, sref_y.true_width as i32, sref_y.true_height as i32,
23184 sref_y.width as i32, &mut pred_y, px as i32, py as i32, SIDE as i32,
23185 SIDE as i32, SIDE as i32, 0, 0,
23186 );
23187 // `av1_init_warp_params`'s per-plane `block_width/height < 8`
23188 // bail-out: an 8x8 leaf's chroma plane is 4x4 in 420, so it is
23189 // predicted translationally even when the luma warps.
23190 #[allow(clippy::absurd_extreme_comparisons)]
23191 if CHROMA_SIDE >= 8 {
23192 crate::warp::warp_affine(
23193 params, &sref_u.data, sref_u.true_width as i32, sref_u.true_height as i32,
23194 sref_u.width as i32, &mut pred_u, cpx as i32, cpy as i32, CHROMA_SIDE as i32,
23195 CHROMA_SIDE as i32, CHROMA_SIDE as i32, 1, 1,
23196 );
23197 crate::warp::warp_affine(
23198 params, &sref_v.data, sref_v.true_width as i32, sref_v.true_height as i32,
23199 sref_v.width as i32, &mut pred_v, cpx as i32, cpy as i32, CHROMA_SIDE as i32,
23200 CHROMA_SIDE as i32, CHROMA_SIDE as i32, 1, 1,
23201 );
23202 }
23203 }
23204
23205 if obmc_selected {
23206 obmc_blend(
23207 grid,
23208 neighbours,
23209 mi_row,
23210 mi_col,
23211 2,
23212 2,
23213 mi_rows as usize,
23214 mi_cols as usize,
23215 SIDE,
23216 SIDE,
23217 SIDE,
23218 CHROMA_SIDE,
23219 px,
23220 py,
23221 cpx,
23222 cpy,
23223 ref_y,
23224 ref_u,
23225 ref_v,
23226 other_refs,
23227 interp_fixed,
23228 frame_width,
23229 &mut pred_y,
23230 &mut pred_u,
23231 &mut pred_v,
23232 )?;
23233 }
23234
23235 // Non-wedge interintra blend, mutually exclusive with OBMC (the
23236 // motion_mode symbol is not read for an interintra block).
23237 if let Some(ii) = interintra_mode {
23238 interintra_blend(y, px, py, SIDE, ii, wedge_mask, &mut pred_y);
23239 interintra_blend(u, cpx, cpy, CHROMA_SIDE, ii, wedge_mask, &mut pred_u);
23240 interintra_blend(v, cpx, cpy, CHROMA_SIDE, ii, wedge_mask, &mut pred_v);
23241 }
23242
23243 split8 = read_block_tx_size(
23244 dec,
23245 cdfs,
23246 neighbours,
23247 leaf_mi,
23248 SIDE,
23249 (mi_cols as usize, mi_rows as usize),
23250 true,
23251 skip,
23252 )?
23253 .1
23254 .is_some();
23255 if skip {
23256 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
23257 u.reconstruct_mc(
23258 cpx,
23259 cpy,
23260 CHROMA_SIDE,
23261 &pred_u,
23262 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
23263 );
23264 v.reconstruct_mc(
23265 cpx,
23266 cpy,
23267 CHROMA_SIDE,
23268 &pred_v,
23269 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
23270 );
23271 luma_grid = vec![0i32; SIDE * SIDE];
23272 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
23273 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
23274 } else {
23275 let around = neighbours.around_mi(leaf_mi, 8);
23276 let (grid8, luma_tx_type) = read_inter_luma8(
23277 dec,
23278 cdfs,
23279 neighbours,
23280 leaf_mi,
23281 y,
23282 px,
23283 py,
23284 &pred_y,
23285 mode_for_tx,
23286 base_q_idx,
23287 scan8,
23288 scan4,
23289 reduced_tx_set,
23290 split8,
23291 )?;
23292 luma_grid = grid8;
23293 u_grid = read_inter_plane(
23294 dec,
23295 cdfs,
23296 TxbSet::Chroma4,
23297 scan4,
23298 1,
23299 around[1],
23300 mode_for_tx,
23301 u,
23302 cpx,
23303 cpy,
23304 CHROMA_SIDE,
23305 base_q_idx,
23306 &pred_u,
23307 Some(luma_tx_type),
23308 None,
23309 )?
23310 .0;
23311 v_grid = read_inter_plane(
23312 dec,
23313 cdfs,
23314 TxbSet::Chroma4,
23315 scan4,
23316 2,
23317 around[2],
23318 mode_for_tx,
23319 v,
23320 cpx,
23321 cpy,
23322 CHROMA_SIDE,
23323 base_q_idx,
23324 &pred_v,
23325 Some(luma_tx_type),
23326 None,
23327 )?
23328 .0;
23329 }
23330 } else {
23331 let mode = dec.symbol(&mut cdfs.y_mode[SIZE_GROUP_8]);
23332 if mode >= 13 {
23333 return Err(unsupported(
23334 "an intra mode this decoder does not code (round 2)",
23335 ));
23336 }
23337 // lane-angleinter r1: `read_intra_angle_info` (libaom `decodemv.c`,
23338 // inside `read_intra_block_mode_info`) -- an intra block in an inter
23339 // frame reads `angle_delta_y` off the same
23340 // `angle_delta_cdf[mode - V_PRED]` row a key-frame block does, and
23341 // the delta feeds the directional predictor (and the edge
23342 // filter/upsample decision derived from the delta'd angle) unchanged.
23343 // The symbol was read and then refused before this round even though
23344 // aomenc enables `--enable-angle-delta` by default.
23345 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
23346 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
23347 } else {
23348 0
23349 };
23350 if angle_delta_y != 0 {
23351 INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.set(c.get() + 1));
23352 // lane-angleinter r1: the >=16x16 arm's lift is gated by a real
23353 // aomenc stream; this leaf's is NOT -- 80 attempts across two
23354 // sizes and five quantisers never produced an 8x8 intra leaf with
23355 // a nonzero delta (the leaf's own sibling refusals -- non-DC
23356 // chroma, the TX_4X4 split, sub-16 rect inter leaves -- fire
23357 // first). The prediction below would handle it; refusing keeps
23358 // the rule that no lift ships ungated. Note the claim is about
23359 // THIS DECODER's gate coverage, not about what an encoder writes.
23360 return Err(unsupported(
23361 "a nonzero angle delta on an 8x8 intra leaf in an inter frame (no gate reaches \
23362 this leaf with one; the >=16x16 arm decodes deltas)",
23363 ));
23364 }
23365 // lane-uv8 r1: the delta'd angle decides the intra edge filter, and a
23366 // directional luma mode is already legal on this leaf -- the arm
23367 // passed a hardcoded `false` where [`decode_leaf8`] reads the
23368 // mi-exact neighbour modes (`get_intra_edge_filter_type`, spec
23369 // 7.11.2).
23370 let (above_mode, left_mode) =
23371 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, neighbours.modes_above_left(r, c));
23372 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
23373 // lane-uv8 r1: libaom `read_intra_block_mode_info` (decodemv.c:1198-1207)
23374 // -- `uv_mode` over the CFL-allowed alphabet (`is_cfl_allowed`: a
23375 // BLOCK_8X8 leaf is inside the 32x32 bound), then `read_cfl_alphas`
23376 // for `UV_CFL_PRED`, then `angle_delta_uv` off the MAPPED uv mode's
23377 // row (`get_uv_mode`, identity over `V_PRED..=D67_PRED`). Every value
23378 // but `DC_PRED` was refused here, which is what blocked the low-cq
23379 // CDEF arms and the 10-bit gates.
23380 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
23381 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
23382 eprintln!(
23383 "EC_ISTEP8 mi_row={} mi_col={} name=modes y={mode} uv={uv_mode} fi_enabled={} rng={}",
23384 leaf_mi.0,
23385 leaf_mi.1,
23386 ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get),
23387 dec.debug_state().0
23388 );
23389 }
23390 if (9..=12).contains(&uv_mode) {
23391 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
23392 INTRA_IN_INTER8_UV_SMOOTH_HITS.with(|c| c.set(c.get() + 1));
23393 }
23394 let alpha = if uv_mode == UV_CFL_PRED {
23395 INTRA_IN_INTER8_UV_CFL_HITS.with(|c| c.set(c.get() + 1));
23396 Some(read_cfl_alphas(dec, cdfs))
23397 } else {
23398 None
23399 };
23400 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
23401 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
23402 INTRA_I

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