forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00a6ca0Tahinli3 months ago1913 commits

decode.rs23138 lines, 1.3 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
184thread_local! {
185 static INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
186}
187
188/// Nonzero luma angle deltas coded by an intra 8x8 leaf inside an inter frame
189/// (lane-leaf8tx r1) -- counted only in [`decode_inter_block8`]'s intra arm.
190pub(crate) fn intra_in_inter8_angle_delta_y_hits() -> usize {
191 INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS.with(|c| c.get())
192}
193
194/// `(directional, smooth/paeth, CfL)` chroma modes coded by an intra 8x8 leaf
195/// inside an inter frame -- see [`INTRA_IN_INTER8_UV_DIR_HITS`].
196pub(crate) fn intra_in_inter8_uv_hits() -> (usize, usize, usize) {
197 (
198 INTRA_IN_INTER8_UV_DIR_HITS.with(|c| c.get()),
199 INTRA_IN_INTER8_UV_SMOOTH_HITS.with(|c| c.get()),
200 INTRA_IN_INTER8_UV_CFL_HITS.with(|c| c.get()),
201 )
202}
203
204// lane-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into
205// [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a
206// frame-level flag through the recursive block decode -- `0` (the default)
207// makes every call a true no-op, matching every existing gate stream's
208// `cdef_bits == 0` behaviour exactly.
209thread_local! {
210 static CDEF_BITS: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
211}
212// lane-realworld r8: the sequence header's `color_config.bit_depth`, set
213// once per `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs`
214// call the same way `CDEF_BITS` is above. `stream.rs`'s own refusal still
215// blocks every non-8-bit stream from reaching a decode call, so this is `8`
216// on every path that runs today -- threading it now (rather than the literal
217// `8`) is stage 1 of widening past that refusal without re-deriving every
218// clamp bound later. `PlaneBuf`'s sample storage stays `u16` regardless of
219// depth (this decoder's own internal choice, matches dav1d/libaom).
220thread_local! {
221 static BIT_DEPTH: std::cell::Cell<u8> = const { std::cell::Cell::new(8) };
222}
223/// `(1 << bit_depth) - 1` — the reconstruction clamp bound for the current
224/// stream's [`BIT_DEPTH`], replacing the crate-wide literal `255`.
225pub(crate) fn sample_max() -> i32 {
226 (1i32 << BIT_DEPTH.with(std::cell::Cell::get)) - 1
227}
228/// The current stream's bit depth, for callers (e.g. dequant) that need the
229/// raw value rather than the derived clamp bound.
230pub(crate) fn bit_depth() -> u8 {
231 BIT_DEPTH.with(std::cell::Cell::get)
232}
233/// Sets [`BIT_DEPTH`] for the current thread, called once per frame from
234/// [`crate::stream`]'s decode loop.
235pub(crate) fn set_bit_depth(bit_depth: u8) {
236 BIT_DEPTH.with(|c| c.set(bit_depth));
237}
238// Whether this superblock's single CDEF unit (this decoder has no 128x128
239// SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal
240// read -- reset to `false` at the top of each superblock in the two tile
241// loops, spec `read_cdef`'s `cdef_transmitted[index]`.
242thread_local! {
243 static CDEF_TRANSMITTED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
244}
245// Number of superblock columns in the current tile's grid, so
246// [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into
247// [`CDEF_IDX_GRID`].
248thread_local! {
249 static CDEF_SB_COLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
250}
251// One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select
252// which of the header's `1 << cdef.bits` strength pairs applies to that
253// superblock's samples.
254thread_local! {
255 static CDEF_IDX_GRID: std::cell::RefCell<Vec<u8>> = std::cell::RefCell::new(Vec::new());
256}
257// How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`]
258// has read, across every call on the current thread -- the gate's proof that a
259// `cdef_bits > 0` stream actually reached the new reader rather than every
260// superblock coincidentally being all-skip.
261thread_local! {
262 static CDEF_IDX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
263}
264
265/// Current value of [`CDEF_IDX_HITS`].
266pub(crate) fn cdef_idx_hits() -> usize {
267 CDEF_IDX_HITS.with(|c| c.get())
268}
269
270// lane-realworld r4: this frame's `delta.q_present` (spec 5.9.17) and its
271// actual step (`1 << delta.q_res`, already the real multiplier, not the raw
272// 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a
273// true no-op, matching every existing gate stream's `delta_q_present == 0`
274// behaviour exactly, the same corner-cut [`CDEF_BITS`] takes above.
275thread_local! {
276 static DELTA_Q_PRESENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
277 static DELTA_Q_RES: std::cell::Cell<i32> = const { std::cell::Cell::new(1) };
278}
279// The running quantizer index (spec `CurrentQIndex`, libaom
280// `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the
281// top of every tile (spec `decode_tile`), carried across superblocks within
282// that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the
283// dequantization call sites instead of the frame-constant `base_q_idx`.
284thread_local! {
285 static CURRENT_Q_IDX: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };
286}
287// This frame's own per-plane DC/AC quantizer-index deltas (lane-sbpart r11,
288// spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- frame-constant (not
289// per-superblock like [`CURRENT_Q_IDX`]), set once per frame decode and read
290// back at every dequantization call site keyed on which plane it is doing.
291thread_local! {
292 static QUANT_DELTAS: std::cell::Cell<crate::quant::QuantDeltas> = const {
293 std::cell::Cell::new(crate::quant::QuantDeltas {
294 y_dc: 0,
295 u_dc: 0,
296 u_ac: 0,
297 v_dc: 0,
298 v_ac: 0,
299 })
300 };
301}
302// How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has
303// read, across every call on the current thread -- the gate's proof that a
304// `delta_q_present` stream actually reached the new reader.
305thread_local! {
306 static DELTA_Q_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
307}
308
309/// Current value of [`DELTA_Q_HITS`].
310pub(crate) fn delta_q_hits() -> usize {
311 DELTA_Q_HITS.with(|c| c.get())
312}
313
314/// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 =
315/// Y, 1 = U, 2 = V) -- luma has no coded `ac` delta (spec 5.9.12 never reads
316/// one), so it is always `0` here.
317fn plane_q_delta(plane_idx: usize) -> (i32, i32) {
318 let d = QUANT_DELTAS.with(|c| c.get());
319 match plane_idx {
320 0 => (d.y_dc, 0),
321 1 => (d.u_dc, d.u_ac),
322 _ => (d.v_dc, d.v_ac),
323 }
324}
325
326/// `read_delta_qindex`/`read_delta_q_params` (spec 5.11.10, libaom
327/// `decodemv.c:85-146,735-770`), called right after [`maybe_read_cdef_idx`]
328/// at every block-decode call site (spec order `skip -> cdef -> delta_q`).
329/// A no-op when `delta_q_present` is unset, or when this block is not at the
330/// superblock's own top-left MI position (`b_row == 0 && b_col == 0` in
331/// libaom, collapsed here to a position check since a partition tree's
332/// top-left leaf is the only block that can ever land there), or when that
333/// leaf both *is* the whole superblock and is `skip` (the one case libaom
334/// itself skips the read, state carrying over unchanged).
335fn maybe_read_delta_q(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool) {
336 if !DELTA_Q_PRESENT.with(|c| c.get()) {
337 return;
338 }
339 let sb_mi = sb_mi_cur() as usize;
340 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
341 return;
342 }
343 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
344 // computed against the sequence's own superblock size (lane-sb128b r1:
345 // it used to be hardcoded against 64 and disabled under `sb128`, which a
346 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
347 // wrong).
348 if is_whole_sb && skip {
349 return;
350 }
351 let mut abs = dec.symbol(&mut cdfs.delta_q) as i32;
352 const DELTA_Q_SMALL: i32 = 3;
353 if abs >= DELTA_Q_SMALL {
354 let rem_bits = dec.literal(3) + 1;
355 let thr = (1i32 << rem_bits) + 1;
356 abs = dec.literal(rem_bits) as i32 + thr;
357 }
358 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
359 let reduced = if sign_negative { -abs } else { abs };
360 DELTA_Q_HITS.with(|c| c.set(c.get() + 1));
361 let res = DELTA_Q_RES.with(|c| c.get());
362 CURRENT_Q_IDX.with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));
363}
364
365// lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi`
366// (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`.
367thread_local! {
368 static DELTA_LF_PRESENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
369 static DELTA_LF_RES: std::cell::Cell<i32> = const { std::cell::Cell::new(1) };
370 static DELTA_LF_MULTI: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
371}
372// The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`,
373// `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile,
374// mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever
375// updates index 0 and every reader treats that as the value for all 4
376// indices (spec `read_delta_lf_params`'s own single-cdf branch).
377thread_local! {
378 static CURRENT_DELTA_LF: std::cell::Cell<[i32; 4]> = const { std::cell::Cell::new([0; 4]) };
379}
380// How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has
381// read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`].
382thread_local! {
383 static DELTA_LF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
384}
385
386/// Current value of [`DELTA_LF_HITS`].
387pub(crate) fn delta_lf_hits() -> usize {
388 DELTA_LF_HITS.with(|c| c.get())
389}
390
391/// `read_delta_lflevel`/`read_delta_lf_params` (spec 5.11.11, libaom
392/// `decodemv.c:99-146,735-770`) -- same shape and same call-site gating as
393/// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over
394/// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or
395/// read once into index 0 otherwise.
396fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool) {
397 if !DELTA_LF_PRESENT.with(|c| c.get()) {
398 return;
399 }
400 let sb_mi = sb_mi_cur() as usize;
401 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
402 return;
403 }
404 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
405 // computed against the sequence's own superblock size (lane-sb128b r1:
406 // it used to be hardcoded against 64 and disabled under `sb128`, which a
407 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
408 // wrong).
409 if is_whole_sb && skip {
410 return;
411 }
412 let multi = DELTA_LF_MULTI.with(|c| c.get());
413 let res = DELTA_LF_RES.with(|c| c.get());
414 let count = if multi { 4 } else { 1 };
415 let mut cur = CURRENT_DELTA_LF.with(|c| c.get());
416 for i in 0..count {
417 let mut abs = if multi {
418 dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32
419 } else {
420 dec.symbol(&mut cdfs.delta_lf) as i32
421 };
422 const DELTA_LF_SMALL: i32 = 3;
423 if abs >= DELTA_LF_SMALL {
424 let rem_bits = dec.literal(3) + 1;
425 let thr = (1i32 << rem_bits) + 1;
426 abs = dec.literal(rem_bits) as i32 + thr;
427 }
428 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
429 let reduced = if sign_negative { -abs } else { abs };
430 cur[i] = (cur[i] + reduced * res).clamp(-63, 63);
431 DELTA_LF_HITS.with(|c| c.set(c.get() + 1));
432 }
433 CURRENT_DELTA_LF.with(|c| c.set(cur));
434}
435
436/// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
437/// after `skip` is known at every block-decode call site. A no-op at
438/// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and
439/// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
440/// `allow_intrabc`, so neither needs a separate check here. Reads once per
441/// superblock, at the first non-skip block.
442fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: bool) {
443 let bits = CDEF_BITS.with(|c| c.get());
444 if bits == 0 || skip || CDEF_TRANSMITTED.with(|c| c.get()) {
445 return;
446 }
447 let idx = dec.literal(u32::from(bits)) as u8;
448 CDEF_TRANSMITTED.with(|c| c.set(true));
449 CDEF_IDX_HITS.with(|c| c.set(c.get() + 1));
450 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
451 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
452 if sb_cols > 0 {
453 CDEF_IDX_GRID.with(|g| {
454 let mut g = g.borrow_mut();
455 let i = sb_r * sb_cols + sb_c;
456 if i < g.len() {
457 g[i] = idx;
458 }
459 });
460 }
461}
462
463// ---------------------------------------------------------------------------
464// lane-seg: segmentation. Header (spec 5.9.14) is parsed by `ec-av1-syntax`;
465// this block is the per-block `segment_id` reader (spec 5.11.7-5.11.9) plus
466// the two consumers a real stream exercises: the per-segment quantizer index
467// (spec 7.12.2 `get_qindex`) and the per-segment loop-filter level
468// (spec 7.14.4). Shapes follow libaom `decodemv.c:read_segment_id`/
469// `read_intra_segment_id`/`read_inter_segment_id` and
470// `pred_common.h:av1_get_spatial_seg_pred` -- note libaom returns the SPATIAL
471// PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which
472// is what the oracle every gate here compares against actually does.
473thread_local! {
474 static SEG: std::cell::RefCell<SegmentationParams> =
475 std::cell::RefCell::new(SegmentationParams::default());
476 /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries
477 /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride).
478 static SEG_IDS: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
479 /// `PrevSegmentIds`: the primary reference frame's saved map, empty when
480 /// this frame has no primary reference (spec `load_previous_segment_ids`).
481 static PREV_SEG_IDS: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
482 /// `(mi_rows, mi_cols)` for both maps above.
483 static SEG_MI_DIMS: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
484 /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi
485 /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which
486 /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead.
487 static ABOVE_SEG_PRED: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
488 static LEFT_SEG_PRED: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
489 /// The block currently being decoded -- read back by [`block_q_idx`].
490 static CUR_SEGMENT_ID: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
491 /// The tile's own top-left mi position, for `AvailU`/`AvailL`.
492 static SEG_TILE_ORIGIN: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
493 /// How many real `segment_id` symbols were read, and the set of segment
494 /// ids any block ended up with -- the gate's proof the feature fired.
495 static SEG_ID_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
496 static SEG_IDS_SEEN: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
497 /// How many `seg_id_predicted` symbols were read (temporal update).
498 static SEG_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
499}
500
501/// Installs this frame's segmentation parameters and allocates its map, with
502/// `prev` the primary reference frame's saved map (spec
503/// `load_previous_segment_ids`; `None` for `PRIMARY_REF_NONE` or an empty
504/// slot). Called once per frame, whether or not segmentation is enabled.
505pub(crate) fn set_segmentation(
506 seg: SegmentationParams,
507 mi_rows: usize,
508 mi_cols: usize,
509 prev: Option<&[u8]>,
510) {
511 SEG.with(|s| *s.borrow_mut() = seg);
512 SEG_MI_DIMS.with(|c| c.set((mi_rows, mi_cols)));
513 SEG_IDS.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]);
514 PREV_SEG_IDS.with(|m| {
515 let mut m = m.borrow_mut();
516 m.clear();
517 if let Some(p) = prev {
518 if p.len() == mi_rows * mi_cols {
519 m.extend_from_slice(p);
520 }
521 }
522 });
523 ABOVE_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_cols]);
524 LEFT_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_rows]);
525 CUR_SEGMENT_ID.with(|c| c.set(0));
526}
527
528/// This frame's decoded segment map, to be stored into whichever reference
529/// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`).
530pub(crate) fn take_segment_ids() -> Vec<u8> {
531 SEG_IDS.with(|m| m.borrow().clone())
532}
533
534/// How many `segment_id` symbols have been read (never reset per frame).
535pub(crate) fn segment_id_hits() -> usize {
536 SEG_ID_HITS.with(|c| c.get())
537}
538
539/// How many distinct segment ids any decoded block has carried.
540pub(crate) fn segment_ids_seen() -> usize {
541 SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize)
542}
543
544/// How many `seg_id_predicted` symbols have been read (temporal update).
545pub(crate) fn segment_pred_hits() -> usize {
546 SEG_PRED_HITS.with(|c| c.get())
547}
548
549/// Resets the segmentation hit counters (gate setup).
550pub(crate) fn reset_segment_hits() {
551 SEG_ID_HITS.with(|c| c.set(0));
552 SEG_IDS_SEEN.with(|c| c.set(0));
553 SEG_PRED_HITS.with(|c| c.set(0));
554}
555
556/// `seg_feature_active_idx(segment_id, feature)` for the frame currently
557/// being decoded, with its `FeatureData` value.
558fn seg_feature(segment_id: usize, feature: usize) -> Option<i32> {
559 SEG.with(|s| {
560 let s = s.borrow();
561 s.feature_active(segment_id, feature)
562 .then(|| i32::from(s.feature_data[segment_id][feature]))
563 })
564}
565
566/// `get_qindex(ignoreDeltaQ = 0, segment_id)` (spec 7.12.2, libaom
567/// `av1_get_qindex`) for the block currently being decoded: the running
568/// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data.
569/// Every dequant call site reads the block's quantizer through here.
570fn block_q_idx() -> i32 {
571 let base = CURRENT_Q_IDX.with(|c| c.get());
572 let seg_id = CUR_SEGMENT_ID.with(|c| c.get()) as usize;
573 match seg_feature(seg_id, SEG_LVL_ALT_Q) {
574 Some(data) => (base + data).clamp(0, 255),
575 None => base,
576 }
577}
578
579/// The segment id recorded for one mi cell of the current frame's map.
580fn segment_id_at(mi_r: usize, mi_c: usize) -> u8 {
581 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
582 if mi_r >= mi_rows || mi_c >= mi_cols {
583 return 0;
584 }
585 SEG_IDS.with(|m| m.borrow()[mi_r * mi_cols + mi_c])
586}
587
588/// `set_segment_id`: stamps `id` over every mi cell this block covers.
589fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8) {
590 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
591 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
592 SEG_IDS.with(|m| {
593 let mut m = m.borrow_mut();
594 for y in 0..y_mis {
595 for x in 0..x_mis {
596 m[(mi_r + y) * mi_cols + mi_c + x] = id;
597 }
598 }
599 });
600 CUR_SEGMENT_ID.with(|c| c.set(id));
601 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
602}
603
604/// `get_predicted_segment_id` (libaom `dec_get_segment_id` over
605/// `last_frame_seg_map`): the minimum previous-frame segment id over the
606/// block's own mi footprint. `0` when there is no previous map.
607fn predicted_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize) -> u8 {
608 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
609 PREV_SEG_IDS.with(|m| {
610 let m = m.borrow();
611 if m.is_empty() {
612 return 0;
613 }
614 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
615 let mut id = u8::MAX;
616 for y in 0..y_mis {
617 for x in 0..x_mis {
618 id = id.min(m[(mi_r + y) * mi_cols + mi_c + x]);
619 }
620 }
621 if id == u8::MAX { 0 } else { id }
622 })
623}
624
625/// `av1_neg_deinterleave` (libaom `decodemv.c:258`).
626fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 {
627 if reference == 0 {
628 return diff;
629 }
630 if reference >= max - 1 {
631 return max - diff - 1;
632 }
633 let half = if 2 * reference < max {
634 diff <= 2 * reference
635 } else {
636 diff <= 2 * (max - reference - 1)
637 };
638 if half {
639 return if diff & 1 != 0 {
640 reference + ((diff + 1) >> 1)
641 } else {
642 reference - (diff >> 1)
643 };
644 }
645 if 2 * reference < max { diff } else { max - (diff + 1) }
646}
647
648/// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current
649/// frame's already-decoded above/left/above-left neighbours.
650fn spatial_seg_pred(mi_r: usize, mi_c: usize) -> (i32, usize) {
651 let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());
652 let (avail_u, avail_l) = (mi_r > row0, mi_c > col0);
653 let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1)));
654 let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c)));
655 let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1)));
656 let ctx = match prev_ul {
657 None => 0,
658 Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2,
659 Some(ul) if Some(ul) == prev_u || Some(ul) == prev_l || prev_u == prev_l => 1,
660 Some(_) => 0,
661 };
662 let pred = match (prev_u, prev_l) {
663 (None, l) => l.unwrap_or(0),
664 (Some(u), None) => u,
665 (Some(u), Some(l)) => {
666 if prev_ul == Some(u) {
667 u
668 } else {
669 l
670 }
671 }
672 };
673 (pred, ctx)
674}
675
676/// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id
677/// when `skip`, otherwise one `segment_id` symbol de-interleaved against
678/// that prediction. Does NOT write the map -- callers do.
679fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, skip: bool) -> u8 {
680 let (pred, ctx) = spatial_seg_pred(mi_r, mi_c);
681 if skip {
682 return pred as u8;
683 }
684 let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32;
685 SEG_ID_HITS.with(|c| c.set(c.get() + 1));
686 let last_active = SEG.with(|s| i32::from(s.borrow().last_active_seg_id));
687 neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active) as u8
688}
689
690/// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block
691/// -- once before `skip` when `SegIdPreSkip`, once after it otherwise (the
692/// caller decides which by passing `pre_skip`).
693fn intra_segment_id(
694 dec: &mut SymbolDecoder,
695 cdfs: &mut Cdfs,
696 mi_r: usize,
697 mi_c: usize,
698 w_mi: usize,
699 h_mi: usize,
700 skip: bool,
701) {
702 if !SEG.with(|s| s.borrow().enabled) {
703 return;
704 }
705 let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip);
706 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
707}
708
709/// Whether this frame's intra blocks read their `segment_id` before `skip`
710/// (`SegIdPreSkip`); `false` also when segmentation is off.
711fn seg_id_pre_skip() -> bool {
712 SEG.with(|s| {
713 let s = s.borrow();
714 s.enabled && s.seg_id_pre_skip
715 })
716}
717
718/// `read_inter_segment_id(preskip)` (spec 5.11.9, libaom `decodemv.c:352`).
719/// Called at both spec positions of an inter frame's block: `pre_skip = true`
720/// before `skip_mode`/`skip`, and `pre_skip = false` after them.
721fn inter_segment_id(
722 dec: &mut SymbolDecoder,
723 cdfs: &mut Cdfs,
724 mi_r: usize,
725 mi_c: usize,
726 w_mi: usize,
727 h_mi: usize,
728 skip: bool,
729 pre_skip: bool,
730) {
731 let (enabled, update_map, temporal_update, pre_skip_frame) = SEG.with(|s| {
732 let s = s.borrow();
733 (s.enabled, s.update_map, s.temporal_update, s.seg_id_pre_skip)
734 });
735 if !enabled {
736 return;
737 }
738 if !update_map {
739 // The map is inherited wholesale from the previous frame.
740 let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi);
741 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
742 return;
743 }
744 if pre_skip && !pre_skip_frame {
745 return;
746 }
747 if !pre_skip && skip {
748 // libaom: a skipped block never codes `seg_id_predicted`, and its
749 // segment id is the spatial prediction.
750 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0);
751 let id = read_segment_id(dec, cdfs, mi_r, mi_c, true);
752 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
753 return;
754 }
755 let id = if temporal_update {
756 let ctx = seg_pred_ctx(mi_r, mi_c);
757 let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0;
758 SEG_PRED_HITS.with(|c| c.set(c.get() + 1));
759 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted));
760 if predicted {
761 predicted_segment_id(mi_r, mi_c, w_mi, h_mi)
762 } else {
763 read_segment_id(dec, cdfs, mi_r, mi_c, false)
764 }
765 } else {
766 read_segment_id(dec, cdfs, mi_r, mi_c, false)
767 };
768 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
769}
770
771/// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags.
772fn seg_pred_ctx(mi_r: usize, mi_c: usize) -> usize {
773 // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and
774 // so contribute 0) outside the tile -- the availability check here is
775 // what keeps a previous tile's stamps out of this tile's context.
776 let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());
777 let above = if mi_r > row0 {
778 ABOVE_SEG_PRED.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))
779 } else {
780 0
781 };
782 let left = if mi_c > col0 {
783 LEFT_SEG_PRED.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))
784 } else {
785 0
786 };
787 usize::from(above + left)
788}
789
790/// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update.
791fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8) {
792 ABOVE_SEG_PRED.with(|m| {
793 let mut m = m.borrow_mut();
794 for i in 0..w_mi {
795 if let Some(cell) = m.get_mut(mi_c + i) {
796 *cell = value;
797 }
798 }
799 });
800 LEFT_SEG_PRED.with(|m| {
801 let mut m = m.borrow_mut();
802 for i in 0..h_mi {
803 if let Some(cell) = m.get_mut(mi_r + i) {
804 *cell = value;
805 }
806 }
807 });
808}
809
810// How many key-frame luma blocks resolved `smooth_neighbor` (spec
811// `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after
812// counter, proving a stream actually put a directional block next to a
813// smooth-predicted neighbour rather than every block reading the (previously
814// hardcoded `false`) edge-filter strength bucket unchanged.
815thread_local! {
816 static SMOOTH_LUMA_HITS: std::cell::Cell<usize> =
817 const { std::cell::Cell::new(0) };
818}
819
820/// Current value of [`SMOOTH_LUMA_HITS`].
821pub(crate) fn smooth_luma_hits() -> usize {
822 SMOOTH_LUMA_HITS.with(|c| c.get())
823}
824
825thread_local! {
826 /// lane-band46 r1: how many split-transform units answered their intra
827 /// reach DIFFERENTLY under libaom's per-unit rules ([`Reach::of_tu`], the
828 /// palette2 r12 fix) than the standalone-block lookup this decoder used to
829 /// apply to them (class reach-is-per-transform-unit). Every hit is a
830 /// transform unit whose above-right / below-left reference samples would
831 /// be wrong without that fix.
832 static SPLIT_TU_REACH_FIX_HITS: std::cell::Cell<usize> =
833 const { std::cell::Cell::new(0) };
834}
835
836/// Current value of [`SPLIT_TU_REACH_FIX_HITS`].
837pub(crate) fn split_tu_reach_fix_hits() -> usize {
838 SPLIT_TU_REACH_FIX_HITS.with(|c| c.get())
839}
840
841/// [`Reach::of_tu`] for one transform unit, counting how often that per-unit
842/// answer differs from the standalone-block answer the call sites used before
843/// lane-palette2 r12 -- the counter a gate asserts on to prove a stream really
844/// exercised the fix. `col_off`/`row_off` are in SAMPLES from the parent
845/// block's top-left `(px, py)`.
846#[allow(clippy::too_many_arguments)]
847fn tu_reach(
848 bw: usize,
849 bh: usize,
850 col_off: usize,
851 row_off: usize,
852 tx: usize,
853 block: Reach,
854 px: usize,
855 py: usize,
856 width: usize,
857 height: usize,
858) -> Reach {
859 let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block);
860 let standalone = Reach::of(tx, px + col_off, py + row_off, width, height);
861 if fixed != standalone {
862 SPLIT_TU_REACH_FIX_HITS.with(|c| c.set(c.get() + 1));
863 }
864 fixed
865}
866
867// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12),
868// across every call on the current thread -- lane-chroma r3's own before/after
869// counter, proving a stream actually exercised chroma's smooth/paeth
870// predictor (the previously-refused round-2 gap) rather than every block
871// landing on DC/CFL/directional.
872thread_local! {
873 static SMOOTH_UV_HITS: std::cell::Cell<usize> =
874 const { std::cell::Cell::new(0) };
875}
876
877/// Current value of [`SMOOTH_UV_HITS`].
878pub(crate) fn smooth_uv_hits() -> usize {
879 SMOOTH_UV_HITS.with(|c| c.get())
880}
881
882// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a
883// full superblock walk over, across every call on the current thread --
884// lane-tiles r2's own gate-blind-to-feature guard: a gate over a
885// multi-tile stream must prove more than one tile actually fired, not just
886// that the stream carried tile_info.cols > 1.
887thread_local! {
888 static TILE_HITS: std::cell::Cell<usize> =
889 const { std::cell::Cell::new(0) };
890}
891/// Current value of [`TILE_HITS`].
892pub(crate) fn tile_hits() -> usize {
893 TILE_HITS.with(|c| c.get())
894}
895
896// How many 4-pixel deblocking edge groups [`edge_params`] has actually
897// selected for filtering, across every call on the current thread -- the same
898// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
899// exercised `apply_deblock` rather than every edge landing on level 0.
900thread_local! {
901 static DEBLOCK_HITS: std::cell::Cell<usize> =
902 const { std::cell::Cell::new(0) };
903}
904/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
905/// mirroring stream.rs's `pictures_decoded` so the two dumps index
906/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
907static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize =
908 std::sync::atomic::AtomicUsize::new(0);
909
910/// Current value of [`DEBLOCK_HITS`].
911pub(crate) fn deblock_hits() -> usize {
912 DEBLOCK_HITS.with(|c| c.get())
913}
914
915// lane-defon r1: how many COMPOUND_REFERENCE blocks read a
916// `UNIDIR_COMP_REFERENCE` pair (both references on the same temporal side,
917// spec 5.11.25 `comp_reference_type == 0`) -- the gate's proof that a
918// stream built with `--enable-onesided-comp=1` really exercised the
919// `uni_comp_ref` alphabet rather than only bidirectional pairs.
920thread_local! {
921 static UNI_COMP_HITS: std::cell::Cell<usize> =
922 const { std::cell::Cell::new(0) };
923}
924
925/// Current value of [`UNI_COMP_HITS`].
926pub(crate) fn uni_comp_hits() -> usize {
927 UNI_COMP_HITS.with(|c| c.get())
928}
929
930// lane-defon r1: how many blocks blended through a `COMPOUND_DIFFWTD` mask
931// (`mc::diffwtd_mask`) -- the narrower half of `MASKED_COMPOUND_HITS`, the
932// gate's proof that `--enable-diff-wtd-comp=1` reached the difference-weighted
933// blend and not only the wedge arm.
934thread_local! {
935 static DIFFWTD_HITS: std::cell::Cell<usize> =
936 const { std::cell::Cell::new(0) };
937}
938
939/// Current value of [`DIFFWTD_HITS`].
940pub(crate) fn diffwtd_hits() -> usize {
941 DIFFWTD_HITS.with(|c| c.get())
942}
943
944// lane-mcomp64 r1: how many blocks took the INFERRED `COMPOUND_DIFFWTD` arm --
945// a block size where `av1_is_wedge_used` is false (64x64 is the only such size
946// this decoder's square inter path reaches), so no `compound_type` symbol is
947// coded at all. Strictly narrower than `DIFFWTD_HITS`, which also counts the
948// coded-symbol DIFFWTD blocks at 8x8/16x16/32x32.
949thread_local! {
950 static DIFFWTD_INFERRED_HITS: std::cell::Cell<usize> =
951 const { std::cell::Cell::new(0) };
952}
953
954/// Current value of [`DIFFWTD_INFERRED_HITS`].
955pub(crate) fn diffwtd_inferred_hits() -> usize {
956 DIFFWTD_INFERRED_HITS.with(|c| c.get())
957}
958
959// lane-defon r1: how many FORWARD KEYFRAMES were decoded -- a KEY frame coded
960// with `show_frame == 0`, output later by a `show_existing_frame` header
961// (aomenc `--enable-fwd-kf=1 --fwd-kf-dist=N`). Counted from
962// `stream::decode_stream`, which is where the frame header is consumed; the
963// gate's proof that the on-value really reached the bitstream rather than
964// being dropped by the rate control.
965thread_local! {
966 static FWD_KF_HITS: std::cell::Cell<usize> =
967 const { std::cell::Cell::new(0) };
968}
969
970/// Current value of [`FWD_KF_HITS`].
971pub(crate) fn fwd_kf_hits() -> usize {
972 FWD_KF_HITS.with(|c| c.get())
973}
974
975/// Records one decoded forward keyframe (see [`FWD_KF_HITS`]).
976pub(crate) fn note_fwd_kf() {
977 FWD_KF_HITS.with(|c| c.set(c.get() + 1));
978}
979
980// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
981// the block's own side, across every call on the current thread -- the same
982// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
983// actually exercised a *split* transform under `TxMode::Select` rather than
984// every block coincidentally resolving `depth=0` (indistinguishable from
985// `TxMode::Largest` pixel-wise).
986thread_local! {
987 static TX_DEPTH_HITS: std::cell::Cell<usize> =
988 const { std::cell::Cell::new(0) };
989}
990
991// How many plain SQUARE intra blocks (lane-sqchroma r1) resolved a luma
992// transform smaller than their own side (`tx_depth != 0`) while coding a
993// chroma prediction other than `DC_PRED` -- the pair the square path's chroma
994// only exercises with aomenc's tx-size search left ON (its default), which
995// every older recipe in this file pins off. Counted at the block, so a stream
996// where RD happened to give every split-transform block a DC chroma mode
997// reads as zero rather than silently passing for free.
998thread_local! {
999 static SQ_CHROMA_TX_HITS: std::cell::Cell<usize> =
1000 const { std::cell::Cell::new(0) };
1001}
1002
1003/// Current value of [`SQ_CHROMA_TX_HITS`].
1004pub(crate) fn sq_chroma_tx_hits() -> usize {
1005 SQ_CHROMA_TX_HITS.with(|c| c.get())
1006}
1007
1008/// Current value of [`TX_DEPTH_HITS`].
1009pub(crate) fn tx_depth_hits() -> usize {
1010 TX_DEPTH_HITS.with(|c| c.get())
1011}
1012
1013// lane-txselect: how many `txfm_split` symbols an inter frame's var-tx tree
1014// read, and how many of those actually took the split, on the current thread
1015// -- the same before/after counter pattern as [`TX_DEPTH_HITS`], proving a
1016// stream exercised spec 5.11.17's `read_var_tx_size` rather than every block
1017// coincidentally coding one whole-block transform.
1018thread_local! {
1019 static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1020 static TXFM_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1021 // lane-inter4 r2: rectangular INTER residual coding -- how many rect
1022 // strips coded one whole-block rect transform unit, and how many split
1023 // their rect max transform into square sub-transforms.
1024 static RECT_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1025 static RECT_INTER_TXSPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1026 // lane-r14 r2: luma transform units of an inter strip with a 64-px axis
1027 // (64x32/32x64/64x16/16x64), whose coefficients are coded as the
1028 // truncated low-32 corner.
1029 static RECT64_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1030 // lane-rectres r1: whole-block luma transform units of a 32x32-level 1:4
1031 // inter strip, `[32x8, 8x32]`.
1032 static RECT32X8_INTER_TU_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1033 // lane-r14 r3: rectangular var-tx LEAVES, [32x16, 16x32].
1034 static VARTX_RECT_LEAF_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1035 // lane-inter16ab r4: rectangular var-tx leaves with a 4-px axis, [8x4, 4x8]
1036 // -- the `sub_tx_size_map[TX_16X4]` split leaves of a 16x16-level 1:4 strip.
1037 static VARTX_RECT_LEAF4_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1038 // lane-inter4 r3: 16x16-level PARTITION_HORZ / PARTITION_VERT on an inter
1039 // frame -- 16x8 and 8x16 inter leaves.
1040 static INTER_LEAF16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1041 static INTER_LEAF16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1042 // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits,
1043 // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] --
1044 // `decode_inter_block` already carries forty parameters and both are
1045 // frame-constant.
1046 static TX_SELECT_INTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1047 static REDUCED_TX_SET_INTER: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
1048 // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit,
1049 // frame-constant like the two above and stashed the same way -- an intra
1050 // block inside an inter frame reads `use_filter_intra` under it.
1051 static ENABLE_FILTER_INTRA_INTER: std::cell::Cell<bool> =
1052 const { std::cell::Cell::new(false) };
1053}
1054
1055/// Current value of [`TXFM_SPLIT_READS`].
1056pub(crate) fn txfm_split_reads() -> usize {
1057 TXFM_SPLIT_READS.with(|c| c.get())
1058}
1059
1060/// Current value of [`TXFM_SPLIT_HITS`].
1061pub(crate) fn txfm_split_hits() -> usize {
1062 TXFM_SPLIT_HITS.with(|c| c.get())
1063}
1064
1065/// Current value of [`INTER_LEAF16_HORZ_HITS`] (lane-inter4 r3).
1066pub(crate) fn inter_leaf16_horz_hits() -> usize {
1067 INTER_LEAF16_HORZ_HITS.with(|c| c.get())
1068}
1069
1070/// Current value of [`INTER_LEAF16_VERT_HITS`] (lane-inter4 r3).
1071pub(crate) fn inter_leaf16_vert_hits() -> usize {
1072 INTER_LEAF16_VERT_HITS.with(|c| c.get())
1073}
1074
1075/// Current value of [`RECT_INTER_TU_HITS`] (lane-inter4 r2).
1076pub(crate) fn rect_inter_tu_hits() -> usize {
1077 RECT_INTER_TU_HITS.with(|c| c.get())
1078}
1079
1080/// Current value of [`RECT_INTER_TXSPLIT_HITS`] (lane-inter4 r2).
1081pub(crate) fn rect_inter_txsplit_hits() -> usize {
1082 RECT_INTER_TXSPLIT_HITS.with(|c| c.get())
1083}
1084
1085/// Current value of [`RECT64_INTER_TU_HITS`] (lane-r14 r2).
1086pub(crate) fn rect64_inter_tu_hits() -> usize {
1087 RECT64_INTER_TU_HITS.with(|c| c.get())
1088}
1089
1090/// Current value of [`RECT32X8_INTER_TU_HITS`] (lane-rectres r1): `[32x8, 8x32]`
1091/// whole-block luma units of a 32x32-level 1:4 inter strip.
1092pub(crate) fn rect32x8_inter_tu_hits() -> [usize; 2] {
1093 RECT32X8_INTER_TU_HITS.with(|c| c.get())
1094}
1095
1096/// Current value of [`VARTX_RECT_LEAF_HITS`] (lane-r14 r3): how many
1097/// rectangular var-tx leaf transform units were coded, `[32x16, 16x32]`.
1098pub(crate) fn vartx_rect_leaf_hits() -> [usize; 2] {
1099 VARTX_RECT_LEAF_HITS.with(|c| c.get())
1100}
1101
1102/// Current value of [`VARTX_RECT_LEAF4_HITS`] (lane-inter16ab r4): 8x4/4x8
1103/// split leaves of a 16x4/4x16 strip, `[8x4, 4x8]`.
1104pub(crate) fn vartx_rect_leaf4_hits() -> [usize; 2] {
1105 VARTX_RECT_LEAF4_HITS.with(|c| c.get())
1106}
1107
1108/// Records one rectangular var-tx leaf.
1109fn vartx_rect_leaf_hit(tw: usize, th: usize) {
1110 if std::env::var_os("EC_VARTXLEAF").is_some() {
1111 eprintln!("EC_VARTXLEAF tw={tw} th={th}");
1112 }
1113 let cell = if tw.min(th) == 4 { &VARTX_RECT_LEAF4_HITS } else { &VARTX_RECT_LEAF_HITS };
1114 cell.with(|c| {
1115 let mut h = c.get();
1116 h[usize::from(th > tw)] += 1;
1117 c.set(h);
1118 });
1119}
1120
1121/// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/
1122/// [`ENABLE_FILTER_INTRA_INTER`].
1123pub(crate) fn set_inter_tx_mode(
1124 tx_select: bool,
1125 reduced_tx_set: bool,
1126 enable_filter_intra: bool,
1127) {
1128 TX_SELECT_INTER.with(|c| c.set(tx_select));
1129 REDUCED_TX_SET_INTER.with(|c| c.set(reduced_tx_set));
1130 ENABLE_FILTER_INTRA_INTER.with(|c| c.set(enable_filter_intra));
1131}
1132
1133// How many `partition_w16` reads (a 16x16 block's own partition symbol, key
1134// intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a
1135// plain default-settings aomenc run over lavfi mandelbrot hits this arm on
1136// frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not
1137// the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real
1138// `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`,
1139// chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8
1140// path above).
1141thread_local! {
1142 static VERT_B_INTRA_HITS: std::cell::Cell<usize> =
1143 const { std::cell::Cell::new(0) };
1144}
1145
1146/// Current value of [`VERT_B_INTRA_HITS`].
1147pub(crate) fn vert_b_intra_hits() -> usize {
1148 VERT_B_INTRA_HITS.with(|c| c.get())
1149}
1150
1151// lane-ab16 r1: how many 16x16-level AB partitions fired, per arm, in
1152// `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order. Each arm is two
1153// 8x8 squares (`decode_leaf8`) plus one 16x8/8x16 strip (`decode_leaf_rect`,
1154// the non-skip coefficient path lane-rectx proved); the gate hard-asserts
1155// every arm separately so a run where aomenc's RD only picked one cannot
1156// pass as proof of four.
1157thread_local! {
1158 static AB16_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
1159}
1160
1161/// [`AB16_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16).
1162thread_local! {
1163 /// 4x4 transform units decoded inside an 8x8 square of a
1164 /// `PARTITION_VERT_A`/`_B` -- the exact call that panicked before
1165 /// [`crate::encode::Reach::of_tu`] (lane-ab16 r2), so the gate can prove
1166 /// a real `--enable-tx-size-search=1` stream reaches it.
1167 static VERT_AB_TX4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1168}
1169
1170pub(crate) fn vert_ab_tx4_hits() -> usize {
1171 VERT_AB_TX4_HITS.with(std::cell::Cell::get)
1172}
1173
1174pub(crate) fn ab16_hits_by_arm() -> [usize; 4] {
1175 AB16_HITS.with(std::cell::Cell::get)
1176}
1177
1178fn bump_ab16(arm: usize) {
1179 AB16_HITS.with(|c| {
1180 let mut v = c.get();
1181 v[arm] += 1;
1182 c.set(v);
1183 });
1184}
1185
1186// How many `partition_w16` reads resolved to a plain `PARTITION_HORZ`/
1187// `PARTITION_VERT` (lane-rect16 r2): re-measuring after the VERT_B fix above
1188// showed mandelbrot's real first-hit blocker is this plain arm at mi=(0,7),
1189// not VERT_B (`refusal-names-a-correlate`; the VERT_B write-up's "frame 0's
1190// very first non-NONE/SPLIT symbol" claim was about decode ORDER within one
1191// superblock's z-order recursion, not raster mi position).
1192thread_local! {
1193 static HORZ_VERT_INTRA_HITS: std::cell::Cell<usize> =
1194 const { std::cell::Cell::new(0) };
1195}
1196
1197/// Current value of [`HORZ_VERT_INTRA_HITS`].
1198pub(crate) fn horz_vert_intra_hits() -> usize {
1199 HORZ_VERT_INTRA_HITS.with(|c| c.get())
1200}
1201
1202// How many blocks were decoded as a frame-edge rect strip -- the single
1203// coded half of a `PARTITION_HORZ`/`PARTITION_VERT` at the true frame edge
1204// (lane-oddh r1), i.e. a block living inside the 8px band of a frame whose
1205// height or width is 8 mod 16 (the user's 3840x1608 film). Intra and inter
1206// paths share the counter.
1207thread_local! {
1208 static EDGE_RECT_STRIP_HITS: std::cell::Cell<usize> =
1209 const { std::cell::Cell::new(0) };
1210}
1211
1212/// Current value of [`EDGE_RECT_STRIP_HITS`].
1213pub(crate) fn edge_rect_strip_hits() -> usize {
1214 EDGE_RECT_STRIP_HITS.with(|c| c.get())
1215}
1216
1217// lane-interedge r1: frame-edge half strips on the INTER path, per partition
1218// level (64/32/16) x axis (HORZ at a bottom edge, VERT at a right edge). The
1219// index is `level_idx * 2 + axis` with `level_idx` 0=64, 1=32, 2=16 and
1220// `axis` 0=HORZ (`!has_rows`), 1=VERT (`!has_cols`). Both of the user's films
1221// are height mod 16 == 8, so every inter frame crosses these nodes.
1222thread_local! {
1223 static INTER_EDGE_STRIP_HITS: std::cell::Cell<[usize; 6]> =
1224 const { std::cell::Cell::new([0; 6]) };
1225}
1226
1227/// Bumps one bucket of [`INTER_EDGE_STRIP_HITS`].
1228pub(crate) fn bump_inter_edge_strip(idx: usize) {
1229 INTER_EDGE_STRIP_HITS.with(|c| {
1230 let mut v = c.get();
1231 v[idx] += 1;
1232 c.set(v);
1233 });
1234}
1235
1236// lane-edgeboth r1: how many partition nodes were coded as the BOTH-AXES-CUT
1237// forced split -- libaom `decode_partition` (decodeframe.c):
1238// `else if (!has_rows && !has_cols) partition = PARTITION_SPLIT;`, the one
1239// straddle case that reads NO symbol at all. Indexed by level:
1240// 0 = 16x16, 1 = 32x32, 2 = 64x64, 3 = 128x128; intra and inter share it.
1241thread_local! {
1242 static EDGE_BOTH_CUT_HITS: std::cell::Cell<[usize; 4]> =
1243 const { std::cell::Cell::new([0; 4]) };
1244}
1245
1246fn bump_edge_both_cut(level: usize) {
1247 EDGE_BOTH_CUT_HITS.with(|c| {
1248 let mut v = c.get();
1249 v[level] += 1;
1250 c.set(v);
1251 });
1252}
1253
1254/// Current value of [`INTER_EDGE_STRIP_HITS`] (`[h64, v64, h32, v32, h16, v16]`).
1255pub fn inter_edge_strip_hits() -> [usize; 6] {
1256 INTER_EDGE_STRIP_HITS.with(|c| c.get())
1257}
1258
1259/// Resets [`INTER_EDGE_STRIP_HITS`] -- a refused attempt must not carry hits
1260/// into the next one (class `counter-from-refused-stream`).
1261pub fn reset_inter_edge_strip_hits() {
1262 INTER_EDGE_STRIP_HITS.with(|c| c.set([0; 6]));
1263}
1264
1265/// Current value of [`EDGE_BOTH_CUT_HITS`] (`[16, 32, 64, 128]` levels).
1266pub(crate) fn edge_both_cut_hits() -> [usize; 4] {
1267 EDGE_BOTH_CUT_HITS.with(|c| c.get())
1268}
1269
1270/// Zeroes [`EDGE_BOTH_CUT_HITS`] so a gate can measure a per-attempt delta.
1271pub(crate) fn reset_edge_both_cut_hits() {
1272 EDGE_BOTH_CUT_HITS.with(|c| c.set([0; 4]));
1273}
1274
1275// How many HORZ/VERT intra strips resolved a SPLIT luma transform
1276// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) --
1277// the case every rect path here refused by name before, and the first
1278// refusal the user's ReelB extract (600s in) stops at.
1279thread_local! {
1280 static RECT_SPLIT_TX_HITS: std::cell::Cell<usize> =
1281 const { std::cell::Cell::new(0) };
1282}
1283
1284/// Current value of [`RECT_SPLIT_TX_HITS`].
1285pub(crate) fn rect_split_tx_hits() -> usize {
1286 RECT_SPLIT_TX_HITS.with(|c| c.get())
1287}
1288
1289// The subset of [`RECT_SPLIT_TX_HITS`] that is BOTH superblock-level (one
1290// side 64) AND split past the first depth, i.e. tiled more than one unit in
1291// each axis -- the only shape with a transform unit that has neighbours on
1292// two sides inside its own strip (`row_off > 0 && col_off > 0`), and the one
1293// no gate fired before lane-rectsplit r2 (the shared counter above also
1294// counts 32x32-level and depth-1 strips, so it cannot prove this case).
1295thread_local! {
1296 static RECT_SPLIT_SB_INTERIOR_TU_HITS: std::cell::Cell<usize> =
1297 const { std::cell::Cell::new(0) };
1298}
1299
1300/// Current value of [`RECT_SPLIT_SB_INTERIOR_TU_HITS`].
1301pub(crate) fn rect_split_sb_interior_tu_hits() -> usize {
1302 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.get())
1303}
1304
1305// Per-shape hit counts for the rect chroma transforms lane-rectchroma r1
1306// wired into [`decode_rect_split`] -- the shapes a split-transform strip's
1307// chroma half takes that had no coefficient tables before (index order:
1308// 32x8, 8x32, 8x4, 4x8). One counter per shape because a gate that only
1309// proves the pair it happens to hit cannot catch a transposed scan/context
1310// table (class scan-weights-cross-axis).
1311thread_local! {
1312 static RECT_SPLIT_CHROMA_SHAPE_HITS: std::cell::Cell<[usize; 4]> =
1313 const { std::cell::Cell::new([0; 4]) };
1314}
1315
1316/// Current value of [`RECT_SPLIT_CHROMA_SHAPE_HITS`] (32x8, 8x32, 8x4, 4x8).
1317pub(crate) fn rect_split_chroma_shape_hits() -> [usize; 4] {
1318 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| c.get())
1319}
1320
1321// How many HORZ/VERT intra strips actually predicted with filter intra
1322// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name
1323// ("this decoder predicts square-only") until `predict_filter_intra` took
1324// `bw`x`bh`.
1325thread_local! {
1326 static FILTER_INTRA_RECT_HITS: std::cell::Cell<usize> =
1327 const { std::cell::Cell::new(0) };
1328}
1329
1330/// Current value of [`FILTER_INTRA_RECT_HITS`].
1331pub(crate) fn filter_intra_rect_hits() -> usize {
1332 FILTER_INTRA_RECT_HITS.with(|c| c.get())
1333}
1334
1335// As [`FILTER_INTRA_RECT_HITS`], counting only the 32x32-level 1:4 strips
1336// (32x8/8x32, lane-fi32x8 r1) -- the shapes whose `use_filter_intra` symbol
1337// was never read at all before that round, so a gate needs to prove the flag
1338// fired at THAT shape and not at a 16x8 one somewhere else in the frame.
1339// Split by ORIENTATION: rows 8 (32x8) and 9 (8x32) of `cdf::FILTER_INTRA`
1340// carry different probabilities (18101 vs 20229), so a transposed pair is
1341// only caught by a gate that sees the flag fire on BOTH shapes (class
1342// scan-weights-cross-axis).
1343thread_local! {
1344 static FILTER_INTRA_RECT4_HORZ_HITS: std::cell::Cell<usize> =
1345 const { std::cell::Cell::new(0) };
1346 static FILTER_INTRA_RECT4_VERT_HITS: std::cell::Cell<usize> =
1347 const { std::cell::Cell::new(0) };
1348}
1349
1350/// Current value of [`FILTER_INTRA_RECT4_HORZ_HITS`] (32x8 strips).
1351pub(crate) fn filter_intra_rect4_horz_hits() -> usize {
1352 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.get())
1353}
1354
1355/// Current value of [`FILTER_INTRA_RECT4_VERT_HITS`] (8x32 strips).
1356pub(crate) fn filter_intra_rect4_vert_hits() -> usize {
1357 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.get())
1358}
1359
1360// How many rectangular transform units actually coded coefficients through
1361// [`read_coeffs_rect`] (`all_zero == 0`) -- lane-rect1d's measure that a gate
1362// exercised the rect coefficient reader at all rather than passing on
1363// all-skip blocks.
1364thread_local! {
1365 static RECT_COEFF_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1366 static RECT_CLASS1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1367}
1368
1369/// Current value of [`RECT_COEFF_TU_HITS`].
1370pub(crate) fn rect_coeff_tu_hits() -> usize {
1371 RECT_COEFF_TU_HITS.with(|c| c.get())
1372}
1373
1374/// Rectangular transform units whose resolved `tx_type` is a 1D class
1375/// (`V_DCT`/`H_DCT`) -- [`TX_CLASS1_HITS`]'s rect-only half, so a gate can
1376/// pin that the 1D-class-on-a-RECT-transform path fired rather than settling
1377/// for the square reader's own 1D types.
1378pub(crate) fn rect_class1_hits() -> usize {
1379 RECT_CLASS1_HITS.with(|c| c.get())
1380}
1381
1382// As [`FILTER_INTRA_RECT_HITS`], counting only the strips BELOW 16x16
1383// (8x16/16x8 leaves of a 16x16 HORZ/VERT partition, lane-fistrip r1) -- the
1384// shapes whose `use_filter_intra` symbol had no CDF class before this round.
1385// A gate asserting the wider counter would be satisfied by a 32x16 strip and
1386// prove nothing about the new shapes.
1387thread_local! {
1388 static FILTER_INTRA_RECT_SUB16_HITS: std::cell::Cell<usize> =
1389 const { std::cell::Cell::new(0) };
1390}
1391
1392/// Current value of [`FILTER_INTRA_RECT_SUB16_HITS`].
1393pub(crate) fn filter_intra_rect_sub16_hits() -> usize {
1394 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.get())
1395}
1396
1397// As [`FILTER_INTRA_RECT_SUB16_HITS`], one partition level further down:
1398// 4x8/8x4 leaves of an 8x8 HORZ/VERT (lane-fi8 r1). A gate on the sub16
1399// counter would be satisfied by a 16x8 strip and prove nothing here.
1400thread_local! {
1401 static FILTER_INTRA_RECT_SUB8_HITS: std::cell::Cell<usize> =
1402 const { std::cell::Cell::new(0) };
1403}
1404
1405/// Current value of [`FILTER_INTRA_RECT_SUB8_HITS`].
1406pub(crate) fn filter_intra_rect_sub8_hits() -> usize {
1407 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.get())
1408}
1409
1410// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
1411// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
1412// call on the current thread -- the same before/after counter pattern as
1413// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
1414// `eob_pt`/1D-neighbour context path rather than every block coincidentally
1415// landing on `DCT_DCT`.
1416thread_local! {
1417 static TX_CLASS1_HITS: std::cell::Cell<usize> =
1418 const { std::cell::Cell::new(0) };
1419}
1420
1421// How many `uv_mode` reads resolved to a directional chroma mode (neither
1422// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
1423// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1424// actually exercised chroma's own directional predictor.
1425thread_local! {
1426 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
1427 const { std::cell::Cell::new(0) };
1428}
1429
1430/// Current value of [`DIRECTIONAL_UV_HITS`].
1431pub(crate) fn directional_uv_hits() -> usize {
1432 DIRECTIONAL_UV_HITS.with(|c| c.get())
1433}
1434
1435// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
1436// something other than [`ANGLE_DELTA_ZERO`], across every call in the
1437// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
1438// proving a stream actually exercised a nonzero angle delta.
1439thread_local! {
1440 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
1441 const { std::cell::Cell::new(0) };
1442}
1443
1444// How many [`read_single_ref`] reads resolved to a reference other than
1445// `LAST_FRAME`, across every call on the current thread -- the same before/after
1446// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1447// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
1448// only other supported one so far) rather than every block coincidentally
1449// resolving `LAST_FRAME`.
1450thread_local! {
1451 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
1452 const { std::cell::Cell::new(0) };
1453}
1454
1455/// Current value of [`NON_LAST_REF_HITS`].
1456pub(crate) fn non_last_ref_hits() -> usize {
1457 NON_LAST_REF_HITS.with(|c| c.get())
1458}
1459
1460// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
1461// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
1462// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
1463// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
1464// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
1465// `GOLDEN_FRAME` draw it did not ask for.
1466thread_local! {
1467 static LAST2_HITS: std::cell::Cell<usize> =
1468 const { std::cell::Cell::new(0) };
1469}
1470thread_local! {
1471 static LAST3_HITS: std::cell::Cell<usize> =
1472 const { std::cell::Cell::new(0) };
1473}
1474thread_local! {
1475 static GOLDEN_HITS: std::cell::Cell<usize> =
1476 const { std::cell::Cell::new(0) };
1477}
1478thread_local! {
1479 static BWDREF_HITS: std::cell::Cell<usize> =
1480 const { std::cell::Cell::new(0) };
1481}
1482thread_local! {
1483 static ALTREF2_HITS: std::cell::Cell<usize> =
1484 const { std::cell::Cell::new(0) };
1485}
1486thread_local! {
1487 static ALTREF_HITS: std::cell::Cell<usize> =
1488 const { std::cell::Cell::new(0) };
1489}
1490
1491// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
1492// -- proves a `reference_select` stream actually reached a block that picked
1493// compound, not just that the header bit was set. Every such block is
1494// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
1495// so this only ever counts attempted reads, never a completed decode.
1496thread_local! {
1497 static COMP_MODE_HITS: std::cell::Cell<usize> =
1498 const { std::cell::Cell::new(0) };
1499}
1500
1501/// Current value of [`COMP_MODE_HITS`].
1502pub(crate) fn comp_mode_hits() -> usize {
1503 COMP_MODE_HITS.with(|c| c.get())
1504}
1505
1506// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
1507// use for, across every call on the current thread -- the same before/after
1508// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1509// exercised palette reconstruction rather than only reading and refusing the
1510// `palette_y_mode` symbol.
1511thread_local! {
1512 static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1513}
1514
1515/// Current value of [`PALETTE_HITS`].
1516pub(crate) fn palette_hits() -> usize {
1517 PALETTE_HITS.with(|c| c.get())
1518}
1519
1520// lane-tiles r12: of those, how many sat at their own TILE's left column --
1521// exactly the blocks whose palette cache/ctx must NOT see the previous tile's
1522// colours (`av1_get_palette_cache`'s `xd->left_mbmi == NULL`). A multi-tile
1523// palette gate that never hits one proves nothing about the tile guard.
1524thread_local! {
1525 static PALETTE_TILE_LEFT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1526}
1527
1528/// Current value of [`PALETTE_TILE_LEFT_HITS`].
1529pub(crate) fn palette_tile_left_hits() -> usize {
1530 PALETTE_TILE_LEFT_HITS.with(|c| c.get())
1531}
1532
1533// lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma
1534// palette use -- proves a stream actually reconstructed UV palette pixels,
1535// not just read and refused the `palette_uv_mode` symbol.
1536thread_local! {
1537 static PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1538}
1539
1540/// Current value of [`PALETTE_UV_HITS`].
1541pub(crate) fn palette_uv_hits() -> usize {
1542 PALETTE_UV_HITS.with(|c| c.get())
1543}
1544
1545// lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`])
1546// decoded a real palette-Y use -- proves the rect strip's own palette syntax
1547// (not just the square path's) actually fired.
1548thread_local! {
1549 static PALETTE_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1550}
1551
1552/// Current value of [`PALETTE_RECT_HITS`].
1553pub(crate) fn palette_rect_hits() -> usize {
1554 PALETTE_RECT_HITS.with(|c| c.get())
1555}
1556
1557// lane-palette2 r6: how many HORZ/VERT rect intra strips ran the
1558// [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] --
1559// i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in
1560// range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per
1561// RD, almost always refused-on-use because the block doesn't end up USING a
1562// palette -- see r5's report). This is the site the removed refusal
1563// ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it
1564// fired here whether or not the block picked a palette, so this is the
1565// counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost
1566// never observes.
1567thread_local! {
1568 static RECT_SCREEN_CONTENT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1569}
1570
1571/// Current value of [`RECT_SCREEN_CONTENT_HITS`].
1572pub(crate) fn rect_screen_content_hits() -> usize {
1573 RECT_SCREEN_CONTENT_HITS.with(|c| c.get())
1574}
1575
1576// lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a
1577// split luma transform (`logical_tx != side`) -- proves the per-TU index-map
1578// windowing actually ran, not just that the whole-block path stayed exact.
1579// Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16);
1580// first actually incremented in r7, when the refusal it guarded was lifted.
1581thread_local! {
1582 static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1583}
1584
1585thread_local! {
1586 /// lane-kf900 r4: rect intra strips that ACTUALLY use a palette -- the
1587 /// 1:4 shapes (32x8/8x32, 16x4/4x16) and the sub-16x16 2:1 leaves
1588 /// (16x8/8x16), the two shapes the lifted refusals named.
1589 static RECT4_PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1590}
1591
1592/// Current value of [`RECT4_PALETTE_HITS`].
1593pub(crate) fn rect4_palette_hits() -> usize {
1594 RECT4_PALETTE_HITS.with(|c| c.get())
1595}
1596
1597/// Current value of [`PALETTE_SPLIT_TX_HITS`].
1598pub(crate) fn palette_split_tx_hits() -> usize {
1599 PALETTE_SPLIT_TX_HITS.with(|c| c.get())
1600}
1601
1602thread_local! {
1603 /// lane-pal8 r1: square 8x8 LEAVES ([`decode_leaf8`]) that actually use a
1604 /// palette (Y or UV) -- the shape every 8-bit `--tune-content=screen`
1605 /// stream stopped on, since aomenc palettes square blocks at 8 bit and
1606 /// `--min-partition-size=8` puts them on this leaf path.
1607 static PALETTE_LEAF8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1608}
1609
1610/// Current value of [`PALETTE_LEAF8_HITS`].
1611pub(crate) fn palette_leaf8_hits() -> usize {
1612 PALETTE_LEAF8_HITS.with(|c| c.get())
1613}
1614
1615/// Zeroes [`PALETTE_LEAF8_HITS`] (per-attempt gate counting).
1616pub(crate) fn reset_palette_leaf8_hits() {
1617 PALETTE_LEAF8_HITS.with(|c| c.set(0));
1618}
1619
1620thread_local! {
1621 /// lane-pal8 r1: NON-SKIP palette blocks on a superblock-level (64-level)
1622 /// HORZ/VERT or 1:4 strip ([`decode_block_rect64`]) -- i.e. a palette
1623 /// block that also carries a real, corner-cropped luma transform.
1624 static PALETTE_SB_STRIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1625}
1626
1627/// Current value of [`PALETTE_SB_STRIP_HITS`].
1628pub(crate) fn palette_sb_strip_hits() -> usize {
1629 PALETTE_SB_STRIP_HITS.with(|c| c.get())
1630}
1631
1632/// Zeroes [`PALETTE_SB_STRIP_HITS`] (per-attempt gate counting).
1633pub(crate) fn reset_palette_sb_strip_hits() {
1634 PALETTE_SB_STRIP_HITS.with(|c| c.set(0));
1635}
1636
1637// lane-hgkf r2: SKIPPED intra blocks whose `tx_depth` split the luma transform
1638// and which are therefore predicted one transform unit at a time (a skipped
1639// block codes no coefficients, so nothing else in the stream witnesses this
1640// path -- only the pixels do).
1641thread_local! {
1642 static SKIP_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1643}
1644
1645/// Current value of [`SKIP_SPLIT_TX_HITS`] (blocks, not units).
1646pub fn skip_split_tx_hits() -> usize {
1647 SKIP_SPLIT_TX_HITS.with(|c| c.get())
1648}
1649
1650/// Zeroes [`SKIP_SPLIT_TX_HITS`] before a gate's own decode attempt.
1651pub fn reset_skip_split_tx_hits() {
1652 SKIP_SPLIT_TX_HITS.with(|c| c.set(0));
1653}
1654
1655// lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth`
1656// symbol split their luma transform, bucketed by block side (8, 16, 32, 64) --
1657// the gate's proof that the lifted path actually ran, per size.
1658thread_local! {
1659 static INTRA_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 4]> =
1660 const { std::cell::Cell::new([0; 4]) };
1661}
1662
1663/// Current value of [`INTRA_IN_INTER_SPLIT_TX_HITS`], indexed 8/16/32/64.
1664pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] {
1665 INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
1666}
1667
1668thread_local! {
1669 /// A just-decoded palette-Y block's own predicted pixels
1670 /// (`side*side`, row-major, `colors[map[i]]`), consumed by
1671 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
1672 /// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
1673 /// per-block override through `read_plane`'s two dozen call sites is the
1674 /// alternative this avoids). Always empty again once that call consumes
1675 /// it (`.take()`), so a non-palette block's own `reconstruct` call never
1676 /// sees stale state.
1677 static PALETTE_PRED: std::cell::RefCell<Option<Vec<u16>>> =
1678 const { std::cell::RefCell::new(None) };
1679}
1680
1681
1682/// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
1683/// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a
1684/// site whose reconstruct never runs would be picked up by the NEXT block's
1685/// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
1686/// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
1687#[track_caller]
1688fn set_palette_pred(buf: Vec<u16>) {
1689 if std::env::var_os("EC_DEBUG_PAL").is_some() {
1690 let stale = PALETTE_PRED.with(|c| c.borrow().is_some());
1691 eprintln!(
1692 "PALSET len={} stale={stale} at {}",
1693 buf.len(),
1694 std::panic::Location::caller()
1695 );
1696 }
1697 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(buf));
1698}
1699
1700#[track_caller]
1701fn take_palette_pred() -> Option<Vec<u16>> {
1702 let got = PALETTE_PRED.with(|c| c.borrow_mut().take());
1703 if std::env::var_os("EC_DEBUG_PAL").is_some() {
1704 eprintln!(
1705 "PALTAKE len={:?} at {}",
1706 got.as_ref().map(Vec::len),
1707 std::panic::Location::caller()
1708 );
1709 }
1710 got
1711}
1712
1713thread_local! {
1714 /// The current frame's `mi` grid, kept only while a frame header set
1715 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
1716 /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
1717 /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
1718 /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
1719 /// does not allow intrabc (so nothing is paid for it).
1720 ///
1721 /// corner-cut: only [`decode_block`] (the square path) records into it,
1722 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
1723 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
1724 /// be wrong there; upgrade = record from the rect/leaf paths too.
1725 static INTRABC_MI_GRID: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>> =
1726 const { std::cell::RefCell::new(None) };
1727 /// The block vector [`read_intra_mode`] just decoded, handed to
1728 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
1729 /// which the alternative -- a tenth tuple member through every caller --
1730 /// already avoids). Always `.take()`n by the block that reads it.
1731 static INTRABC_DV: std::cell::Cell<Option<(i32, i32)>> = const { std::cell::Cell::new(None) };
1732 /// How many blocks decoded `use_intrabc == 1` -- the gate's hit counter.
1733 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1734 /// The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so
1735 /// an intrabc block's chroma reads can inherit it (see
1736 /// [`INTRABC_CHROMA_TX`]). Written on every luma read; only ever read
1737 /// through that one arming site.
1738 static LUMA_TX_TYPE: std::cell::Cell<TxType> = const { std::cell::Cell::new(TxType::DctDct) };
1739 /// libaom `av1_get_tx_type` (`blockd.h:1350`): for `PLANE_TYPE_UV` it
1740 /// branches on `is_inter_block(mbmi)` -- which `is_intrabc_block` also
1741 /// satisfies (`blockd.h:373`) -- and takes the *colocated luma
1742 /// transform's coded* `tx_type` (`mbmi->txk_type[...]`), never
1743 /// `intra_mode_to_tx_type` of the chroma mode. `Some` only across an
1744 /// intrabc block's two chroma [`read_plane`] calls; the type decides the
1745 /// `TX_CLASS`, hence the scan order, `eob_multi_ctx` and every nz context
1746 /// -- getting it wrong desyncs the chroma coefficients, it is not a
1747 /// reconstruction-only detail.
1748 static INTRABC_CHROMA_TX: std::cell::Cell<Option<TxType>> = const { std::cell::Cell::new(None) };
1749}
1750
1751/// Whether this frame's header set `allow_intrabc` -- [`INTRABC_MI_GRID`] is
1752/// `Some` exactly then (set once per frame in `decode_frame`), so the flag
1753/// needs no separate plumbing to reach the rect-strip mode reader.
1754fn allow_intrabc_frame() -> bool {
1755 INTRABC_MI_GRID.with(|g| g.borrow().is_some())
1756}
1757
1758thread_local! {
1759 /// How many rect intra strips READ the `use_intrabc` symbol (i.e. how many
1760 /// times the fix below was exercised) -- the rect-strip gate's hit counter,
1761 /// distinct from [`INTRABC_HITS`] which counts blocks that USE intrabc.
1762 static RECT_INTRABC_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1763}
1764
1765/// Current value of [`RECT_INTRABC_READS`].
1766pub(crate) fn rect_intrabc_reads() -> usize {
1767 RECT_INTRABC_READS.with(|c| c.get())
1768}
1769
1770/// Zeroes [`RECT_INTRABC_READS`] (gate tests call this before a decode).
1771pub(crate) fn reset_rect_intrabc_reads() {
1772 RECT_INTRABC_READS.with(|c| c.set(0));
1773}
1774
1775thread_local! {
1776 /// Blocks that USED intrabc at an 8x8 LEAF (`decode_leaf8`) specifically
1777 /// -- the shape lane-kf900 r7 fixed; [`INTRABC_HITS`] counts every shape.
1778 static LEAF8_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1779}
1780
1781/// Current value of [`LEAF8_INTRABC_HITS`].
1782pub(crate) fn leaf8_intrabc_hits() -> usize {
1783 LEAF8_INTRABC_HITS.with(|c| c.get())
1784}
1785
1786/// Zeroes [`LEAF8_INTRABC_HITS`] (gate tests call this before a decode).
1787pub(crate) fn reset_leaf8_intrabc_hits() {
1788 LEAF8_INTRABC_HITS.with(|c| c.set(0));
1789}
1790
1791/// Current value of [`INTRABC_HITS`].
1792pub(crate) fn intrabc_hits() -> usize {
1793 INTRABC_HITS.with(|c| c.get())
1794}
1795
1796/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
1797pub(crate) fn reset_intrabc_hits() {
1798 INTRABC_HITS.with(|c| c.set(0));
1799}
1800
1801/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
1802/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
1803/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
1804/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
1805fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>) {
1806 INTRABC_MI_GRID.with(|g| {
1807 let mut g = g.borrow_mut();
1808 let Some((grid, _, _)) = g.as_mut() else {
1809 return;
1810 };
1811 let info = crate::mvstack::MiInfo {
1812 is_inter: dv.is_some(),
1813 ref_frame: 0,
1814 ref_frame1: None,
1815 mv: dv.unwrap_or((0, 0)),
1816 mv1: None,
1817 is_new_mv: dv.is_some(),
1818 is_global_mv0: false,
1819 is_global_mv1: false,
1820 size: n4,
1821 size_h: n4,
1822 };
1823 for r in mi_r..mi_r + n4 {
1824 for c in mi_c..mi_c + n4 {
1825 grid.set(r, c, info);
1826 }
1827 }
1828 });
1829}
1830
1831// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
1832// proves a real `skip_mode_present` stream actually reached a block that
1833// picked it, not just that the frame header bit was set.
1834thread_local! {
1835 static SKIP_MODE_HITS: std::cell::Cell<usize> =
1836 const { std::cell::Cell::new(0) };
1837}
1838
1839/// Current value of [`SKIP_MODE_HITS`].
1840pub(crate) fn skip_mode_hits() -> usize {
1841 SKIP_MODE_HITS.with(|c| c.get())
1842}
1843
1844// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
1845// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
1846// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
1847// reached [`obmc_blend`], not just the header bit.
1848thread_local! {
1849 static OBMC_HITS: std::cell::Cell<usize> =
1850 const { std::cell::Cell::new(0) };
1851}
1852
1853// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the
1854// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled
1855// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while
1856// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have
1857// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this
1858// decoder used to read with the wrong alphabet, so a gate that asserts this
1859// counter advanced proves the fixed path fired (class
1860// `gate-blind-to-feature`).
1861thread_local! {
1862 static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1863}
1864
1865/// Current value of [`FIMV_ALPHABET_HITS`].
1866pub fn fimv_alphabet_hits() -> usize {
1867 FIMV_ALPHABET_HITS.with(|c| c.get())
1868}
1869
1870// lane-fimv r1: how many frame headers this decoder has decoded with
1871/// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate
1872// prove the encoder really produced the header state under test rather than
1873// assume it.
1874thread_local! {
1875 static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1876}
1877
1878/// Current value of [`FIMV_FRAME_HITS`].
1879pub fn fimv_frame_hits() -> usize {
1880 FIMV_FRAME_HITS.with(|c| c.get())
1881}
1882
1883/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
1884/// `force_integer_mv` bit is set.
1885pub fn note_force_integer_mv_frame() {
1886 FIMV_FRAME_HITS.with(|c| c.set(c.get() + 1));
1887}
1888
1889/// Current value of [`OBMC_HITS`].
1890pub(crate) fn obmc_hits() -> usize {
1891 OBMC_HITS.with(|c| c.get())
1892}
1893
1894// lane-scaledref r1: per-case firing counts for the scaled-reference gate
1895// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED
1896// reference would pass just as well and prove nothing, so the gate
1897// hard-asserts each combination this round lifts actually occurred:
1898// a compound block with a scaled tap, a warp block whose warp libaom
1899// suppresses because the reference is scaled, an OBMC block, an interintra
1900// block, and an 8x8 leaf.
1901thread_local! {
1902 static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1903 static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1904 static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1905 static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1906 static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1907 static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1908 static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1909}
1910
1911/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one
1912/// scaled and one unscaled tap.
1913pub(crate) fn mixed_scale_compound_hits() -> usize {
1914 MIXED_SCALE_COMPOUND_HITS.with(|c| c.get())
1915}
1916
1917/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have
1918/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf`
1919/// instead because their reference is scaled (libaom `motion_mode_allowed`,
1920/// `blockd.h:1484`).
1921pub(crate) fn scaled_warp_suppressed_hits() -> usize {
1922 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get())
1923}
1924
1925/// Current value of [`SCALED_COMPOUND_HITS`].
1926pub(crate) fn scaled_compound_hits() -> usize {
1927 SCALED_COMPOUND_HITS.with(|c| c.get())
1928}
1929
1930/// Current value of [`SCALED_WARP_FALLBACK_HITS`].
1931pub(crate) fn scaled_warp_fallback_hits() -> usize {
1932 SCALED_WARP_FALLBACK_HITS.with(|c| c.get())
1933}
1934
1935/// Current value of [`SCALED_OBMC_HITS`].
1936pub(crate) fn scaled_obmc_hits() -> usize {
1937 SCALED_OBMC_HITS.with(|c| c.get())
1938}
1939
1940/// Current value of [`SCALED_INTERINTRA_HITS`].
1941pub(crate) fn scaled_interintra_hits() -> usize {
1942 SCALED_INTERINTRA_HITS.with(|c| c.get())
1943}
1944
1945/// Current value of [`SCALED_BLOCK8_HITS`].
1946pub(crate) fn scaled_block8_hits() -> usize {
1947 SCALED_BLOCK8_HITS.with(|c| c.get())
1948}
1949
1950// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
1951// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
1952// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
1953// 8x8-leaf OBMC block apart from a 16x16+ one.
1954thread_local! {
1955 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1956}
1957
1958// lane-interp3 r1: how many inter blocks read a SWITCHABLE `interp_filter`
1959// pair whose two directions differ (`enable_dual_filter` only -- with dual
1960// filter off both directions take the single symbol, so this can never fire).
1961// A gate asserting it proves the stream really carries dual-filter blocks.
1962thread_local! {
1963 static DUAL_FILTER_DIFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1964}
1965
1966// lane-interp3 r1: how many COMPOUND 8x8 leaves read their own
1967// `read_mb_interp_filter` symbol(s) -- the read this round added (the leaf
1968// used to skip it entirely, losing a symbol and stamping the `[3, 3]`
1969// no-filter sentinel that made a neighbouring OBMC block panic).
1970thread_local! {
1971 static COMPOUND8_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1972}
1973
1974/// Current value of [`DUAL_FILTER_DIFF_HITS`].
1975pub(crate) fn dual_filter_diff_hits() -> usize {
1976 DUAL_FILTER_DIFF_HITS.with(|c| c.get())
1977}
1978
1979/// Current value of [`COMPOUND8_FILTER_HITS`].
1980pub(crate) fn compound8_filter_hits() -> usize {
1981 COMPOUND8_FILTER_HITS.with(|c| c.get())
1982}
1983
1984// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
1985// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
1986// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
1987// -- the gate's proof that a fixture really exercises the alphabet this
1988// round changed, even though the block itself still refuses (warp
1989// estimation/filter not ported).
1990thread_local! {
1991 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
1992 const { std::cell::Cell::new(0) };
1993}
1994
1995/// Current value of [`WARP_SELECTED_HITS`].
1996pub(crate) fn warp_selected_hits() -> usize {
1997 WARP_SELECTED_HITS.with(|c| c.get())
1998}
1999
2000// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one
2001// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane`
2002// into the compound intermediate) rather than translationally -- the
2003// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model
2004// really reached [`crate::warp::warp_affine_compound`].
2005thread_local! {
2006 static COMPOUND_WARP_HITS: std::cell::Cell<usize> =
2007 const { std::cell::Cell::new(0) };
2008}
2009
2010/// Current value of [`COMPOUND_WARP_HITS`].
2011pub(crate) fn compound_warp_hits() -> usize {
2012 COMPOUND_WARP_HITS.with(|c| c.get())
2013}
2014
2015// lane-interp3 r3: the same proof narrowed to the 8x8 LEAF's own compound
2016// arm ([`decode_inter_block8`]) -- that arm predicted both taps
2017// translationally until r3, so a gate needs to tell a warped 8x8 compound
2018// leaf apart from a warped 16x16+ one (both bump [`COMPOUND_WARP_HITS`]).
2019thread_local! {
2020 static COMPOUND_WARP_HITS_8: std::cell::Cell<usize> =
2021 const { std::cell::Cell::new(0) };
2022}
2023
2024/// Current value of [`COMPOUND_WARP_HITS_8`].
2025pub(crate) fn compound_warp_hits_8() -> usize {
2026 COMPOUND_WARP_HITS_8.with(|c| c.get())
2027}
2028
2029// lane-gmaffine r1: how many blocks built their prediction from a
2030// SIX-parameter (`AFFINE`) global-motion model through
2031// `crate::warp::global_warp_params` -- the gate's proof that a stream really
2032// carried an AFFINE `global_motion_params` AND that a block was predicted
2033// with it, not merely that the header parsed one.
2034thread_local! {
2035 static AFFINE_GM_HITS: std::cell::Cell<usize> =
2036 const { std::cell::Cell::new(0) };
2037}
2038
2039/// Current value of [`AFFINE_GM_HITS`].
2040pub(crate) fn affine_gm_hits() -> usize {
2041 AFFINE_GM_HITS.with(|c| c.get())
2042}
2043
2044// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves
2045// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real
2046// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented
2047// only once `find_projection` returned a usable model, unlike
2048// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates'
2049// proof that the leaf path itself fired, not the 16x16+ one.
2050thread_local! {
2051 static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2052 static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2053}
2054
2055/// Current value of [`GLOBALMV_HITS_8`].
2056pub(crate) fn globalmv_hits_8() -> usize {
2057 GLOBALMV_HITS_8.with(|c| c.get())
2058}
2059
2060/// Current value of [`WARP_HITS_8`].
2061pub(crate) fn warp_hits_8() -> usize {
2062 WARP_HITS_8.with(|c| c.get())
2063}
2064
2065// How many blocks decoded `interintra == 1` with the non-wedge blended
2066// prediction applied (lane-interintra r1) -- the gate's proof that a
2067// stream actually exercised interintra.
2068thread_local! {
2069 static INTERINTRA_HITS: std::cell::Cell<usize> =
2070 const { std::cell::Cell::new(0) };
2071}
2072
2073/// Current value of [`INTERINTRA_HITS`].
2074pub(crate) fn interintra_hits() -> usize {
2075 INTERINTRA_HITS.with(|c| c.get())
2076}
2077
2078// lane-midcut r1: of those, how many were RECTANGULAR (`write_w != write_h`)
2079// -- the shape `interintra_blend` used to build a square `side x side` intra
2080// predictor for, with `ii_size_scales`/`edges` taken at the square. Every
2081// pre-existing interintra gate passed with that bug, so the rect arm needs
2082// its own counter to stop being vacuous.
2083thread_local! {
2084 static INTERINTRA_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2085}
2086
2087/// Current value of [`INTERINTRA_RECT_HITS`].
2088pub fn interintra_rect_hits() -> usize {
2089 INTERINTRA_RECT_HITS.with(|c| c.get())
2090}
2091
2092// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
2093// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
2094// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
2095// gate fixture actually exercises this alphabet, even though the block
2096// still refuses (the mask blend itself is unported).
2097thread_local! {
2098 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
2099 const { std::cell::Cell::new(0) };
2100}
2101
2102/// Current value of [`MASKED_COMPOUND_HITS`].
2103pub(crate) fn masked_compound_hits() -> usize {
2104 MASKED_COMPOUND_HITS.with(|c| c.get())
2105}
2106
2107// lane-intersub8 r4/r5: the NON-SQUARE half of `MASKED_COMPOUND_HITS` -- a
2108// masked-compound block whose true footprint is rectangular, i.e. the case
2109// whose `compound_type`/`wedge_idx` CDF row r4 fixed (it used to read the
2110// square envelope's `BLOCK_SIZES_ALL` index). Square blocks cannot show that
2111// defect, so a gate asserting `masked_compound_hits` alone stays vacuous for it.
2112thread_local! {
2113 static RECT_MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
2114 const { std::cell::Cell::new(0) };
2115}
2116
2117/// Current value of [`RECT_MASKED_COMPOUND_HITS`].
2118pub(crate) fn rect_masked_compound_hits() -> usize {
2119 RECT_MASKED_COMPOUND_HITS.with(|c| c.get())
2120}
2121
2122// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
2123// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
2124// actually exercised the wedge blend, not just the DIFFWTD half of
2125// `MASKED_COMPOUND_HITS`.
2126thread_local! {
2127 static WEDGE_HITS: std::cell::Cell<usize> =
2128 const { std::cell::Cell::new(0) };
2129}
2130
2131/// Current value of [`WEDGE_HITS`].
2132pub(crate) fn wedge_hits() -> usize {
2133 WEDGE_HITS.with(|c| c.get())
2134}
2135
2136// How many blocks decoded a real wedge-INTERINTRA block
2137// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
2138// a gate fixture exercised the wedge blend (fixed sign 0), not just the
2139// smooth arm counted by `INTERINTRA_HITS`.
2140thread_local! {
2141 static WII_HITS: std::cell::Cell<usize> =
2142 const { std::cell::Cell::new(0) };
2143}
2144
2145/// Current value of [`WII_HITS`].
2146pub(crate) fn wii_hits() -> usize {
2147 WII_HITS.with(|c| c.get())
2148}
2149
2150// lane-sbrect10 r1: how many INTRA blocks read `uv_mode` off the 13-symbol
2151// NO-CFL alphabet *because their size excludes CFL* (libaom `is_cfl_allowed`:
2152// wide <= 32 && high <= 32). The witness that a gate stream really carries a
2153// 64-axis intra block -- the shape whose 14-symbol read desynced every inter
2154// frame carrying one.
2155thread_local! {
2156 static NOCFL_UV_MODE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2157}
2158
2159/// Current value of [`NOCFL_UV_MODE_HITS`].
2160pub(crate) fn nocfl_uv_mode_hits() -> usize {
2161 NOCFL_UV_MODE_HITS.with(|c| c.get())
2162}
2163
2164/// lane-inter16ab r5: the six RECTANGULAR wedge shapes, in this order --
2165/// the counter slots of [`RECT_WEDGE_HITS`]/[`RECT_WII_HITS`].
2166pub(crate) const RECT_WEDGE_SHAPES: [(usize, usize); 6] =
2167 [(8, 16), (16, 8), (16, 32), (32, 16), (8, 32), (32, 8)];
2168
2169fn rect_wedge_slot(bw: usize, bh: usize) -> Option<usize> {
2170 RECT_WEDGE_SHAPES.iter().position(|&s| s == (bw, bh))
2171}
2172
2173// lane-inter16ab r5: how many COMPOUND_WEDGE / wedge-INTERINTRA blocks used a
2174// RECTANGULAR codebook row (hgtw/hltw), per shape -- the gate's proof that
2175// the rect wedge masks lifted this round actually fired, not just the square
2176// ones already counted by `WEDGE_HITS`/`WII_HITS`.
2177thread_local! {
2178 static RECT_WEDGE_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
2179 static RECT_WII_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
2180}
2181
2182/// Current value of [`RECT_WEDGE_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
2183pub(crate) fn rect_wedge_hits() -> [usize; 6] {
2184 RECT_WEDGE_HITS.with(|c| c.get())
2185}
2186
2187/// Current value of [`RECT_WII_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
2188pub(crate) fn rect_wii_hits() -> [usize; 6] {
2189 RECT_WII_HITS.with(|c| c.get())
2190}
2191
2192// lane-inter4 r4: how many 16x8/8x16 INTER LEAVES actually ran the OBMC
2193// blend -- the gate's proof that `--enable-obmc=1` reached this shape (the
2194// r3 refusal's replacement: prefilt frames are bit-exact vs an instrumented
2195// aomdec, neighbour list included).
2196thread_local! {
2197 static OBMC_RECT_LEAF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2198}
2199
2200/// Current value of [`OBMC_RECT_LEAF_HITS`].
2201pub(crate) fn obmc_rect_leaf_hits() -> usize {
2202 OBMC_RECT_LEAF_HITS.with(|c| c.get())
2203}
2204
2205// lane-obmcrec r1: how many OBMC neighbours were taken from the SECOND half of
2206// a 4-wide/4-tall (1:4 strip) chroma pair -- the case whose interp filter used
2207// to be read from the pair's FIRST mi, which is a different block and, when
2208// that half is intra, carries the `[3, 3]` "no filter" sentinel (the three
2209// 1080p 10-bit film cuts refused there). The gate's proof the shape fired.
2210thread_local! {
2211 static OBMC_PAIR_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2212}
2213
2214/// Current value of [`OBMC_PAIR_FILTER_HITS`].
2215pub(crate) fn obmc_pair_filter_hits() -> usize {
2216 OBMC_PAIR_FILTER_HITS.with(|c| c.get())
2217}
2218
2219/// Current value of [`OBMC_HITS_8`].
2220pub(crate) fn obmc_hits_8() -> usize {
2221 OBMC_HITS_8.with(|c| c.get())
2222}
2223
2224// lane-rectgate r1: how many 32x32 quadrants actually decoded a
2225// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
2226// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
2227// `VERT_B` all still fall into the generic "a partition type this encoder
2228// never writes" refusal below) -- the gate's proof that a free-partition
2229// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
2230// coincidentally never selecting one.
2231thread_local! {
2232 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
2233 const { std::cell::Cell::new(0) };
2234}
2235
2236/// Current value of [`EXTENDED_PARTITION_HITS`].
2237pub(crate) fn extended_partition_hits() -> usize {
2238 EXTENDED_PARTITION_HITS.with(|c| c.get())
2239}
2240
2241// lane-partitions r1: how many 32x32 quadrants decoded a real
2242// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
2243// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
2244// gate's proof this round's arms actually fired.
2245thread_local! {
2246 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
2247 const { std::cell::Cell::new(0) };
2248}
2249
2250/// Current value of [`RECT_PARTITION_HITS`].
2251pub(crate) fn rect_partition_hits() -> usize {
2252 RECT_PARTITION_HITS.with(|c| c.get())
2253}
2254
2255// lane-inter8 r1: how many superblocks an inter tile coded as a single
2256// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for
2257// static content, previously a named refusal).
2258thread_local! {
2259 /// lane-sb128c r1: how many 128x128 `PARTITION_NONE` roots this INTER tile
2260 /// path decoded as one whole block (its gate's own witness).
2261 pub(crate) static INTER_SB128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2262 /// 128x64 / 64x128 INTER blocks decoded at the 128 root (lane-sb128c r7).
2263 pub(crate) static INTER_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2264 pub(crate) static INTER_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2265}
2266
2267/// Current value of [`INTER_SB128_HORZ_HITS`], for a gate's before/after delta.
2268pub(crate) fn inter_sb128_horz_hits() -> usize {
2269 INTER_SB128_HORZ_HITS.with(std::cell::Cell::get)
2270}
2271
2272/// Current value of [`INTER_SB128_VERT_HITS`], for a gate's before/after delta.
2273pub(crate) fn inter_sb128_vert_hits() -> usize {
2274 INTER_SB128_VERT_HITS.with(std::cell::Cell::get)
2275}
2276
2277/// Current value of [`INTER_SB128_NONE_HITS`], for a gate's before/after delta.
2278pub fn inter_sb128_none_hits() -> usize {
2279 INTER_SB128_NONE_HITS.with(std::cell::Cell::get)
2280}
2281
2282thread_local! {
2283 /// lane-sb128c r3: how many INTRA-coded 128x128 blocks inside an INTER
2284 /// frame this decoder reconstructed (mu-chunk chroma, four TX_64X64 luma
2285 /// units) -- the gate's witness that the lifted refusal's case fired.
2286 pub(crate) static INTRA_128_IN_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2287}
2288
2289/// Current value of [`INTRA_128_IN_INTER_HITS`], for a gate's before/after delta.
2290pub fn intra_128_in_inter_hits() -> usize {
2291 INTRA_128_IN_INTER_HITS.with(std::cell::Cell::get)
2292}
2293
2294thread_local! {
2295 static INTER_SB_NONE_HITS: std::cell::Cell<usize> =
2296 const { std::cell::Cell::new(0) };
2297}
2298
2299/// Current value of [`INTER_SB_NONE_HITS`].
2300pub(crate) fn inter_sb_none_hits() -> usize {
2301 INTER_SB_NONE_HITS.with(|c| c.get())
2302}
2303
2304// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter
2305// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle
2306// path has always run that loop, so only this counter proves the newly-lifted
2307// alphabet value fired.
2308thread_local! {
2309 static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> =
2310 const { std::cell::Cell::new(0) };
2311}
2312
2313/// Current value of [`INTER_SUB16_SPLIT_HITS`].
2314pub(crate) fn inter_sub16_split_hits() -> usize {
2315 INTER_SUB16_SPLIT_HITS.with(|c| c.get())
2316}
2317
2318// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
2319// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
2320// rect coefficient reader itself fired, not just the strip-level partition
2321// symbol [`RECT_PARTITION_HITS`] already counts.
2322thread_local! {
2323 static RECT_COEFF_HITS: std::cell::Cell<usize> =
2324 const { std::cell::Cell::new(0) };
2325}
2326
2327/// Current value of [`RECT_COEFF_HITS`].
2328pub(crate) fn rect_coeff_hits() -> usize {
2329 RECT_COEFF_HITS.with(|c| c.get())
2330}
2331
2332// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`])
2333// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the
2334// charter's real-aomenc gate hard-asserts.
2335thread_local! {
2336 static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> =
2337 const { std::cell::Cell::new(0) };
2338}
2339
2340/// Current value of [`RECT_LEAF_COEFF_HITS`].
2341pub(crate) fn rect_leaf_coeff_hits() -> usize {
2342 RECT_LEAF_COEFF_HITS.with(|c| c.get())
2343}
2344
2345// lane-intrarect r1: how many intra-coded HORZ/VERT strips decoded on the
2346// INTER block path ([`decode_intra_rect_in_inter`]), per shape class --
2347// [0] the superblock-level 64x32/32x64, [1] 32x16/16x32, [2] 16x8/8x16.
2348// Every one of them was the named refusal "an intra-coded HORZ/VERT strip
2349// needs rectangular intra prediction" before this round.
2350thread_local! {
2351 static INTRA_RECT_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
2352 const { std::cell::Cell::new([0; 3]) };
2353}
2354
2355/// Current value of [`INTRA_RECT_IN_INTER_HITS`] for one shape class
2356/// (0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16).
2357pub(crate) fn intra_rect_strip_in_inter_hits(class: usize) -> usize {
2358 INTRA_RECT_IN_INTER_HITS.with(|c| c.get()[class])
2359}
2360
2361// lane-rect64port r1 (ported by hand from lane-intra64split 5ffbaf3): coded
2362// (non-skip) 64-level HORZ/VERT intra strips whose luma transform is the
2363// un-split TX_64X32/TX_32X64 -- the corner-cropped 32x32 coefficient read of
2364// [`decode_rect_split`], the shape both 10-bit 3840x1608 film cuts stop on.
2365// Split by ORIENTATION (index 0 = 64x32 wide / HORZ, 1 = 32x64 tall / VERT):
2366// a single counter cannot tell an axis swap from a working arm
2367// (class [[scan-weights-cross-axis]]), so the gate asserts both cells.
2368thread_local! {
2369 static RECT64_CORNER_TU_HITS: std::cell::Cell<[usize; 2]> =
2370 const { std::cell::Cell::new([0; 2]) };
2371}
2372
2373/// Current value of [`RECT64_CORNER_TU_HITS`] for one orientation
2374/// (0 = 64x32, 1 = 32x64).
2375pub(crate) fn rect64_corner_tu_hits(orient: usize) -> usize {
2376 RECT64_CORNER_TU_HITS.with(|c| c.get()[orient])
2377}
2378
2379// lane-intrasplit r1: intra HORZ/VERT strips inside an INTER frame whose luma
2380// transform is SPLIT, bucketed by the read `tx_depth` (index 1 and 2; index 0
2381// is never incremented) -- the gate's proof that the lifted path ran per depth.
2382thread_local! {
2383 static INTRA_RECT_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 3]> =
2384 const { std::cell::Cell::new([0; 3]) };
2385}
2386
2387/// Current value of [`INTRA_RECT_IN_INTER_SPLIT_TX_HITS`], indexed by tx depth.
2388pub(crate) fn intra_rect_in_inter_split_tx_hits() -> [usize; 3] {
2389 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
2390}
2391
2392// lane-midcut r2: rect intra blocks inside an inter frame whose `tx_depth` CDF
2393// ROW moved when libaom's inter-neighbour override was applied -- i.e. exactly
2394// the blocks the key frame's deblock-grid approximation used to mis-read.
2395thread_local! {
2396 static INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS: std::cell::Cell<usize> =
2397 const { std::cell::Cell::new(0) };
2398}
2399
2400/// Current value of [`INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS`].
2401pub(crate) fn intra_rect_in_inter_txctx_override_hits() -> usize {
2402 INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS.with(std::cell::Cell::get)
2403}
2404
2405// lane-intra14 r1: how many intra-coded 1:4 strips decoded on the INTER
2406// block path, per shape -- [0] 64x16, [1] 16x64, [2] 32x8, [3] 8x32. Every
2407// one of them was the named refusal "an intra-coded 1:4 (or other non-2:1)
2408// rect strip on the inter block path" before this round.
2409thread_local! {
2410 static INTRA_RECT4_IN_INTER_HITS: std::cell::Cell<[usize; 4]> =
2411 const { std::cell::Cell::new([0; 4]) };
2412}
2413
2414/// Current value of [`INTRA_RECT4_IN_INTER_HITS`] for one shape
2415/// (0 = 64x16, 1 = 16x64, 2 = 32x8, 3 = 8x32).
2416pub(crate) fn intra_rect4_strip_in_inter_hits(shape: usize) -> usize {
2417 INTRA_RECT4_IN_INTER_HITS.with(|c| c.get()[shape])
2418}
2419
2420// lane-intra14 r1: set while an INTRA block of an INTER frame is decoded
2421// through one of the key-frame rect readers ([`decode_block_rect4`],
2422// [`decode_block_rect64`]). `Some((size_group, skip))` tells
2423// [`read_intra_mode_rect`] that (a) `skip`/segment id/cdef/delta-q were
2424// already read by [`decode_inter_block`] and (b) the luma mode comes off
2425// `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`,
2426// decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair.
2427thread_local! {
2428 static INTRA_IN_INTER_MODE: std::cell::Cell<Option<(usize, bool)>> =
2429 const { std::cell::Cell::new(None) };
2430}
2431
2432// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
2433// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
2434// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16
2435// slot -- i.e. how often the r5 defect would have picked the wrong CDF row.
2436thread_local! {
2437 static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
2438 const { std::cell::Cell::new(0) };
2439}
2440
2441/// Current value of [`MODE_MI_OVERRIDE_HITS`].
2442pub(crate) fn mode_mi_override_hits() -> usize {
2443 MODE_MI_OVERRIDE_HITS.with(|c| c.get())
2444}
2445
2446// lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a
2447// TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a
2448// mode from the previous tile, where libaom's `up_available`/`left_available`
2449// make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams:
2450// `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode`
2451// per superblock row in `start_row`, so the luma fallback cannot leak the way
2452// lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is
2453// the invariant that makes the coarse fallback safe.
2454thread_local! {
2455 static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell<usize> =
2456 const { std::cell::Cell::new(0) };
2457}
2458
2459/// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`].
2460pub(crate) fn mode_tile_edge_coarse_leaks() -> usize {
2461 MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get())
2462}
2463
2464// lane-cfl r1: how many times a chroma intra-edge filter-type read
2465// (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the
2466// mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the
2467// r1 defect would have filtered a chroma edge with the wrong strength.
2468thread_local! {
2469 static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
2470 const { std::cell::Cell::new(0) };
2471}
2472
2473/// Current value of [`UV_MODE_MI_OVERRIDE_HITS`].
2474pub(crate) fn uv_mode_mi_override_hits() -> usize {
2475 UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get())
2476}
2477
2478// lane-mtfix r1: how many times a chroma intra-edge filter-type read was
2479// suppressed at a TILE edge that is not a frame edge -- the above/left
2480// `uv_mode` neighbour of a block on a tile's first mi row/column lives in
2481// another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The
2482// coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per
2483// tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile
2484// above would decide this tile's chroma edge filter strength.
2485thread_local! {
2486 static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell<usize> =
2487 const { std::cell::Cell::new(0) };
2488}
2489
2490/// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`].
2491pub(crate) fn uv_tile_edge_suppressed_hits() -> usize {
2492 UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get())
2493}
2494
2495// lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs`
2496// read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block
2497// shapes the r1 chroma defect showed up on.
2498thread_local! {
2499 static CFL_BLOCK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2500 static UV_ANGLE_DELTA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2501}
2502
2503/// Current value of [`CFL_BLOCK_HITS`].
2504pub(crate) fn cfl_block_hits() -> usize {
2505 CFL_BLOCK_HITS.with(|c| c.get())
2506}
2507
2508/// Current value of [`UV_ANGLE_DELTA_HITS`].
2509pub(crate) fn uv_angle_delta_hits() -> usize {
2510 UV_ANGLE_DELTA_HITS.with(|c| c.get())
2511}
2512
2513// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
2514// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
2515// gate's proof this round's arms actually reached a real block, not just
2516// that `partition_w64` read one of those two symbol values.
2517thread_local! {
2518 static SB_RECT_HITS: std::cell::Cell<usize> =
2519 const { std::cell::Cell::new(0) };
2520}
2521
2522/// Current value of [`SB_RECT_HITS`].
2523// lane-hgkf r1: the frame-edge partition bit, one level each. Slot 0 = a
2524// 64-level gathered edge bit read as HORZ/VERT, 1 = the same bit read as
2525// SPLIT, 2/3 = the 32-level pair. A gate asserting slot 0 or 2 proves the
2526// non-SPLIT edge arm actually decoded (before this round the bit was read and
2527// thrown away, so that arm was unreachable).
2528thread_local! {
2529 static EDGE_PART_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
2530}
2531
2532/// Current value of [`EDGE_PART_HITS`].
2533pub(crate) fn edge_part_hits() -> [usize; 4] {
2534 EDGE_PART_HITS.with(|c| c.get())
2535}
2536
2537/// Reset [`EDGE_PART_HITS`] (a gate counts one stream at a time).
2538pub(crate) fn reset_edge_part_hits() {
2539 EDGE_PART_HITS.with(|c| c.set([0; 4]));
2540}
2541
2542fn bump_edge_part(slot: usize) {
2543 EDGE_PART_HITS.with(|c| {
2544 let mut h = c.get();
2545 h[slot] += 1;
2546 c.set(h);
2547 });
2548}
2549
2550pub(crate) fn sb_rect_hits() -> usize {
2551 SB_RECT_HITS.with(|c| c.get())
2552}
2553
2554// lane-golomb r2: the 32x32-level FRAME-EDGE partition. Slot 0/1 = the
2555// gathered edge bit read as 0 (HORZ/VERT) / 1 (SPLIT); slot 2 = a 32-level
2556// PARTITION_HORZ decoded with `has_rows32 == false` (only the top 32x16 half
2557// is coded), slot 3 = a PARTITION_VERT with `has_cols32 == false`. Both tile
2558// paths (intra and inter) feed the same counter.
2559//
2560// lane-golomb r3: slots 4..7 are the same four facts one level up, at the
2561// SUPERBLOCK (64x64) edge -- 4/5 = the gathered 64-level bit read as
2562// HORZ/VERT / SPLIT, 6 = a 64x32 bottom-edge strip decoded with
2563// `has_rows == false`, 7 = a 32x64 right-edge strip. Real aomenc answers a
2564// bottom-edge superblock with the 64-level HORZ (measured: 192x80 flat-band,
2565// every SB of the last row), so the 32-level slots stay 0 on that content and
2566// only these prove the arm fired.
2567thread_local! {
2568 static EDGE32_HITS: std::cell::Cell<[usize; 8]> =
2569 const { std::cell::Cell::new([0; 8]) };
2570}
2571
2572/// Current value of [`EDGE32_HITS`].
2573pub(crate) fn edge32_hits() -> [usize; 8] {
2574 EDGE32_HITS.with(|c| c.get())
2575}
2576
2577/// [`bump_edge32`] of `base + bit`, returning the bit -- the gathered edge
2578/// reads are `if`-conditions, so the counter has to ride the expression.
2579fn bump_edge32_bit(base: usize, bit: usize) -> usize {
2580 bump_edge32(base + bit.min(1));
2581 bit
2582}
2583
2584fn bump_edge32(slot: usize) {
2585 EDGE32_HITS.with(|c| {
2586 let mut h = c.get();
2587 h[slot] += 1;
2588 c.set(h)
2589 });
2590}
2591
2592// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/
2593// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64
2594// strip) fired. Real aomenc picks these at 64 even with
2595// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is
2596// the counter the gate hard-asserts.
2597thread_local! {
2598 static SB_AB_HITS: std::cell::Cell<[usize; 4]> =
2599 const { std::cell::Cell::new([0; 4]) };
2600}
2601
2602/// Current value of [`SB_AB_HITS`], summed over the four arms.
2603pub(crate) fn sb_ab_hits() -> usize {
2604 SB_AB_HITS.with(|c| c.get().iter().sum())
2605}
2606
2607/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`,
2608/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a
2609/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as
2610/// proof of all four.
2611pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] {
2612 SB_AB_HITS.with(std::cell::Cell::get)
2613}
2614
2615// lane-tx64x16: the two 1:4 superblock arms, counted per orientation --
2616// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64
2617// strips). Two counters, not one, because a gate that only proved "some 1:4
2618// strip fired" would pass on a stream that never coded the other axis, and
2619// every scan/context table this round added comes in a transposed pair.
2620thread_local! {
2621 static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2622 static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2623}
2624
2625/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded).
2626pub(crate) fn sb_rect4_horz_hits() -> usize {
2627 SB_RECT4_HORZ_HITS.with(|c| c.get())
2628}
2629
2630/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded).
2631pub(crate) fn sb_rect4_vert_hits() -> usize {
2632 SB_RECT4_VERT_HITS.with(|c| c.get())
2633}
2634
2635// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation --
2636// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32
2637// strips), the arms the ReelB mid-film extract stops at.
2638thread_local! {
2639 static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2640 static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2641 /// lane-inter4 r1: the INTER-frame twins of the two counters above --
2642 /// four 32x8 / 8x32 inter strips of a 32x32-level `PARTITION_HORZ_4` /
2643 /// `PARTITION_VERT_4`.
2644 static RECT4_32_HORZ_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2645 static RECT4_32_VERT_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2646 /// lane-inter4 r1: superblock-level inter `PARTITION_HORZ`/`PARTITION_VERT`
2647 /// strips (64x32 / 32x64) and their 1:4 pair (64x16 / 16x64).
2648 static INTER_SB_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2649 static INTER_SB_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2650 static INTER_SB_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2651 static INTER_SB_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2652}
2653
2654/// How many 32x32-level 1:4 strips actually read coefficients (non-skip):
2655/// a gate that only counted strips would pass on an all-skip stream, which
2656/// exercises none of the new scan/context tables.
2657thread_local! {
2658 static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2659}
2660
2661// lane-rectsplitx r1: 1:4 strips (32x8/8x32/64x16/16x64) decoded through the
2662// per-transform-unit split path, split by tx depth -- depth 1 is a 2:1 RECT
2663// unit (TX_16X8/TX_32X16), depth 2 a square one, and the two INTERLEAVE in
2664// every real stream, so a gate must prove both fired. `SUB16_SPLIT_HITS`
2665// counts the same for a 16x8/8x16 strip below 16x16.
2666thread_local! {
2667 static RECT4_SPLIT_DEPTH1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2668 static RECT4_SPLIT_DEPTH2_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2669 static SUB16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2670}
2671
2672/// Current values of `RECT4_SPLIT_DEPTH1_HITS` / `RECT4_SPLIT_DEPTH2_HITS`.
2673pub(crate) fn rect4_split_depth_hits() -> (usize, usize) {
2674 (
2675 RECT4_SPLIT_DEPTH1_HITS.with(|c| c.get()),
2676 RECT4_SPLIT_DEPTH2_HITS.with(|c| c.get()),
2677 )
2678}
2679
2680/// Current value of `SUB16_SPLIT_HITS`.
2681pub(crate) fn sub16_split_hits() -> usize {
2682 SUB16_SPLIT_HITS.with(|c| c.get())
2683}
2684
2685// lane-frame36 r2: superblock-level strips ([`decode_block_rect64`]) whose
2686// luma transform is SPLIT and which therefore leave through that fn's early
2687// return -- the arm that published no `TXFM_CONTEXT` band until this round.
2688thread_local! {
2689 static RECT64_SPLIT_TXFM_PUBLISH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2690}
2691
2692/// Current value of `RECT64_SPLIT_TXFM_PUBLISH_HITS`.
2693pub(crate) fn rect64_split_txfm_publish_hits() -> usize {
2694 RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.get())
2695}
2696
2697/// Current value of `RECT4_COEFF_HITS`.
2698pub(crate) fn rect4_coeff_hits() -> usize {
2699 RECT4_COEFF_HITS.with(|c| c.get())
2700}
2701
2702// lane-sbab r1: how many superblock-level (64x64) AB partitions fired IN AN
2703// INTER frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`,
2704// `_VERT_B` order (the intra-frame counterpart is `SB_AB_HITS`). Each arm is
2705// two 32x32 inter squares plus one true 64x32/32x64 inter strip; the gate
2706// asserts the arms it proves separately so a run whose RD only picked one
2707// cannot pass as proof of the others.
2708thread_local! {
2709 static SB_AB_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
2710}
2711
2712/// [`SB_AB_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 64x64 in an
2713/// inter frame).
2714pub fn sb_ab_inter_hits_by_arm() -> [usize; 4] {
2715 SB_AB_INTER_HITS.with(std::cell::Cell::get)
2716}
2717
2718// lane-inter16ab r1: how many 16x16-level AB partitions fired IN AN INTER
2719// frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B`
2720// order (the intra-frame counterpart is `AB16_HITS`). Each arm is two 8x8
2721// inter leaves (`decode_inter_block8`) plus one true 16x8/8x16 inter strip
2722// (`decode_inter_block` with `write_w`/`write_h`); the gate asserts every
2723// arm separately so a run whose RD only picked one cannot pass as proof of
2724// four.
2725thread_local! {
2726 static AB16_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
2727}
2728
2729/// [`AB16_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16 in an
2730/// inter frame).
2731pub fn ab16_inter_hits_by_arm() -> [usize; 4] {
2732 AB16_INTER_HITS.with(std::cell::Cell::get)
2733}
2734
2735// lane-inter16ab r2: the 16x16-level 1:4 pair as INTER blocks -- four 16x4
2736// (`PARTITION_HORZ_4`) or 4x16 (`PARTITION_VERT_4`) strips. `CHROMA_PAIRS`
2737// counts the odd strips that close a 4:2:0 chroma pair
2738// (`is_chroma_reference`, av1_common_int.h:1454: bh == 1 mi => odd mi_row),
2739// `SUB8_PIECES` the pair chroma blocks whose TOP (LEFT) half was built from
2740// the PREVIOUS strip's own mv/ref/filters -- libaom
2741// `build_inter_predictors_sub8x8` (reconinter_template.inc:87-160), reached
2742// through `is_sub8x8_inter` (same file, :54).
2743thread_local! {
2744 static INTER16_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2745 static INTER16_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2746 static INTER16_CHROMA_PAIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2747 static INTER16_SUB8_PIECE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2748}
2749
2750// lane-intra16x4: INTRA-coded strips of an inter 16x16-level 1:4 partition --
2751// [0] 16x4, [1] 4x16, [2] the odd (chroma-reference) ones, which carry the
2752// pair's single 8x4 (4x8) chroma unit for BOTH strips.
2753thread_local! {
2754 static INTRA16X4_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
2755 const { std::cell::Cell::new([0; 3]) };
2756}
2757
2758/// `(intra 16x4 strips, intra 4x16 strips, of which chroma-reference)` decoded
2759/// inside an INTER 16x16-level 1:4 partition (lane-intra16x4).
2760pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) {
2761 let v = INTRA16X4_IN_INTER_HITS.with(std::cell::Cell::get);
2762 (v[0], v[1], v[2])
2763}
2764
2765/// Current values of the inter 16x16-level 1:4 counters: `(16x4 strips, 4x16
2766/// strips, chroma pairs closed, chroma pairs built from two different
2767/// strips' motion vectors)`.
2768pub fn inter16_rect4_counters() -> (usize, usize, usize, usize) {
2769 (
2770 INTER16_HORZ4_HITS.with(std::cell::Cell::get),
2771 INTER16_VERT4_HITS.with(std::cell::Cell::get),
2772 INTER16_CHROMA_PAIR_HITS.with(std::cell::Cell::get),
2773 INTER16_SUB8_PIECE_HITS.with(std::cell::Cell::get),
2774 )
2775}
2776
2777/// One 16x4 / 4x16 inter strip's chroma situation, handed to
2778/// [`decode_inter_block`] out of band (the same one-shot thread-local idiom
2779/// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites
2780/// that all mean "an ordinary block, chroma of its own".
2781#[derive(Clone, Copy)]
2782struct InterStripChroma {
2783 /// `is_chroma_reference` for this strip: false on strips 0 and 2, which
2784 /// read and reconstruct NO chroma at all.
2785 has_chroma: bool,
2786 /// `PARTITION_HORZ_4` (16x4 strips) rather than `PARTITION_VERT_4`.
2787 horz: bool,
2788 /// The mi position of the EVEN strip of this pair -- `setup_pred_plane`'s
2789 /// `if (ss_y && (mi_row & 1) && mi_size_high[bsize] == 1) mi_row -= 1`,
2790 /// i.e. the origin of the 8x4 (4x8) chroma transform.
2791 pair_mi: (usize, usize),
2792 /// The previous (even) strip's single-reference MC parameters, `None`
2793 /// when it was intra or compound -- `is_sub8x8_inter` then returns false
2794 /// and the whole chroma block is predicted from THIS strip's mv.
2795 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
2796}
2797
2798thread_local! {
2799 static INTER_STRIP_CHROMA: std::cell::Cell<Option<InterStripChroma>> =
2800 const { std::cell::Cell::new(None) };
2801 /// The single-reference MC parameters of the inter block that decoded
2802 /// last -- read by the next 1:4 strip to build its pair's chroma.
2803 static INTER_LAST_MC: std::cell::Cell<
2804 Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
2805 > = const { std::cell::Cell::new(None) };
2806}
2807
2808fn bump_ab16_inter(arm: usize) {
2809 AB16_INTER_HITS.with(|c| {
2810 let mut v = c.get();
2811 v[arm] += 1;
2812 c.set(v);
2813 });
2814}
2815
2816// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or
2817// 4x16 (`PARTITION_VERT_4`) strips, `CHROMA` counting the odd strips that
2818// close a 4:2:0 chroma pair and `COEFF` the strips with a coded residual.
2819thread_local! {
2820 static RECT4_16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2821 static RECT4_16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2822 static RECT4_16_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2823 static RECT4_16_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2824 static RECT4_16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2825 /// lane-kf1200: pairs whose chroma edge-filter type read from the PAIR's
2826 /// base mi differs from what the strip's own (odd) mi would have said --
2827 /// the shape that made 4 chroma samples of the ReelB `-ss 1200`
2828 /// key frame miss by 1. Zero here means a gate never exercised the fix.
2829 static RECT4_16_UV_PAIR_FILT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2830 /// lane-kf1200 r2: sub-8x8 chroma blocks that are `skip_txfm` AND
2831 /// `UV_CFL_PRED` -- the arm that used to drop the CfL alpha entirely.
2832 static SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2833}
2834
2835/// How many skipped sub-8x8 chroma blocks carried a CfL alpha (the shape
2836/// that reconstructed as flat DC before lane-kf1200 r2).
2837pub fn skip_cfl_hits() -> usize {
2838 SKIP_CFL_HITS.with(|c| c.get())
2839}
2840
2841/// How many 16x4/4x16 chroma pairs took a different `intra_edge_filter_type`
2842/// from the pair's base mi than the strip's own mi would have given.
2843pub fn rect4_16_uv_pair_filt_hits() -> usize {
2844 RECT4_16_UV_PAIR_FILT_HITS.with(|c| c.get())
2845}
2846
2847// lane-reelckf r1: the two chroma defects ReelC's key frames exposed --
2848// CHROMA_SKIP_CFL counts skipped intra blocks whose chroma is `UV_CFL_PRED`
2849// (prediction still runs, libaom `predict_and_reconstruct_intra_block`), and
2850// RECT4_16_CHROMA_DIR counts 1:4 chroma pairs predicted directionally (whose
2851// intra-edge filter type must come from the chroma-reference position).
2852thread_local! {
2853 static CHROMA_SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2854 static RECT4_16_CHROMA_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2855}
2856
2857/// `(skipped UV_CFL_PRED blocks, directional 1:4 chroma pairs)` -- lane-reelckf.
2858pub fn reelc_chroma_counters() -> (usize, usize) {
2859 (
2860 CHROMA_SKIP_CFL_HITS.with(|c| c.get()),
2861 RECT4_16_CHROMA_DIR_HITS.with(|c| c.get()),
2862 )
2863}
2864
2865/// Current values of the 16x16-level 1:4 counters: `(16x4 strips, 4x16
2866/// strips, chroma-reference strips, strips with a coded residual, strips
2867/// whose luma transform is split)`.
2868pub fn rect4_16_counters() -> (usize, usize, usize, usize, usize) {
2869 (
2870 RECT4_16_HORZ_HITS.with(|c| c.get()),
2871 RECT4_16_VERT_HITS.with(|c| c.get()),
2872 RECT4_16_CHROMA_HITS.with(|c| c.get()),
2873 RECT4_16_COEFF_HITS.with(|c| c.get()),
2874 RECT4_16_SPLIT_HITS.with(|c| c.get()),
2875 )
2876}
2877
2878/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded).
2879pub(crate) fn rect4_32_horz_hits() -> usize {
2880 RECT4_32_HORZ_HITS.with(|c| c.get())
2881}
2882
2883/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded).
2884pub(crate) fn rect4_32_vert_hits() -> usize {
2885 RECT4_32_VERT_HITS.with(|c| c.get())
2886}
2887
2888/// Current value of `RECT4_32_HORZ_INTER_HITS` (32x8 inter strips decoded).
2889pub(crate) fn rect4_32_horz_inter_hits() -> usize {
2890 RECT4_32_HORZ_INTER_HITS.with(|c| c.get())
2891}
2892
2893/// Current value of `RECT4_32_VERT_INTER_HITS` (8x32 inter strips decoded).
2894pub(crate) fn rect4_32_vert_inter_hits() -> usize {
2895 RECT4_32_VERT_INTER_HITS.with(|c| c.get())
2896}
2897
2898/// Current value of `INTER_SB_HORZ_HITS` (64x32 inter strips decoded).
2899pub(crate) fn inter_sb_horz_hits() -> usize {
2900 INTER_SB_HORZ_HITS.with(|c| c.get())
2901}
2902
2903/// Current value of `INTER_SB_VERT_HITS` (32x64 inter strips decoded).
2904pub(crate) fn inter_sb_vert_hits() -> usize {
2905 INTER_SB_VERT_HITS.with(|c| c.get())
2906}
2907
2908/// Current value of `INTER_SB_HORZ4_HITS` (64x16 inter strips decoded).
2909pub(crate) fn inter_sb_horz4_hits() -> usize {
2910 INTER_SB_HORZ4_HITS.with(|c| c.get())
2911}
2912
2913/// Current value of `INTER_SB_VERT4_HITS` (16x64 inter strips decoded).
2914pub(crate) fn inter_sb_vert4_hits() -> usize {
2915 INTER_SB_VERT4_HITS.with(|c| c.get())
2916}
2917
2918// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
2919// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
2920// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
2921// just inert-compiled. Zero forever on a passing gate means that gate's
2922// stream never carries `delta_q_present=1` through a rect64 block.
2923thread_local! {
2924 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
2925 const { std::cell::Cell::new(0) };
2926}
2927
2928/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
2929pub(crate) fn rect64_qidx_drift_hits() -> usize {
2930 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
2931}
2932
2933// lane-partab r1: how many 32x32 quadrants decoded an AB partition
2934// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
2935// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
2936// free-partition gate's proof this round's arms actually fired.
2937thread_local! {
2938 static PARTAB_HITS: std::cell::Cell<usize> =
2939 const { std::cell::Cell::new(0) };
2940}
2941
2942/// Current value of [`PARTAB_HITS`].
2943pub(crate) fn partab_hits() -> usize {
2944 PARTAB_HITS.with(|c| c.get())
2945}
2946
2947// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm,
2948// one counter per arm rather than one shared total -- the gate hard-asserts
2949// each of these individually nonzero so a recipe that only ever fires
2950// HORZ_A can't silently stand in for the whole set.
2951thread_local! {
2952 static INTRA_HORZ_A_HITS: std::cell::Cell<usize> =
2953 const { std::cell::Cell::new(0) };
2954 static INTRA_HORZ_B_HITS: std::cell::Cell<usize> =
2955 const { std::cell::Cell::new(0) };
2956 static INTRA_VERT_A_HITS: std::cell::Cell<usize> =
2957 const { std::cell::Cell::new(0) };
2958 static INTRA_VERT_B_HITS: std::cell::Cell<usize> =
2959 const { std::cell::Cell::new(0) };
2960}
2961
2962/// Current value of [`INTRA_HORZ_A_HITS`].
2963pub(crate) fn intra_horz_a_hits() -> usize {
2964 INTRA_HORZ_A_HITS.with(|c| c.get())
2965}
2966/// Current value of [`INTRA_HORZ_B_HITS`].
2967pub(crate) fn intra_horz_b_hits() -> usize {
2968 INTRA_HORZ_B_HITS.with(|c| c.get())
2969}
2970/// Current value of [`INTRA_VERT_A_HITS`].
2971pub(crate) fn intra_vert_a_hits() -> usize {
2972 INTRA_VERT_A_HITS.with(|c| c.get())
2973}
2974/// Current value of [`INTRA_VERT_B_HITS`].
2975pub(crate) fn intra_vert_b_hits() -> usize {
2976 INTRA_VERT_B_HITS.with(|c| c.get())
2977}
2978
2979// How many [`read_inter_compound_mode`] reads actually happened
2980// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
2981// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
2982// mvstack build), not just that `comp_mode` fired. Still refused right
2983// after (no MV assignment or MC wired), so this only counts attempted
2984// reads.
2985thread_local! {
2986 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
2987 const { std::cell::Cell::new(0) };
2988}
2989
2990/// Current value of [`COMPOUND_MODE_HITS`].
2991pub(crate) fn compound_mode_hits() -> usize {
2992 COMPOUND_MODE_HITS.with(|c| c.get())
2993}
2994
2995/// How many query blocks folded in at least one temporal MV candidate
2996/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
2997/// temporal-MV gate's own firing counter (lane-av1tmvp).
2998///
2999/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
3000/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
3001/// this file (`decode_inter_block`) still passes `tpl: None` -- this
3002/// counter compiles and the projection math it counts is unit-tested
3003/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
3004/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
3005/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
3006/// against any real stream today. See the module doc on
3007/// `crate::motion_field` and this crate's ledger for the remaining wiring.
3008pub(crate) fn tmv_hits() -> usize {
3009 crate::mvstack::tmv_hits()
3010}
3011
3012/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
3013/// produced on this thread, the 10-bit inter gate's firing proof.
3014pub(crate) fn inter_pred_hits() -> usize {
3015 crate::mc::inter_pred_hits()
3016}
3017
3018/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
3019/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
3020/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
3021/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
3022/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
3023/// needs to turn a query block's own resolved `ref_frame` into
3024/// `TplArgs::cur_offset_0` (spec 7.9.3).
3025pub(crate) struct TplFrameArgs<'a> {
3026 pub field: &'a crate::motion_field::TplField,
3027 pub order_hint_bits: u32,
3028 pub order_hint: u32,
3029 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
3030 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
3031 /// frame's own `ref_frame_idx` names for each single reference.
3032 pub ref_order_hints: [u32; 7],
3033}
3034
3035/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
3036/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
3037/// decoded `grid`: every 4x4 unit an inter block covers reads the same
3038/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
3039/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
3040/// exact — every block this crate ever codes is at least 8x8, so no 8x8
3041/// cell straddles two different blocks' values.
3042pub(crate) fn build_motion_field(
3043 grid: &MiGrid,
3044 mi_cols: usize,
3045 mi_rows: usize,
3046 order_hint: u32,
3047 order_hint_bits: u32,
3048 ref_order_hints: [u32; 7],
3049) -> crate::motion_field::MotionField {
3050 let mut field =
3051 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false);
3052 // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference
3053 // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other
3054 // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block
3055 // referencing one stores only its OTHER side's mv. With
3056 // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and
3057 // nothing is skipped.
3058 let other_side = |rf: i8| -> bool {
3059 if order_hint_bits == 0 {
3060 return false;
3061 }
3062 let oh = ref_order_hints[(rf - LAST_FRAME) as usize];
3063 crate::motion_field::get_relative_dist(order_hint_bits, oh, order_hint) > 0
3064 || oh == order_hint
3065 };
3066 // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is
3067 // capped at 12 bits per component; a longer one is not stored at all.
3068 const REFMVS_LIMIT: i32 = (1 << 12) - 1;
3069 for row in 0..mi_rows {
3070 for col in 0..mi_cols {
3071 let Some(info) = grid.get_frame(row, col) else {
3072 continue;
3073 };
3074 // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and
3075 // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`),
3076 // so an intra block -- or an inter block whose every slot is on the
3077 // other side / over the limit -- wipes what an earlier block wrote
3078 // into the same 8x8 cell (only reachable from sub-8x8 leaves, which
3079 // share a cell).
3080 if !info.is_inter {
3081 field.set(row, col, None);
3082 continue;
3083 }
3084 // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST
3085 // qualifying one wins -- a compound block stores its second
3086 // reference's mv, never its first (unless the second is on the
3087 // other side or over the limit). Storing slot 0 unconditionally
3088 // put the wrong (mv, ref_frame_offset) pair in every compound
3089 // block's cell, which a later frame's temporal candidate then
3090 // projected with the wrong reference distance.
3091 let mut saved: Option<crate::motion_field::SavedMv> = None;
3092 for (rf, mv) in [
3093 (info.ref_frame, Some(info.mv)),
3094 (info.ref_frame1.unwrap_or(0), info.mv1),
3095 ] {
3096 let (Some(mv), true) = (mv, rf > 0) else {
3097 continue;
3098 };
3099 if other_side(rf) {
3100 continue;
3101 }
3102 if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT {
3103 continue;
3104 }
3105 saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf });
3106 }
3107 field.set(row, col, saved);
3108 }
3109 }
3110 if std::env::var_os("EC_TRACE_TPL").is_some() {
3111 eprintln!("EC_TPL_SAVED oh={order_hint}");
3112 for (r, row) in field.occupancy().iter().enumerate() {
3113 eprintln!("EC_TPL_SAVED r{r} {row}");
3114 }
3115 }
3116 field
3117}
3118
3119/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
3120/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
3121pub(crate) fn ref_hits(ref_frame: i8) -> usize {
3122 let c = match ref_frame {
3123 LAST2_FRAME => &LAST2_HITS,
3124 LAST3_FRAME => &LAST3_HITS,
3125 GOLDEN_FRAME => &GOLDEN_HITS,
3126 BWDREF_FRAME => &BWDREF_HITS,
3127 ALTREF2_FRAME => &ALTREF2_HITS,
3128 ALTREF_FRAME => &ALTREF_HITS,
3129 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
3130 };
3131 c.with(|v| v.get())
3132}
3133
3134thread_local! {
3135 /// The sequence header's `enable_intra_edge_filter`, set once per
3136 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
3137 /// own read of it, kept off the call stack (see that function's own doc
3138 /// comment for why) rather than threaded through every `read_plane`/
3139 /// `decode_block`/`decode_leaf8` call between here and there.
3140 static ENABLE_EDGE_FILTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3141}
3142
3143/// Set [`ENABLE_EDGE_FILTER`] for this thread.
3144///
3145/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
3146/// never did -- so an inter frame's intra blocks read whatever value the last
3147/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
3148/// harmless (its own key frame sets it first), but a caller that decodes an
3149/// inter frame directly, or a test harness running several streams on one
3150/// thread, inherits a foreign sequence's bit: decode stops being a pure
3151/// function of the bitstream. `decode_stream` now calls this once per stream
3152/// from the sequence header, which covers every frame including inter ones.
3153pub(crate) fn set_enable_edge_filter(value: bool) {
3154 ENABLE_EDGE_FILTER.with(|f| f.set(value));
3155}
3156
3157/// Current value of [`ANGLE_DELTA_HITS`].
3158pub(crate) fn angle_delta_hits() -> usize {
3159 ANGLE_DELTA_HITS.with(|c| c.get())
3160}
3161
3162/// Current value of [`TX_CLASS1_HITS`].
3163pub(crate) fn tx_class1_hits() -> usize {
3164 TX_CLASS1_HITS.with(|c| c.get())
3165}
3166
3167// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent
3168// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion
3169// bottom) this thread's decode actually reconstructed -- the same
3170// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream
3171// genuinely exercised the sub-8x8 leaf path rather than every attempt
3172// coincidentally landing on `PARTITION_NONE`.
3173thread_local! {
3174 static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3175 /// How many 8x8 groups an INTER frame split into four BLOCK_4X4 inter
3176 /// sub-blocks (lane-intersub8).
3177 static SUB8_INTER_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3178 /// How many 8x8 groups an INTER frame split into two rectangular sub-8x8
3179 /// inter leaves (lane-intersub8 r3), indexed `[0] = HORZ` (two BLOCK_8X4),
3180 /// `[1] = VERT` (two BLOCK_4X8).
3181 static SUB8_INTER_RECT_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
3182 /// lane-sub8intra: INTRA leaves decoded inside an inter frame's sub-8x8
3183 /// HORZ/VERT partition -- `[0]` 8x4, `[1]` 4x8, `[2]` of those that were
3184 /// the chroma reference (so coded the group's 4x4 chroma intra), `[3]`
3185 /// MIXED groups whose chroma reference is INTER while its sibling is
3186 /// intra (the `is_sub8x8_inter` false path), `[4]` INTRA `BLOCK_4X4`
3187 /// leaves of an inter frame's sub-8x8 `PARTITION_SPLIT` (lane-sub8x4 r2 --
3188 /// the second lifted refusal's own witness; `[0]`/`[1]` count those too,
3189 /// so only this cell separates the split arm from the HORZ/VERT one).
3190 static SUB8_INTRA_RECT_HITS: std::cell::Cell<[usize; 5]> = const { std::cell::Cell::new([0; 5]) };
3191}
3192
3193/// Current value of [`SUB8_INTRA_RECT_HITS`]: `(8x4, 4x8, chroma-reference,
3194/// mixed groups, split 4x4 leaves)`.
3195pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) {
3196 SUB8_INTRA_RECT_HITS.with(|c| {
3197 let h = c.get();
3198 (h[0], h[1], h[2], h[3], h[4])
3199 })
3200}
3201
3202/// Current value of [`SUB8_INTER_RECT_HITS`]: `(8x4 groups, 4x8 groups)`.
3203pub fn sub8_inter_rect_hits() -> (usize, usize) {
3204 SUB8_INTER_RECT_HITS.with(|c| {
3205 let h = c.get();
3206 (h[0], h[1])
3207 })
3208}
3209
3210// lane-cdef r1: (a) how many 8x8 CDEF units `apply_cdef` EXCLUDED because all
3211// four of their mi cells are `skip_txfm` (libaom `cdef.c:29-38`
3212// `is_8x8_block_skip` / `av1_cdef_compute_sb_list`'s dlist test), and (b) how
3213// many 8x8 inter leaves (`decode_inter_block8`) wrote that skip band at all.
3214// (b) was 0 for every stream before this round -- the leaf path never touched
3215// the band, so an all-skip 8x8 group kept the PREVIOUS frame's flags and got
3216// filtered where libaom skips it. A gate asserts both are non-zero.
3217thread_local! {
3218 static CDEF_SKIPPED_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3219 static INTER8_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3220 // lane-cdef r2: (c) 8x8 CDEF units that are FILTERED and whose extent
3221 // crosses the cropped frame edge -- the only units for which "clamp at
3222 // the crop" and "pad past the mi-rounded extent with CDEF_VERY_LARGE"
3223 // (libaom `cdef.c:249-256`, `cdef_prepare_fb`'s hsize/vsize are
3224 // `nhb << mi_wide_l2` off the MI grid, not the crop) differ. A frame
3225 // whose width or height is not a multiple of 8 is the only shape that
3226 // produces one; the straddling-band gate arms assert it grew.
3227 static CDEF_STRADDLE_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3228 // lane-cdefstrip r1: 8x8 CDEF units visited with an UNWRITTEN skip band
3229 // (see `Neighbours::skip_written`).
3230 static CDEF_UNWRITTEN_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3231 // lane-cdefstrip r1: (d) skip RECTANGULAR blocks (every strip arm: 32x8,
3232 // 8x32, 16x8, 32x16, 64x16, AB/1:4 pieces...) that wrote the CDEF skip
3233 // band, and (e) 8x8 CDEF units whose four mi cells do NOT agree on skip --
3234 // the shape libaom's `is_8x8_block_skip` (`cdef.c:29-38`) exists for: an
3235 // 8-tall strip pair where only one half is skip must still be FILTERED.
3236 static RECT_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3237 static CDEF_MIXED_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3238}
3239
3240/// Current value of `RECT_SKIP_BAND_HITS`.
3241pub fn rect_skip_band_hits() -> usize {
3242 RECT_SKIP_BAND_HITS.with(|c| c.get())
3243}
3244
3245/// Current value of `CDEF_MIXED_SKIP_UNITS`.
3246pub fn cdef_mixed_skip_units() -> usize {
3247 CDEF_MIXED_SKIP_UNITS.with(|c| c.get())
3248}
3249
3250/// Current value of `CDEF_SKIPPED_UNITS`.
3251pub(crate) fn cdef_skipped_units() -> usize {
3252 CDEF_SKIPPED_UNITS.with(|c| c.get())
3253}
3254
3255/// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded
3256/// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1).
3257pub fn cdef_unwritten_skip_units() -> usize {
3258 CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get())
3259}
3260
3261/// Current value of `INTER8_SKIP_BAND_HITS`.
3262pub(crate) fn inter8_skip_band_hits() -> usize {
3263 INTER8_SKIP_BAND_HITS.with(|c| c.get())
3264}
3265
3266/// Current value of `CDEF_STRADDLE_UNITS`.
3267pub(crate) fn cdef_straddle_units() -> usize {
3268 CDEF_STRADDLE_UNITS.with(|c| c.get())
3269}
3270
3271/// Current value of [`SUB8_SPLIT_HITS`].
3272pub(crate) fn sub8_split_hits() -> usize {
3273 SUB8_SPLIT_HITS.with(|c| c.get())
3274}
3275
3276/// Current value of [`SUB8_INTER_SPLIT_HITS`].
3277pub fn sub8_inter_split_hits() -> usize {
3278 SUB8_INTER_SPLIT_HITS.with(|c| c.get())
3279}
3280
3281// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ`
3282// of an 8x8 block) this thread's decode reconstructed with REAL coefficients
3283// -- a skipped leaf exercises the prediction and the mi bookkeeping but never
3284// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate
3285// asserts on these two rather than a plain leaf count.
3286thread_local! {
3287 static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3288 static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3289 /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's
3290 /// two 4x4 transform units, predicted one after the other. A separate
3291 /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so
3292 /// the gate can prove THIS path fired.
3293 static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3294 /// 16x8/8x16 intra strips whose prediction actually read past the block's
3295 /// own width (above-right) or height (below-left) -- the samples
3296 /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/
3297 /// `has_bl_*` table row can corrupt (lane-tx4x8 r3).
3298 static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3299 /// Every 16x8/8x16 intra strip predicted, reaching or not -- the
3300 /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of.
3301 static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3302}
3303
3304/// Current value of [`RECT8_SPLIT_TX_HITS`].
3305pub(crate) fn rect8_split_tx_hits() -> usize {
3306 RECT8_SPLIT_TX_HITS.with(|c| c.get())
3307}
3308
3309/// Current value of [`RECT_STRIP_PRED_HITS`].
3310pub(crate) fn rect_strip_pred_hits() -> usize {
3311 RECT_STRIP_PRED_HITS.with(|c| c.get())
3312}
3313
3314/// Current value of [`RECT_STRIP_REACH_HITS`].
3315pub(crate) fn rect_strip_reach_hits() -> usize {
3316 RECT_STRIP_REACH_HITS.with(|c| c.get())
3317}
3318
3319/// Current value of [`TX4X8_CODED_HITS`].
3320pub(crate) fn tx4x8_coded_hits() -> usize {
3321 TX4X8_CODED_HITS.with(|c| c.get())
3322}
3323
3324/// Current value of [`TX8X4_CODED_HITS`].
3325pub(crate) fn tx8x4_coded_hits() -> usize {
3326 TX8X4_CODED_HITS.with(|c| c.get())
3327}
3328
3329// How many CHROMA coefficient blocks read their `eob_pt` from the class-1
3330// (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread.
3331// Chroma never codes a `tx_type` symbol -- it inherits the colocated luma
3332// type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on
3333// an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired
3334// (`eob_pt_{16,64,128,256}_chroma_class1`).
3335thread_local! {
3336 static CHROMA_EOB_CLASS1_HITS: std::cell::Cell<usize> =
3337 const { std::cell::Cell::new(0) };
3338}
3339
3340/// Current value of [`CHROMA_EOB_CLASS1_HITS`].
3341pub(crate) fn chroma_eob_class1_hits() -> usize {
3342 CHROMA_EOB_CLASS1_HITS.with(|c| c.get())
3343}
3344
3345/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
3346/// `tx_type` put this block's `eob_pt` on the class-1 row.
3347fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
3348 if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD {
3349 CHROMA_EOB_CLASS1_HITS.with(|c| c.set(c.get() + 1));
3350 }
3351}
3352
3353const SUB_MI: u32 = 4;
3354const MI: usize = 4;
3355const SB: usize = 64;
3356/// The `above_side`/`left_side` value a cell with no decoded neighbour holds
3357/// (tile start, superblock-row start).
3358///
3359/// [`Neighbours::partition_ctx_mi`] reads it as libaom's
3360/// `av1_get_partition_plane_context` reads its own zero-initialised
3361/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at
3362/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB`
3363/// (64), which reads identically at every level up to 64x64 but sets the bit
3364/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition
3365/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec
3366/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`).
3367const NO_NEIGHBOUR_SIDE: usize = 128;
3368const BLOCK: usize = 32;
3369const SUB: usize = 16;
3370const TX32: usize = 32;
3371const TX16: usize = 16;
3372const TX8: usize = 8;
3373const TX4: usize = 4;
3374const DC_PRED: usize = 0;
3375/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
3376/// carries an angle delta — [`crate::tile`]'s own private copy of the same
3377/// constant.
3378const V_PRED: usize = 1;
3379const H_PRED: usize = 2;
3380/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
3381/// `Fimode_To_Intradir`, libaom `blockd.h`).
3382const D157_PRED: usize = 6;
3383/// The last directional mode, `D67_PRED`.
3384const D67_PRED: usize = 8;
3385/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
3386/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
3387/// codes anything else, so this decoder never reads anything else either.
3388const ANGLE_DELTA_ZERO: usize = 3;
3389const NUM_BASE_LEVELS: i32 = 2;
3390const COEFF_BASE_RANGE: i32 = 12;
3391const BR_STEP: i32 = 3;
3392const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
3393
3394/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
3395/// whose probability mass a superblock or block half outside the frame
3396/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
3397/// duplicated here (that module is another lane's territory this round) and
3398/// kept in step with it by the byte-exact round-trip tests below rather than
3399/// by sharing code.
3400const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
3401const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
3402
3403fn trace_edge(mi_r: usize, mi_c: usize, bsize: u32, ctx: usize, rng: u32) {
3404 if std::env::var_os("EC_AV1_TRACE").is_some() {
3405 eprintln!("OUR_PART mi_row={mi_r} mi_col={mi_c} bsize={bsize} ctx={ctx} rng={rng}");
3406 }
3407}
3408
3409fn element_prob(cdf: &[u16], element: usize) -> u16 {
3410 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
3411}
3412
3413/// The two-symbol CDF a partial superblock/block's forced-split flag is read
3414/// with: the mass of `elements` becomes the probability of the one partition
3415/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
3416/// (the encoder's non-adapting counterpart to this read).
3417fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
3418 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
3419 [32768 - split, 32768, 0]
3420}
3421
3422fn unsupported(what: impl Into<String>) -> Error {
3423 Error::unsupported("AV1 tile", what.into())
3424}
3425
3426/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
3427/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
3428/// same rule.
3429pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
3430 match base_q_idx {
3431 0..=20 => 0,
3432 21..=60 => 1,
3433 61..=120 => 2,
3434 _ => 3,
3435 }
3436}
3437
3438/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
3439/// [`crate::tile`]'s writer generates its scan tables with.
3440fn default_scan(side: usize) -> Vec<u16> {
3441 let mut scan = Vec::with_capacity(side * side);
3442 for d in 0..(2 * side - 1) {
3443 let lo = d.saturating_sub(side - 1);
3444 let hi = d.min(side - 1);
3445 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
3446 if d % 2 == 0 {
3447 scan.extend(diagonal.rev());
3448 } else {
3449 scan.extend(diagonal);
3450 }
3451 }
3452 scan
3453}
3454
3455/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
3456/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
3457/// in, instead of the default zigzag. libaom's own tables are keyed by a
3458/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
3459/// physically column-major level buffer, but they decompose to the exact
3460/// same (row, col) walk as a flat row-major traversal of *our* row-major
3461/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
3462/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
3463/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
3464/// transposed (column 0 down every row, then column 1, ...).
3465fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
3466 class_scan_table_wh(side, side, class)
3467}
3468
3469/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
3470/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
3471/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
3472/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
3473/// transcribed with -- `mrow` is the plain row-major raster in our indexing
3474/// and `mcol` its transpose, at rect sizes exactly as at square ones.
3475fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
3476 match class {
3477 TxClass::Vert => (0..(w * h) as u16).collect(),
3478 TxClass::Horiz => (0..w)
3479 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
3480 .collect(),
3481 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
3482 }
3483}
3484
3485fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
3486 match scan_idx {
3487 0 => 0,
3488 i if i <= area / 8 => 1,
3489 i if i <= area / 4 => 2,
3490 _ => 3,
3491 }
3492}
3493
3494fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
3495 if row >= side || col >= side {
3496 0
3497 } else {
3498 grid[row * side + col]
3499 }
3500}
3501
3502/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
3503/// `txb_common.h`): everything but the two lone-axis-identity types this
3504/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
3505#[derive(Clone, Copy, PartialEq, Eq)]
3506enum TxClass {
3507 TwoD,
3508 Horiz,
3509 Vert,
3510}
3511
3512impl TxClass {
3513 fn of(tx_type: TxType) -> Self {
3514 match tx_type {
3515 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
3516 // key on axis alone -- FLIPADST is still ADST for this purpose.
3517 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
3518 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
3519 _ => Self::TwoD,
3520 }
3521 }
3522}
3523
3524/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
3525/// table (indexed by the position along the transform's *coded* axis --
3526/// `col` for horiz, `row` for vert) that places their contexts past the 2D
3527/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
3528/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
3529fn nz_map_ctx_offset_1d(i: usize) -> usize {
3530 match i {
3531 0 => 26,
3532 1 => 31,
3533 _ => 36,
3534 }
3535}
3536
3537fn base_ctx(
3538 grid: &[i32],
3539 side: usize,
3540 row: usize,
3541 col: usize,
3542 class: TxClass,
3543 rect_shape: Option<(usize, usize)>,
3544) -> usize {
3545 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
3546 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
3547 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
3548 // position through the full 1D neighbour sum and offset table. Skipping
3549 // that for every class desynced the last (DC) coefficient of a
3550 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
3551 // 0, which then read one extra `BR` symbol at the max and forced a
3552 // spurious third Golomb call).
3553 if class == TxClass::TwoD && row == 0 && col == 0 {
3554 return 0;
3555 }
3556 let offsets: [(usize, usize); 5] = match class {
3557 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
3558 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
3559 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
3560 };
3561 let mag: i32 = offsets
3562 .iter()
3563 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
3564 .sum();
3565 let ctx = ((mag + 1) >> 1).min(4) as usize;
3566 match class {
3567 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
3568 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
3569 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
3570 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
3571 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
3572 // strip, which own a genuinely different table from the square one
3573 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
3574 // square table vs the real ctx 13 the rect table gives).
3575 TxClass::TwoD => {
3576 // lane-rectsplit r4: apply libaom's GENERATING RULE
3577 // (`txb_common.h:199-209`) directly instead of indexing the
3578 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
3579 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
3580 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
3581 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
3582 // so 32 consecutive entries are one COLUMN: the [`cdf`]
3583 // transcriptions are `[col][row]` and this read had them as
3584 // `[row][col]` -- the transpose, i.e. the other shape's rule with
3585 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
3586 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
3587 // pins the rule against the tables over their whole 5x5 domain.
3588 if let Some((w, h)) = rect_shape {
3589 if std::env::var_os("EC_NZOFF_DUMP").is_some() {
3590 eprintln!("NZOFF side={side} shape={w}x{h} row={row} col={col}");
3591 }
3592 if w < h && row < 2 {
3593 return ctx + 11;
3594 }
3595 if w > h && col < 2 {
3596 return ctx + 16;
3597 }
3598 }
3599 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
3600 }
3601 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
3602 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
3603 }
3604}
3605
3606fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize, class: TxClass) -> usize {
3607 let extra = match class {
3608 TxClass::TwoD => neighbour(grid, side, row + 1, col + 1).abs(),
3609 TxClass::Horiz => neighbour(grid, side, row, col + 2).abs(),
3610 TxClass::Vert => neighbour(grid, side, row + 2, col).abs(),
3611 };
3612 let mag = neighbour(grid, side, row + 1, col).abs()
3613 + neighbour(grid, side, row, col + 1).abs()
3614 + extra;
3615 let mag = (((mag + 1) >> 1).min(6)) as usize;
3616 if row == 0 && col == 0 {
3617 return mag;
3618 }
3619 let near_origin = match class {
3620 TxClass::TwoD => row < 2 && col < 2,
3621 TxClass::Horiz => col == 0,
3622 TxClass::Vert => row == 0,
3623 };
3624 if near_origin { mag + 7 } else { mag + 14 }
3625}
3626
3627/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
3628/// transposed from libaom's column-major buffer into this decoder's row-major
3629/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
3630/// against the real table). Not the square zigzag formula generalized to
3631/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
3632const SCAN_32X16: [u16; 512] = [
3633 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161,
3634 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39,
3635 8, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72,
3636 41, 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229,
3637 198, 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44,
3638 13, 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418,
3639 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326,
3640 295, 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234,
3641 203, 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142,
3642 111, 80, 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19,
3643 485, 454, 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424,
3644 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332,
3645 301, 270, 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240,
3646 209, 178, 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148,
3647 117, 86, 55, 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25,
3648 491, 460, 429, 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430,
3649 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338,
3650 307, 276, 245, 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246,
3651 215, 184, 153, 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154,
3652 123, 92, 61, 30, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31,
3653 497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405,
3654 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251,
3655 220, 189, 158, 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439,
3656 408, 377, 346, 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503,
3657 472, 441, 410, 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443,
3658 412, 381, 350, 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415,
3659 509, 478, 447, 510, 479, 511,
3660];
3661
3662/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
3663/// [`SCAN_32X16`]'s doc comment).
3664const SCAN_16X32: [u16; 512] = [
3665 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,
3666 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
3667 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
3668 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
3669 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
3670 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
3671 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
3672 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
3673 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
3674 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
3675 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
3676 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
3677 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
3678 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
3679 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
3680 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
3681 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
3682 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
3683 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
3684 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
3685 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
3686 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
3687 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
3688 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
3689 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
3690 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
3691];
3692
3693/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
3694/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
3695/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
3696/// the same source).
3697const SCAN_4X8: [u16; 32] = [
3698 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,
3699 23, 26, 29, 27, 30, 31,
3700];
3701
3702/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
3703const SCAN_8X4: [u16; 32] = [
3704 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,
3705 29, 22, 15, 30, 23, 31,
3706];
3707
3708/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
3709/// [`SCAN_32X16`]'s doc comment).
3710const SCAN_16X8: [u16; 128] = [
3711 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,
3712 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
3713 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
3714 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
3715 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
3716 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
3717];
3718
3719/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
3720/// [`SCAN_32X16`]'s doc comment).
3721const SCAN_8X16: [u16; 128] = [
3722 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,
3723 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
3724 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
3725 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
3726 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
3727 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
3728];
3729
3730/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
3731/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
3732/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
3733/// scans column-major (`p = col * height + row`), so a naive copy of
3734/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
3735/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
3736/// are byte-identical to this decoder's [`SCAN_8X16`].
3737const SCAN_32X8: [u16; 256] = [
3738 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
3739 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226, 195,
3740 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104, 73, 42,
3741 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200, 169,
3742 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78, 47, 16,
3743 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205, 174, 143,
3744 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83, 52, 21, 239,
3745 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210, 179, 148, 117,
3746 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88, 57, 26, 244, 213,
3747 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215, 184, 153, 122, 91,
3748 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93, 62, 31, 249, 218, 187,
3749 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127, 252, 221, 190, 159, 253,
3750 222, 191, 254, 223, 255,
3751];
3752/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
3753/// 16x64 `PARTITION_VERT_4` strip).
3754const SCAN_8X32: [u16; 256] = [
3755 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,
3756 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
3757 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
3758 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
3759 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
3760 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
3761 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
3762 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
3763 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
3764 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
3765 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
3766 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
3767 239, 246, 253, 247, 254, 255,
3768];
3769/// `Default_Scan_16x4`, this decoder's own row-major transcription of
3770/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
3771/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
3772/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
3773/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
3774/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
3775/// were emitted -- a naive copy installs the transpose (class
3776/// reference-layout-not-spec).
3777const SCAN_16X4: [u16; 64] = [
3778 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,
3779 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
3780 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
3781];
3782/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
3783/// 8x32 `PARTITION_VERT_4` strip).
3784const SCAN_4X16: [u16; 64] = [
3785 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,
3786 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
3787 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
3788];
3789
3790/// [`neighbour`] with independent `w` (row stride)/`h` (row-bound) extents
3791/// (lane-rectwire, mirrors [`record_rect`](Neighbours::record_rect)'s
3792/// asymmetric-extent pattern).
3793fn neighbour_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> i32 {
3794 if row >= h || col >= w {
3795 0
3796 } else {
3797 grid[row * w + col]
3798 }
3799}
3800
3801/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
3802/// the rect generalization is libaom's own comment in
3803/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
3804/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
3805/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
3806/// [`decode_block_rect`] codes (see that function's own doc comment).
3807fn base_ctx_rect(
3808 grid: &[i32],
3809 w: usize,
3810 h: usize,
3811 row: usize,
3812 col: usize,
3813 class: TxClass,
3814) -> usize {
3815 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
3816 // the 2D class short-circuits the DC position.
3817 if class == TxClass::TwoD && row == 0 && col == 0 {
3818 return 0;
3819 }
3820 let offsets: [(usize, usize); 5] = match class {
3821 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
3822 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
3823 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
3824 };
3825 let mag: i32 = offsets
3826 .iter()
3827 .map(|&(dr, dc)| neighbour_rect(grid, w, h, row + dr, col + dc).abs().min(3))
3828 .sum();
3829 let ctx = ((mag + 1) >> 1).min(4) as usize;
3830 match class {
3831 TxClass::TwoD => {
3832 if w < h && row < 2 {
3833 return ctx + 11;
3834 }
3835 if w > h && col < 2 {
3836 return ctx + 16;
3837 }
3838 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
3839 }
3840 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
3841 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
3842 // position along one axis only).
3843 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
3844 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
3845 }
3846}
3847
3848/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
3849/// neighbour-offset math itself is shape-independent, only the boundary
3850/// clamp needs the real bound in each axis.
3851fn br_ctx_rect(
3852 grid: &[i32],
3853 w: usize,
3854 h: usize,
3855 row: usize,
3856 col: usize,
3857 class: TxClass,
3858) -> usize {
3859 let extra = match class {
3860 TxClass::TwoD => neighbour_rect(grid, w, h, row + 1, col + 1).abs(),
3861 TxClass::Horiz => neighbour_rect(grid, w, h, row, col + 2).abs(),
3862 TxClass::Vert => neighbour_rect(grid, w, h, row + 2, col).abs(),
3863 };
3864 let mag = neighbour_rect(grid, w, h, row + 1, col).abs()
3865 + neighbour_rect(grid, w, h, row, col + 1).abs()
3866 + extra;
3867 let mag = (((mag + 1) >> 1).min(6)) as usize;
3868 if row == 0 && col == 0 {
3869 return mag;
3870 }
3871 let near_origin = match class {
3872 TxClass::TwoD => row < 2 && col < 2,
3873 TxClass::Horiz => col == 0,
3874 TxClass::Vert => row == 0,
3875 };
3876 if near_origin { mag + 7 } else { mag + 14 }
3877}
3878
3879fn dc_vote(dc: Option<bool>) -> i32 {
3880 match dc {
3881 None => 0,
3882 Some(true) => -1,
3883 Some(false) => 1,
3884 }
3885}
3886
3887fn dc_sign_ctx(vote: i32) -> usize {
3888 match vote.signum() {
3889 0 => 0,
3890 -1 => 1,
3891 _ => 2,
3892 }
3893}
3894
3895/// The remainder of a level the base and base-range syntax could not reach
3896/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
3897/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
3898fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
3899 // lane-scaledref r1: this cap MASKS A REAL DEFECT and must not be lifted
3900 // on its own. Reading up to 32 leading zeros (dav1d's `len < 32`; libaom
3901 // itself calls a 21st bit a corrupt frame, decodetxb.c:30) is bit-identical
3902 // for every tail any encoder writes -- our own writer tops out at 19 zeros
3903 // (`tile::MAX_LEVEL == MAX_BR_LEVEL + (1 << 19)`) -- and was implemented
3904 // and round-trip tested here (commit ee1f980, reverted in 314ee08). It
3905 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
3906 // RED: seed 67 stops here today, and with the cap raised it decodes to a
3907 // frame-0 LUMA MISMATCH instead. A key frame cannot legitimately carry a
3908 // level above 1<<19, so the long tail is the SYMPTOM of an earlier desync
3909 // in that intra rect64 stream -- class `refusal-hides-a-defect`. Lift this
3910 // together with that defect's fix, not before.
3911 let mut length = 1u32;
3912 while dec.literal(1) == 0 {
3913 length += 1;
3914 if length > 20 {
3915 return Err(unsupported("a Golomb tail longer than this decoder reads"));
3916 }
3917 }
3918 let mut x = 1u32;
3919 for _ in 1..length {
3920 x = (x << 1) | dec.literal(1);
3921 }
3922 Ok(x - 1)
3923}
3924
3925/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
3926/// [`crate::tile`]'s `write_eob`.
3927fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
3928 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
3929 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
3930
3931 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
3932 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
3933 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
3934 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
3935 // `eob_multi_ctx`). Missing that split desynced the very first
3936 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
3937 // against a real aomdec trace).
3938 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
3939 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
3940 (_, Some(class1)) => class1,
3941 };
3942 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
3943 let (range, value) = dec.debug_state();
3944 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
3945 }
3946 let group = dec.symbol(eob_pt) + 1;
3947 if trace {
3948 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
3949 }
3950 let bits = OFFSET_BITS[group];
3951 let mut offset = 0u32;
3952 if bits > 0 {
3953 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
3954 if trace {
3955 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
3956 }
3957 offset = top << (bits - 1);
3958 if bits > 1 {
3959 offset |= dec.literal(bits - 1);
3960 }
3961 }
3962 GROUP_START[group] + offset as usize
3963}
3964
3965/// One transform block's levels, the inverse of [`crate::tile`]'s
3966/// `write_coeffs`, returned as a `side * side` grid in raster order, along
3967/// with the transform type that grid was coded under (`DCT_DCT` when the
3968/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
3969/// 64-point transforms, which never code anything else).
3970///
3971/// # Errors
3972/// Returns an error if the `tx_type` symbol decodes to a value outside its
3973/// CDF's own set (a corrupt or unsupported bitstream) — every value the
3974/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
3975/// produce dispatches to a real inverse transform.
3976/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
3977/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
3978/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
3979/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
3980/// the plane's own predicted mode instead. Every entry this table can
3981/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
3982/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
3983/// table ever names), so unlike the CDF-coded luma path there is no
3984/// ext-tx-set membership check to fall back from here.
3985fn default_intra_tx_type(mode: u8) -> TxType {
3986 use crate::intra::{
3987 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
3988 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
3989 };
3990 match mode {
3991 DC_PRED | D45_PRED => TxType::DctDct,
3992 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
3993 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
3994 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
3995 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
3996 }
3997}
3998
3999/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
4000/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
4001/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
4002fn is_smooth_mode(mode: usize) -> bool {
4003 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
4004}
4005
4006fn read_coeffs(
4007 dec: &mut SymbolDecoder,
4008 coding: &mut TxbTables,
4009 scan: &[u16],
4010 skip_ctx: usize,
4011 sign_ctx: usize,
4012 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
4013 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
4014 // nothing at all; `DctDct` for every luma call and every chroma call at
4015 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
4016 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
4017 default_tx_type: TxType,
4018 // `Some((w, h))` with `w != h` when this read is a superblock-level
4019 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
4020 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
4021 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
4022 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
4023 // caller's block genuinely is `side` x `side`.
4024 rect_shape: Option<(usize, usize)>,
4025) -> Result<(Vec<i32>, TxType)> {
4026 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
4027 let side = coding.side;
4028 let mut grid = vec![0i32; side * side];
4029 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
4030 let (range, value) = dec.debug_state();
4031 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
4032 }
4033 let dbg_txbskip = if std::env::var_os("EC_TRACE_COEFF").is_some() {
4034 coding.txb_skip[skip_ctx]
4035 } else {
4036 [0; 3]
4037 };
4038 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
4039 if std::env::var_os("EC_TRACE_COEFF").is_some() {
4040 let (rng, _) = dec.debug_state();
4041 eprintln!(
4042 "EC_COEFF_STEP tag=all_zero side={} ctx={skip_ctx} cdf={dbg_txbskip:?} all_zero={} rng={rng}",
4043 coding.side,
4044 all_zero as i32
4045 );
4046 }
4047 if std::env::var_os("EC_AV1_TELL").is_some() {
4048 eprintln!(
4049 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
4050 all_zero as u8, dec.debug_bitpos(), dec.debug_state().0
4051 );
4052 }
4053 if trace {
4054 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
4055 }
4056 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
4057 let (range, value) = dec.debug_state();
4058 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
4059 }
4060 if all_zero {
4061 return Ok((grid, TxType::DctDct));
4062 }
4063 let mut tx_type = default_tx_type;
4064 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
4065 // The CDF row's own width names its set (lane-cdffwd2: extended
4066 // past the original two-way intra split once wider `reduced_tx_set
4067 // == 0` inter sets joined the table): 17 slots (16 symbols) is
4068 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
4069 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
4070 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
4071 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
4072 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
4073 let len = tx_type_cdf.len();
4074 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() && len == 3 {
4075 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
4076 }
4077 let t = dec.symbol(tx_type_cdf);
4078 if std::env::var_os("EC_TRACE_COEFF").is_some() {
4079 let (rng, _) = dec.debug_state();
4080 eprintln!("EC_COEFF_STEP tag=tx_type len={len} rng={rng}");
4081 }
4082 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
4083 let (range, value) = dec.debug_state();
4084 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
4085 }
4086 if trace {
4087 eprintln!("TRACE tx_type value={t} len={len}");
4088 }
4089 tx_type = match len {
4090 17 => TxType::from_symbol_all16(t),
4091 13 => TxType::from_symbol_set2_12(t),
4092 8 => TxType::from_symbol_set1(t),
4093 _ => TxType::from_symbol(t),
4094 }
4095 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
4096 }
4097
4098 let class = TxClass::of(tx_type);
4099 if class != TxClass::TwoD {
4100 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
4101 RECT_CLASS1_HITS.with(|c| c.set(c.get() + 1));
4102 }
4103 let eob = read_eob(dec, coding, class);
4104 if trace {
4105 eprintln!("TRACE eob value={eob}");
4106 }
4107 let ec_trace_coeff = std::env::var_os("EC_TRACE_COEFF").is_some();
4108 if ec_trace_coeff {
4109 let (rng, _) = dec.debug_state();
4110 let cls = match class { TxClass::TwoD => "2d", TxClass::Horiz => "horiz", TxClass::Vert => "vert" };
4111 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
4112 }
4113 let class_scan;
4114 let scan: &[u16] = if class == TxClass::TwoD {
4115 scan
4116 } else {
4117 class_scan = class_scan_table(side, class);
4118 &class_scan
4119 };
4120 let mut levels = vec![0i32; side * side];
4121 for scan_idx in (0..eob).rev() {
4122 let pos = scan[scan_idx] as usize;
4123 let (row, col) = (pos / side, pos % side);
4124 let level = if scan_idx == eob - 1 {
4125 let ctx = eob_coeff_ctx(scan_idx, side * side);
4126 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
4127 if trace {
4128 eprintln!(
4129 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
4130 );
4131 }
4132 v
4133 } else {
4134 let ctx = base_ctx(&levels, side, row, col, class, rect_shape);
4135 let v = dec.symbol(&mut coding.base[ctx]) as i32;
4136 if ec_trace_coeff {
4137 let (rng, _) = dec.debug_state();
4138 // `pos` in libaom's column-major `coeff_idx` convention, so
4139 // the ladder lines up with instrumented `aomdec`.
4140 let apos = col * side + row;
4141 eprintln!(
4142 "EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}"
4143 );
4144 }
4145 if trace {
4146 eprintln!(
4147 "TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
4148 );
4149 }
4150 v
4151 };
4152 let level = if level > NUM_BASE_LEVELS {
4153 let ctx = br_ctx(&levels, side, row, col, class);
4154 let mut level = level;
4155 let mut sent = 0;
4156 loop {
4157 let k = dec.symbol(&mut coding.br[ctx]) as i32;
4158 if ec_trace_coeff {
4159 // lane-leaf8tx r3: the `br` rung was missing from THIS
4160 // path's trace, so the cross-decoder range ladder was
4161 // blind to every base-range symbol and mis-reported the
4162 // first divergence (class [[gate-blind-to-feature]]).
4163 let (rng, _) = dec.debug_state();
4164 let apos = col * side + row;
4165 eprintln!(
4166 "EC_COEFF_STEP tag=br c={scan_idx} pos={apos} ctx={ctx} k={k} rng={rng}"
4167 );
4168 }
4169 if trace {
4170 eprintln!(
4171 "TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}"
4172 );
4173 }
4174 level += k;
4175 sent += BR_STEP;
4176 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
4177 break;
4178 }
4179 }
4180 level
4181 } else {
4182 level
4183 };
4184 if ec_trace_coeff && scan_idx == eob - 1 {
4185 let (rng, _) = dec.debug_state();
4186 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
4187 }
4188 levels[pos] = level;
4189 }
4190 if ec_trace_coeff {
4191 let (rng, _) = dec.debug_state();
4192 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
4193 }
4194
4195 for (c, &pos) in scan[..eob].iter().enumerate() {
4196 let level = levels[pos as usize];
4197 if level == 0 {
4198 continue;
4199 }
4200 let negative = if pos == 0 {
4201 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
4202 if trace {
4203 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
4204 }
4205 v
4206 } else {
4207 dec.literal(1) == 1
4208 };
4209 if ec_trace_coeff {
4210 let (rng, _) = dec.debug_state();
4211 eprintln!("EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}", negative as i32);
4212 }
4213 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
4214 let g = read_golomb(dec)?;
4215 if trace {
4216 eprintln!("TRACE golomb pos={pos} value={g}");
4217 }
4218 level + g as i32
4219 } else {
4220 level
4221 };
4222 if ec_trace_coeff {
4223 let (rng, _) = dec.debug_state();
4224 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
4225 }
4226 grid[pos as usize] = if negative { -level } else { level };
4227 }
4228 Ok((grid, tx_type))
4229}
4230
4231/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
4232/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
4233/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
4234/// can ever produce, since every `tx_type` this decoder's rect sets can read
4235/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
4236/// rather than guess-decode if a non-2D class ever shows up here, since
4237/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
4238/// form for those.
4239fn read_coeffs_rect(
4240 dec: &mut SymbolDecoder,
4241 coding: &mut TxbTables,
4242 scan: &[u16],
4243 w: usize,
4244 h: usize,
4245 skip_ctx: usize,
4246 sign_ctx: usize,
4247 default_tx_type: TxType,
4248) -> Result<(Vec<i32>, TxType)> {
4249 let rect_trace = std::env::var_os("EC_TRACE_COEFF").is_some();
4250 let mut grid = vec![0i32; w * h];
4251 let entry_rng = dec.debug_state().0;
4252 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
4253 if rect_trace {
4254 eprintln!(
4255 "EC_COEFF_STEP tag=all_zero plane=0 ctx={skip_ctx} entry={entry_rng} all_zero={} rng={}",
4256 all_zero as i32,
4257 dec.debug_state().0
4258 );
4259 }
4260 if all_zero {
4261 return Ok((grid, TxType::DctDct));
4262 }
4263 RECT_COEFF_TU_HITS.with(|c| c.set(c.get() + 1));
4264 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
4265 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
4266 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
4267 // context offsets -- both of which now have rect forms
4268 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
4269 // The rect sets that carry no symbol at all still pass `None` here.
4270 let mut tx_type = default_tx_type;
4271 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
4272 let len = tx_type_cdf.len();
4273 let t = dec.symbol(tx_type_cdf);
4274 tx_type = match len {
4275 17 => TxType::from_symbol_all16(t),
4276 13 => TxType::from_symbol_set2_12(t),
4277 8 => TxType::from_symbol_set1(t),
4278 _ => TxType::from_symbol(t),
4279 }
4280 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
4281 if rect_trace {
4282 eprintln!("EC_COEFF_STEP tag=tx_type plane=0 rng={}", dec.debug_state().0);
4283 }
4284 }
4285 let class = TxClass::of(tx_type);
4286 if class != TxClass::TwoD {
4287 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
4288 }
4289 let eob = read_eob(dec, coding, class);
4290 if rect_trace {
4291 eprintln!("EC_COEFF_STEP tag=eob eob={eob} rng={}", dec.debug_state().0);
4292 }
4293 let class_scan;
4294 let scan: &[u16] = if class == TxClass::TwoD {
4295 scan
4296 } else {
4297 class_scan = class_scan_table_wh(w, h, class);
4298 &class_scan
4299 };
4300 let mut levels = vec![0i32; w * h];
4301 for scan_idx in (0..eob).rev() {
4302 let pos = scan[scan_idx] as usize;
4303 let (row, col) = (pos / w, pos % w);
4304 // libaom's column-major `coeff_idx`, for ladder comparison.
4305 let apos = col * h + row;
4306 let level = if scan_idx == eob - 1 {
4307 let ctx = eob_coeff_ctx(scan_idx, w * h);
4308 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
4309 if rect_trace {
4310 eprintln!(
4311 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
4312 dec.debug_state().0
4313 );
4314 }
4315 v
4316 } else {
4317 let ctx = base_ctx_rect(&levels, w, h, row, col, class);
4318 let v = dec.symbol(&mut coding.base[ctx]) as i32;
4319 if rect_trace {
4320 eprintln!(
4321 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
4322 dec.debug_state().0
4323 );
4324 }
4325 v
4326 };
4327 let level = if level > NUM_BASE_LEVELS {
4328 let ctx = br_ctx_rect(&levels, w, h, row, col, class);
4329 let mut level = level;
4330 let mut sent = 0;
4331 loop {
4332 let k = dec.symbol(&mut coding.br[ctx]) as i32;
4333 if rect_trace {
4334 eprintln!(
4335 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
4336 dec.debug_state().0
4337 );
4338 }
4339 level += k;
4340 sent += BR_STEP;
4341 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
4342 break;
4343 }
4344 }
4345 level
4346 } else {
4347 level
4348 };
4349 levels[pos] = level;
4350 if rect_trace {
4351 let (rng, _) = dec.debug_state();
4352 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}");
4353 }
4354 }
4355 if rect_trace {
4356 let (rng, _) = dec.debug_state();
4357 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
4358 }
4359 for &pos in &scan[..eob] {
4360 let level = levels[pos as usize];
4361 if level == 0 {
4362 continue;
4363 }
4364 let negative = if pos == 0 {
4365 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
4366 } else {
4367 dec.literal(1) == 1
4368 };
4369 if rect_trace {
4370 let (rng, _) = dec.debug_state();
4371 eprintln!("EC_COEFF_STEP tag=sign_rect pos={pos} sign={} dcctx={sign_ctx} rng={rng}", u8::from(negative));
4372 }
4373 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
4374 let g = read_golomb(dec)?;
4375 level + g as i32
4376 } else {
4377 level
4378 };
4379 grid[pos as usize] = if negative { -level } else { level };
4380 }
4381 Ok((grid, tx_type))
4382}
4383
4384/// What one coded block leaves behind for the blocks that read it as a
4385/// neighbour: whether it coded anything at all, and the sign of its DC —
4386/// [`crate::tile`]'s own private `Neighbour`.
4387#[derive(Clone, Copy, Default)]
4388struct Neighbour {
4389 /// The transform unit's cumulative coefficient level (spec `cul_level`,
4390 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
4391 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
4392 /// boolean (`level != 0`) is enough for every context this decoder read
4393 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
4394 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
4395 /// needs the actual magnitude tier of its above/left neighbours, not
4396 /// just whether they coded anything.
4397 level: u8,
4398 dc: Option<bool>,
4399}
4400
4401fn neighbour_state(grid: &[i32]) -> Neighbour {
4402 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
4403 Neighbour {
4404 level: cul.min(7) as u8,
4405 dc: (grid[0] != 0).then_some(grid[0] < 0),
4406 }
4407}
4408
4409/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
4410/// transform unit smaller than the block it sits in): `top`/`left` are the
4411/// above/left neighbours' magnitude tiers, each already clamped to 4.
4412const SKIP_CONTEXTS: [[usize; 5]; 5] = [
4413 [1, 2, 2, 2, 3],
4414 [2, 4, 4, 4, 5],
4415 [2, 4, 4, 4, 5],
4416 [2, 4, 4, 4, 5],
4417 [3, 5, 5, 5, 6],
4418];
4419
4420/// The neighbour state a block's contexts are read from — a duplicate of
4421/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
4422/// territory this round), kept at the same two granularities the real writer
4423/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
4424/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
4425/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
4426/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
4427/// chroma transform straddling the true, odd-sized frame edge see its
4428/// neighbour's state clamped at its own subsampled edge rather than luma's.
4429struct Neighbours {
4430 above: Vec<[Neighbour; 3]>,
4431 left: Vec<[Neighbour; 3]>,
4432 above_mode: Vec<usize>,
4433 left_mode: Vec<usize>,
4434 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
4435 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
4436 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
4437 /// luma one -- the same block can (and often does) code a different
4438 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
4439 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
4440 /// within-block neighbour finer than this grid) is luma-only -- a known,
4441 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
4442 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
4443 above_uv_mode: Vec<usize>,
4444 left_uv_mode: Vec<usize>,
4445 above_side: Vec<usize>,
4446 left_side: Vec<usize>,
4447 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
4448 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
4449 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
4450 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
4451 /// array cannot tell the second leaf's partition symbol that the first
4452 /// one was coded at 8x8.
4453 above_side_mi: Vec<usize>,
4454 left_side_mi: Vec<usize>,
4455 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
4456 /// / row, with the mi position it was written at
4457 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
4458 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
4459 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
4460 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
4461 /// leaf whose neighbour is another split group needs that group's leaf 3
4462 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
4463 /// and read only by [`decode_leaf_split4`]; the position guard makes it
4464 /// fall back to the coarse slot whenever the real neighbour was a block
4465 /// of 8x8 or larger (whose one mode is correct for every row it spans).
4466 sub8_mode_col: Vec<(usize, usize)>,
4467 sub8_mode_row: Vec<(usize, usize)>,
4468 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
4469 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
4470 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
4471 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
4472 /// the leaf above writes the same row slot the block to the left owns.
4473 uv_mode_col: Vec<(usize, usize)>,
4474 uv_mode_row: Vec<(usize, usize)>,
4475 /// Whether the block above/left of this column/row was coded `skip` --
4476 /// an inter frame's own `skip` context (spec `SkipContext`), which the
4477 /// key-frame writer never tracks (its skip context is always zero); a
4478 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
4479 /// `left_skip`.
4480 above_skip: Vec<bool>,
4481 left_skip: Vec<bool>,
4482 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
4483 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
4484 /// pixels last written over each unit by `set_txfm_ctxs`/
4485 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
4486 /// symbol reads its context from (lane-txselect, spec 5.11.17).
4487 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
4488 /// array is exactly libaom's per-superblock-row reset, since each mi row
4489 /// is only ever visited inside one superblock row.
4490 above_txfm: Vec<u8>,
4491 left_txfm: Vec<u8>,
4492 /// Whether the block above/left of this column/row coded `skip_mode`
4493 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
4494 /// lane-av1comp round 14.
4495 above_skip_mode: Vec<bool>,
4496 left_skip_mode: Vec<bool>,
4497 /// Whether the block above/left was coded inter -- the `is_inter`
4498 /// context (spec `av1_get_intra_inter_context`), a duplicate of
4499 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
4500 above_inter: Vec<bool>,
4501 left_inter: Vec<bool>,
4502 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
4503 /// alphabet) the block above/left of this column/row coded, or `-1` for
4504 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
4505 /// functions (`mvstack::ref_ctx` family) need the real reference, not
4506 /// just "was it inter" (lane-av1refs: every inter block used to be
4507 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
4508 /// enough).
4509 above_ref: Vec<i8>,
4510 left_ref: Vec<i8>,
4511 /// The block above/left's *second* reference frame when it was coded
4512 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
4513 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
4514 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
4515 /// `i8`, once a compound `read_ref_frames` lands. Always `None` today
4516 /// (no decode path here ever produces a compound block yet).
4517 above_ref1: Vec<Option<i8>>,
4518 left_ref1: Vec<Option<i8>>,
4519 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
4520 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
4521 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
4522 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
4523 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
4524 above_comp_group_idx: Vec<u8>,
4525 left_comp_group_idx: Vec<u8>,
4526 above_compound_idx: Vec<u8>,
4527 left_compound_idx: Vec<u8>,
4528 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
4529 /// `3` = "no info": an intra neighbour or the frame's own border) of the
4530 /// block above/left of this column/row -- spec
4531 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
4532 above_filter: Vec<[u8; 2]>,
4533 left_filter: Vec<[u8; 2]>,
4534 mi_cols: usize,
4535 mi_rows: usize,
4536 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
4537 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
4538 /// 7.15) never filters an 8x8 luma block whose covering coded block read
4539 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
4540 /// grain [`Self::record_mi`] already writes at), read back at 8x8
4541 /// granularity by [`apply_cdef`] since `skip` is constant across every
4542 /// mi cell one coded block covers.
4543 skip_grid: Vec<bool>,
4544 /// lane-cdefstrip r1 instrument: whether any coded block actually WROTE
4545 /// [`Self::skip_grid`] at this mi cell during this frame. A fresh
4546 /// `Neighbours` seeds `skip_grid` all-`false` ("not skip"), so a decode
4547 /// arm that forgets [`Self::fill_skip_grid_rect`] silently makes
4548 /// [`apply_cdef`] filter an 8x8 unit libaom's `is_8x8_block_skip`
4549 /// (`cdef.c:29-38`) excludes -- exactly the lane-cdef defect, and
4550 /// unobservable from the pixels alone. Counted by
4551 /// [`cdef_unwritten_skip_units`].
4552 skip_written: Vec<bool>,
4553 /// Per-4x4-mi origin `(mi_row, mi_col)` of the coded (prediction) block
4554 /// covering that cell -- spec 7.14.2's `isBlockEdge`/libaom `pu_edge`,
4555 /// which re-enables the loop filter at a prediction boundary between two
4556 /// skipped inter blocks (lane-mergefix r4). Written by
4557 /// [`Self::fill_skip_grid_rect`], whose `at_mi` IS that origin.
4558 blk_org_grid: Vec<[u16; 2]>,
4559 skip_grid_cols_mi: usize,
4560 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
4561 /// never splits a coded block's transform below its own size (round 2:
4562 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
4563 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
4564 /// edge-length lookup (`apply_deblock`).
4565 tx_grid: Vec<u8>,
4566 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
4567 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
4568 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
4569 tx_h_grid: Vec<u8>,
4570 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
4571 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
4572 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
4573 /// does NOT follow luma's `tx_depth` split, so deriving it as
4574 /// `tx_grid / 2` invented chroma transform edges the deblocker then
4575 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
4576 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
4577 /// every caller routes through.
4578 uv_tx_grid: Vec<u8>,
4579 uv_tx_h_grid: Vec<u8>,
4580 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
4581 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
4582 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
4583 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
4584 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
4585 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
4586 /// reference onto `LAST_FRAME`'s own delta).
4587 ref_grid: Vec<i8>,
4588 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
4589 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
4590 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
4591 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
4592 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
4593 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
4594 /// to know which mode produced the value.
4595 delta_lf_grid: Vec<[i8; 4]>,
4596 /// The block above/left's own palette-Y size (0 = not a palette block)
4597 /// and its base colours -- `av1_get_palette_mode_ctx`/
4598 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
4599 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
4600 above_palette_size: Vec<usize>,
4601 left_palette_size: Vec<usize>,
4602 above_palette_colors: Vec<[u16; 8]>,
4603 left_palette_colors: Vec<[u16; 8]>,
4604 /// As the four fields above, for the neighbour's own chroma (U-channel
4605 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
4606 /// palette size/colours (lane-palette2 r1).
4607 above_palette_uv_size: Vec<usize>,
4608 left_palette_uv_size: Vec<usize>,
4609 above_palette_uv_colors: Vec<[u16; 8]>,
4610 left_palette_uv_colors: Vec<[u16; 8]>,
4611 /// This tile's own top-left corner, in 4x4 mode-info units (spec
4612 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
4613 /// neighbour" check compares against this instead of literal `0`, since a
4614 /// block at the tile's own top/left edge has no usable neighbour even
4615 /// though a decoded block sits there in the picture (spec `decode_tile`'s
4616 /// per-tile `clear_above_context`/`left_available`/`up_available`).
4617 /// `0` for a single-tile frame, matching every existing caller exactly.
4618 tile_row0_mi: usize,
4619 tile_col0_mi: usize,
4620}
4621
4622impl Neighbours {
4623 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
4624 /// true (unpadded) size in 4x4 mode-info units.
4625 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
4626 // lane-sb128c r7: a 128x64 block at the bottom frame edge records its
4627 // neighbour state over the whole 64-row extent, past the frame's last
4628 // mi row (mi_rows 198, block rows 192..208). libaom's own context
4629 // buffers are superblock-aligned for exactly that reason
4630 // (`av1_alloc_context_buffers` rounds to `MAX_MIB_SIZE`), so pad the
4631 // side arrays to a superblock multiple and leave those cells unread --
4632 // every availability check uses the true `mi_rows`/`mi_cols` below.
4633 let sb_sub = (sb_mi_cur() as usize) / (SUB / MI);
4634 let (cols, rows) = (
4635 cols.next_multiple_of(sb_sub),
4636 rows.next_multiple_of(sb_sub),
4637 );
4638 Self {
4639 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
4640 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
4641 above_mode: vec![DC_PRED; cols],
4642 left_mode: vec![DC_PRED; rows],
4643 above_uv_mode: vec![DC_PRED; cols],
4644 left_uv_mode: vec![DC_PRED; rows],
4645 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
4646 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
4647 above_side_mi: vec![NO_NEIGHBOUR_SIDE; cols * (SUB / MI)],
4648 left_side_mi: vec![NO_NEIGHBOUR_SIDE; rows * (SUB / MI)],
4649 sub8_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],
4650 sub8_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)],
4651 uv_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],
4652 uv_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)],
4653 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
4654 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
4655 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
4656 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
4657 // 16x16 block beside it, which a SUB-grid slot cannot name
4658 // (class context-read-from-one-cell).
4659 above_skip: vec![false; cols * (SUB / MI)],
4660 left_skip: vec![false; rows * (SUB / MI)],
4661 above_skip_mode: vec![false; cols * (SUB / MI)],
4662 left_skip_mode: vec![false; rows * (SUB / MI)],
4663 above_inter: vec![false; cols * (SUB / MI)],
4664 left_inter: vec![false; rows * (SUB / MI)],
4665 above_ref: vec![-1; cols * (SUB / MI)],
4666 left_ref: vec![-1; rows * (SUB / MI)],
4667 above_ref1: vec![None; cols * (SUB / MI)],
4668 left_ref1: vec![None; rows * (SUB / MI)],
4669 above_comp_group_idx: vec![0; cols * (SUB / MI)],
4670 left_comp_group_idx: vec![0; rows * (SUB / MI)],
4671 above_compound_idx: vec![0; cols * (SUB / MI)],
4672 left_compound_idx: vec![0; rows * (SUB / MI)],
4673 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
4674 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
4675 mi_cols,
4676 mi_rows,
4677 skip_grid: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
4678 skip_written: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
4679 blk_org_grid: vec![[0u16; 2]; cols * (SUB / MI) * rows * (SUB / MI)],
4680 skip_grid_cols_mi: cols * (SUB / MI),
4681 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
4682 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
4683 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
4684 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
4685 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
4686 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
4687 above_palette_size: vec![0; cols * (SUB / MI)],
4688 left_palette_size: vec![0; rows * (SUB / MI)],
4689 above_palette_colors: vec![[0u16; 8]; cols * (SUB / MI)],
4690 left_palette_colors: vec![[0u16; 8]; rows * (SUB / MI)],
4691 above_palette_uv_size: vec![0; cols * (SUB / MI)],
4692 left_palette_uv_size: vec![0; rows * (SUB / MI)],
4693 above_palette_uv_colors: vec![[0u16; 8]; cols * (SUB / MI)],
4694 left_palette_uv_colors: vec![[0u16; 8]; rows * (SUB / MI)],
4695 tile_row0_mi: 0,
4696 tile_col0_mi: 0,
4697 }
4698 }
4699
4700 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
4701 /// tile's own column span (`col1_mi` exclusive), plus recording
4702 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
4703 /// availability check below. Left context resets every superblock row
4704 /// regardless of tile ([`Self::start_row`], already called once per SB
4705 /// row by every caller) so it needs no tile-specific reset here.
4706 fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize) {
4707 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
4708 // are tile-relative, same as every other neighbour lookup here.
4709 SEG_TILE_ORIGIN.with(|c| c.set((row0_mi, col0_mi)));
4710 self.tile_row0_mi = row0_mi;
4711 self.tile_col0_mi = col0_mi;
4712 let end = col1_mi.min(self.above.len());
4713 for i in col0_mi.min(end)..end {
4714 self.above[i] = Default::default();
4715 self.above_side_mi[i] = NO_NEIGHBOUR_SIDE;
4716 }
4717 let (sc0, sc1) = (
4718 col0_mi / (SUB / MI),
4719 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
4720 );
4721 for i in sc0.min(sc1)..sc1 {
4722 self.above_mode[i] = DC_PRED;
4723 self.above_side[i] = NO_NEIGHBOUR_SIDE;
4724 }
4725 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
4726 // the tile's own mi column span directly.
4727 let mend = col1_mi.min(self.above_skip.len());
4728 for i in col0_mi.min(mend)..mend {
4729 self.above_skip[i] = false;
4730 self.above_skip_mode[i] = false;
4731 self.above_inter[i] = false;
4732 self.above_ref[i] = -1;
4733 self.above_ref1[i] = None;
4734 self.above_comp_group_idx[i] = 0;
4735 self.above_compound_idx[i] = 0;
4736 self.above_filter[i] = [3u8; 2];
4737 }
4738 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
4739 // stale `(row, mode)` from the tile to the LEFT names an mi row this
4740 // tile's first block would read as its own above neighbour.
4741 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
4742 for i in col0_mi.min(mcol_end)..mcol_end {
4743 self.sub8_mode_col[i] = (usize::MAX, 0);
4744 self.uv_mode_col[i] = (usize::MAX, 0);
4745 }
4746 // lane-mergefix r2: `av1_zero_above_context` also memsets the txfm row
4747 // over the tile's own column span (to `tx_size_wide[TX_SIZES_LARGEST]`,
4748 // not zero) -- without it a second tile column reads the first one's
4749 // resolved transform sizes as its own above context.
4750 let tend = col1_mi.min(self.above_txfm.len());
4751 for i in col0_mi.min(tend)..tend {
4752 self.above_txfm[i] = TXFM_CTX_INIT;
4753 }
4754 }
4755
4756 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
4757 /// for a non-palette block, clearing any stale neighbour state) into every
4758 /// [`SUB`]-grid cell it covers on both the above and left edges --
4759 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
4760 /// call sites are all square blocks).
4761 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
4762 self.record_palette_y_rect((at.0 * (SUB / MI), at.1 * (SUB / MI)), side, side, size, colors);
4763 }
4764
4765 /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
4766 /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
4767 /// [`Self::record`]): a true rect strip's above/left neighbour spans
4768 /// differ.
4769 fn record_palette_y_rect(
4770 &mut self,
4771 mi: (usize, usize),
4772 w: usize,
4773 h: usize,
4774 size: usize,
4775 colors: [u16; 8],
4776 ) {
4777 let (r, c) = mi;
4778 // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size`
4779 // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi
4780 // cell immediately left of the block, not its 16px [`SUB`] cell. The
4781 // old SUB grid let a 16x8 strip pair share one slot, so the second
4782 // strip of mi(0,8) read the FIRST strip's palette size and the colour
4783 // cache came out one entry short (class [[context-read-from-one-cell]]).
4784 for cell in 0..(w / MI).max(1) {
4785 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
4786 *e = size;
4787 self.above_palette_colors[c + cell] = colors;
4788 }
4789 }
4790 for cell in 0..(h / MI).max(1) {
4791 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
4792 *e = size;
4793 self.left_palette_colors[r + cell] = colors;
4794 }
4795 }
4796 }
4797
4798 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
4799 /// neighbours that are themselves a palette-Y block, plus
4800 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
4801 /// cache (pred_common.c:73).
4802 ///
4803 /// The SB-top-row exclusion of the above neighbour (`row % 64` in
4804 /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
4805 /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
4806 /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
4807 /// the ctx too made every superblock in the frame's second SB row read
4808 /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
4809 /// palette block decoded as "no palette" and the tile desynced from
4810 /// there (class [[cdf-row-held-constant]]).
4811 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
4812 self.palette_ctx_and_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
4813 }
4814
4815 /// [`Self::palette_ctx_and_cache`] with the block's REAL mi row, which a
4816 /// 1:4 strip does not share with its [`SUB`] cell: `av1_get_palette_cache`
4817 /// drops the above neighbour on a 64-px superblock boundary
4818 /// (pred_common.c:76, `row % (1 << MIN_SB_SIZE_LOG2)` with `row` the
4819 /// block's own PIXEL row), and strip 1 of a HORZ_4 sits 8 px into the
4820 /// cell -- reading `at.0 % 4` there excludes strip 0 from the cache of
4821 /// every strip in an SB's top cell row, which libaom does not do.
4822 fn palette_ctx_and_cache_mi(&self, mi: (usize, usize)) -> (usize, Vec<u16>) {
4823 let (r, c) = mi;
4824 let above_ok = r % 16 != 0;
4825 // `xd->above_mbmi` exists for every row but the tile's own first.
4826 let above_is_palette = r > self.tile_row0_mi && self.above_palette_size[c] > 0;
4827 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
4828 (self.above_palette_size[c], self.above_palette_colors[c])
4829 } else {
4830 (0, [0u16; 8])
4831 };
4832 // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which
4833 // is NULL whenever the block sits at its TILE's own left column
4834 // (`left_available`), not the frame's -- without this guard a second
4835 // tile column reads the previous tile's palette colours into its cache
4836 // and its `palette_y_mode` ctx.
4837 let left_ok = c > self.tile_col0_mi;
4838 let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 {
4839 (self.left_palette_size[r], self.left_palette_colors[r])
4840 } else {
4841 (0, [0u16; 8])
4842 };
4843 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
4844 let mut cache = Vec::with_capacity(16);
4845 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
4846 if cache.last() != Some(&v) {
4847 cache.push(v);
4848 }
4849 };
4850 let (mut ai, mut li) = (0usize, 0usize);
4851 while ai < above_n && li < left_n {
4852 let (va, vl) = (above_colors[ai], left_colors[li]);
4853 if vl < va {
4854 push_dedup(&mut cache, vl);
4855 li += 1;
4856 } else {
4857 push_dedup(&mut cache, va);
4858 ai += 1;
4859 if vl == va {
4860 li += 1;
4861 }
4862 }
4863 }
4864 while ai < above_n {
4865 push_dedup(&mut cache, above_colors[ai]);
4866 ai += 1;
4867 }
4868 while li < left_n {
4869 push_dedup(&mut cache, left_colors[li]);
4870 li += 1;
4871 }
4872 (ctx, cache)
4873 }
4874
4875 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
4876 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
4877 /// same way (lane-palette2 r1).
4878 fn record_palette_uv(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
4879 self.record_palette_uv_rect(
4880 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
4881 side,
4882 side,
4883 size,
4884 colors,
4885 );
4886 }
4887
4888 /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
4889 /// extents, in LUMA pixels (lane-palette2 r4, same convention as
4890 /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
4891 /// luma resolution regardless of which plane the recorded state is for).
4892 fn record_palette_uv_rect(
4893 &mut self,
4894 mi: (usize, usize),
4895 w: usize,
4896 h: usize,
4897 size: usize,
4898 colors: [u16; 8],
4899 ) {
4900 let (r, c) = mi;
4901 // mi granularity, see [`Self::record_palette_y_rect`].
4902 for cell in 0..(w / MI).max(1) {
4903 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
4904 *e = size;
4905 self.above_palette_uv_colors[c + cell] = colors;
4906 }
4907 }
4908 for cell in 0..(h / MI).max(1) {
4909 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
4910 *e = size;
4911 self.left_palette_uv_colors[r + cell] = colors;
4912 }
4913 }
4914 }
4915
4916 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
4917 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
4918 /// no neighbour lookup at all (it is this block's own just-decided Y
4919 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
4920 /// so only the cache is wanted here.
4921 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
4922 self.palette_uv_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
4923 }
4924
4925 /// [`Self::palette_uv_cache`] with the block's real mi row -- see
4926 /// [`Self::palette_ctx_and_cache_mi`].
4927 fn palette_uv_cache_mi(&self, mi: (usize, usize)) -> Vec<u16> {
4928 let (r, c) = mi;
4929 let above_ok = r % 16 != 0;
4930 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
4931 (self.above_palette_uv_size[c], self.above_palette_uv_colors[c])
4932 } else {
4933 (0, [0u16; 8])
4934 };
4935 // Same tile-relative left availability as the luma cache above.
4936 let left_ok = c > self.tile_col0_mi;
4937 let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 {
4938 (self.left_palette_uv_size[r], self.left_palette_uv_colors[r])
4939 } else {
4940 (0, [0u16; 8])
4941 };
4942 let mut cache = Vec::with_capacity(16);
4943 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
4944 if cache.last() != Some(&v) {
4945 cache.push(v);
4946 }
4947 };
4948 let (mut ai, mut li) = (0usize, 0usize);
4949 while ai < above_n && li < left_n {
4950 let (va, vl) = (above_colors[ai], left_colors[li]);
4951 if vl < va {
4952 push_dedup(&mut cache, vl);
4953 li += 1;
4954 } else {
4955 push_dedup(&mut cache, va);
4956 ai += 1;
4957 if vl == va {
4958 li += 1;
4959 }
4960 }
4961 }
4962 while ai < above_n {
4963 push_dedup(&mut cache, above_colors[ai]);
4964 ai += 1;
4965 }
4966 while li < left_n {
4967 push_dedup(&mut cache, left_colors[li]);
4968 li += 1;
4969 }
4970 cache
4971 }
4972
4973 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
4974 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
4975 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
4976 /// units as [`Self::fill_skip_grid`].
4977 fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8) {
4978 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame);
4979 }
4980
4981 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
4982 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
4983 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
4984 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
4985 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
4986 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
4987 /// libaom `set_one_param_for_line_luma`/`_chroma`: an edge that is a
4988 /// transform-unit edge but NOT a prediction-unit edge is not filtered when
4989 /// `curr_skipped = mbmi->skip_txfm && is_inter_block(mbmi)`. Widening this
4990 /// block's published transform extent to its own size is exactly that
4991 /// suppression for the deblocker's `x0 % tx != 0` test -- the only shape
4992 /// that needs it is the 128 root, whose chroma extent (64) is the one
4993 /// [`Self::fill_lf_grid_rect`]'s TX_32X32 cap narrows. An INTRA block is
4994 /// never suppressed (libaom's `is_inter_block` term), so this is called
4995 /// only from the skipped-inter branch.
4996 fn suppress_internal_lf_edges(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize) {
4997 let (mi_r, mi_c) = at_mi;
4998 let (uv_w, uv_h) = ((w_mi * MI / 2).max(4) as u8, (h_mi * MI / 2).max(4) as u8);
4999 for rr in 0..h_mi {
5000 for cc in 0..w_mi {
5001 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
5002 if let Some(cell) = self.uv_tx_grid.get_mut(idx) {
5003 *cell = uv_w;
5004 }
5005 if let Some(cell) = self.uv_tx_h_grid.get_mut(idx) {
5006 *cell = uv_h;
5007 }
5008 }
5009 }
5010 }
5011
5012 fn fill_lf_grid_rect(
5013 &mut self,
5014 at_mi: (usize, usize),
5015 w_mi: usize,
5016 h_mi: usize,
5017 tx_px: u8,
5018 tx_h_px: u8,
5019 ref_frame: i8,
5020 ) {
5021 let (mi_r, mi_c) = at_mi;
5022 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
5023 // half its luma one (min 4 px, the smallest transform), capped at
5024 // TX_32X32 -- independent of this block's luma `tx_depth`.
5025 let uv_tx_w = ((w_mi * MI / 2).max(4).min(32)) as u8;
5026 let uv_tx_h = ((h_mi * MI / 2).max(4).min(32)) as u8;
5027 if std::env::var_os("EC_TXGRID_TRACE").is_some() {
5028 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}");
5029 }
5030 let cur = CURRENT_DELTA_LF.with(|c| c.get());
5031 let snapshot: [i8; 4] = if DELTA_LF_MULTI.with(|c| c.get()) {
5032 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
5033 } else {
5034 [cur[0].clamp(-63, 63) as i8; 4]
5035 };
5036 for rr in 0..h_mi {
5037 for cc in 0..w_mi {
5038 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
5039 if let Some(cell) = self.tx_grid.get_mut(idx) {
5040 *cell = tx_px;
5041 }
5042 if let Some(cell) = self.tx_h_grid.get_mut(idx) {
5043 *cell = tx_h_px;
5044 }
5045 if let Some(cell) = self.uv_tx_grid.get_mut(idx) {
5046 *cell = uv_tx_w;
5047 }
5048 if let Some(cell) = self.uv_tx_h_grid.get_mut(idx) {
5049 *cell = uv_tx_h;
5050 }
5051 if let Some(cell) = self.ref_grid.get_mut(idx) {
5052 *cell = ref_frame;
5053 }
5054 if let Some(cell) = self.delta_lf_grid.get_mut(idx) {
5055 *cell = snapshot;
5056 }
5057 }
5058 }
5059 }
5060
5061 /// One var-tx / split-tx LEAF's own LUMA transform dims over its mi span.
5062 /// libaom `get_transform_size` (av1_loopfilter.c:207) applies the split
5063 /// override only `if ((plane == AOM_PLANE_Y) && ...)` -- chroma keeps
5064 /// `av1_get_max_uv_txsize(mbmi->bsize)`, the whole BLOCK's uv transform.
5065 /// Routing a leaf through [`Self::fill_lf_grid_rect`] recomputed the uv
5066 /// dims from the LEAF span and so invented chroma transform edges the
5067 /// deblocker then filtered (lane-golomb r6). `ref_grid`/`delta_lf_grid`
5068 /// are already correct from the block's own fill over the same span.
5069 fn fill_lf_grid_leaf_luma(
5070 &mut self,
5071 at_mi: (usize, usize),
5072 w_mi: usize,
5073 h_mi: usize,
5074 tx_px: u8,
5075 tx_h_px: u8,
5076 ) {
5077 let (mi_r, mi_c) = at_mi;
5078 if std::env::var_os("EC_TXGRID_TRACE").is_some() {
5079 eprintln!("EC_LFLEAF mi_row={mi_r} mi_col={mi_c} w_mi={w_mi} h_mi={h_mi} tx_px={tx_px} tx_h_px={tx_h_px}");
5080 }
5081 for rr in 0..h_mi {
5082 for cc in 0..w_mi {
5083 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
5084 if let Some(cell) = self.tx_grid.get_mut(idx) {
5085 *cell = tx_px;
5086 }
5087 if let Some(cell) = self.tx_h_grid.get_mut(idx) {
5088 *cell = tx_h_px;
5089 }
5090 }
5091 }
5092 }
5093
5094 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
5095 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
5096 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
5097 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
5098 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
5099 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
5100 }
5101
5102 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
5103 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
5104 let (mi_r, mi_c) = at_mi;
5105 if skip && w_mi != h_mi {
5106 RECT_SKIP_BAND_HITS.with(|c| c.set(c.get() + 1));
5107 }
5108 for rr in 0..h_mi {
5109 for cc in 0..w_mi {
5110 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
5111 if let Some(cell) = self.skip_grid.get_mut(idx) {
5112 *cell = skip;
5113 }
5114 if let Some(cell) = self.skip_written.get_mut(idx) {
5115 *cell = true;
5116 }
5117 if let Some(org) = self.blk_org_grid.get_mut(idx) {
5118 *org = [mi_r as u16, mi_c as u16];
5119 }
5120 }
5121 }
5122 }
5123
5124 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
5125 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
5126 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
5127 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
5128 /// straddle the region with a mix of skip/non-skip blocks).
5129 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
5130 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
5131 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
5132 /// filtered edge's two sides are each exactly one coded block wide.
5133 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
5134 self.skip_grid
5135 .get(mi_r * self.skip_grid_cols_mi + mi_c)
5136 .copied()
5137 .unwrap_or(false)
5138 }
5139
5140 /// The `skip_txfm` context of a block whose top-left mi cell is
5141 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
5142 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
5143 /// with an absent neighbour contributing 0. The mi grid is per tile, so
5144 /// row/column 0 is a tile edge and has no neighbour on that axis.
5145 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
5146 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
5147 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
5148 }
5149
5150 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
5151 (0..2).all(|rr| {
5152 (0..2).all(|cc| {
5153 self.skip_grid
5154 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
5155 .copied()
5156 .unwrap_or(false)
5157 })
5158 })
5159 }
5160
5161 fn start_row(&mut self) {
5162 self.left.iter_mut().for_each(|l| *l = Default::default());
5163 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
5164 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
5165 self.left_side.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
5166 self.left_side_mi.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
5167 self.left_skip.iter_mut().for_each(|s| *s = false);
5168 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
5169 self.left_inter.iter_mut().for_each(|i| *i = false);
5170 self.left_ref.iter_mut().for_each(|r| *r = -1);
5171 self.left_ref1.iter_mut().for_each(|r| *r = None);
5172 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
5173 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
5174 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
5175 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
5176 // context (a tile/SB-row boundary has no left neighbour).
5177 self.sub8_mode_row.iter_mut().for_each(|s| *s = (usize::MAX, 0));
5178 self.uv_mode_row.iter_mut().for_each(|s| *s = (usize::MAX, 0));
5179 // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands
5180 // are per-mi maps like every other one here, so they reset with the
5181 // row too -- the left guard above is what actually stops a cross-tile
5182 // read, this keeps a stale colour out of the arrays at all.
5183 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
5184 self.left_palette_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
5185 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
5186 self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
5187 // lane-mergefix r2: `av1_zero_left_context` memsets
5188 // `left_txfm_context_buffer` to `tx_size_high[TX_SIZES_LARGEST]` at
5189 // every superblock row of every tile -- the var-tx left context does
5190 // NOT carry over a tile boundary (its `txfm_partition` ctx read the
5191 // previous tile column's last block otherwise).
5192 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
5193 }
5194
5195 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
5196 /// block that reads it as a neighbour -- [`crate::tile`]'s
5197 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
5198 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
5199 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
5200 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
5201 /// the real value, not just `is_inter`).
5202 fn record_inter(
5203 &mut self,
5204 at: (usize, usize),
5205 side: usize,
5206 skip: bool,
5207 is_inter: bool,
5208 ref_frame: i8,
5209 filter: [u8; 2],
5210 skip_mode: bool,
5211 ) {
5212 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
5213 }
5214
5215 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
5216 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
5217 /// r1: a true rectangular strip's above-context span (its own width) and
5218 /// left-context span (its own height) differ, unlike every caller before
5219 /// this round (class neighbour-votes-all-its-fields).
5220 #[allow(clippy::too_many_arguments)]
5221 fn record_inter_rect(
5222 &mut self,
5223 at: (usize, usize),
5224 w_sub: usize,
5225 h_sub: usize,
5226 skip: bool,
5227 is_inter: bool,
5228 ref_frame: i8,
5229 filter: [u8; 2],
5230 skip_mode: bool,
5231 ) {
5232 let (r, c) = at;
5233 self.record_inter_rect_mi(
5234 (r * (SUB / MI), c * (SUB / MI)),
5235 w_sub / MI,
5236 h_sub / MI,
5237 skip,
5238 is_inter,
5239 ref_frame,
5240 filter,
5241 skip_mode,
5242 );
5243 }
5244
5245 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
5246 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
5247 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
5248 /// routes through the wrapper above.
5249 #[allow(clippy::too_many_arguments)]
5250 fn record_inter_rect_mi(
5251 &mut self,
5252 at_mi: (usize, usize),
5253 w_mi: usize,
5254 h_mi: usize,
5255 skip: bool,
5256 is_inter: bool,
5257 ref_frame: i8,
5258 filter: [u8; 2],
5259 skip_mode: bool,
5260 ) {
5261 let (r, c) = at_mi;
5262 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
5263 for cell in 0..w_mi {
5264 self.above_skip[c + cell] = skip;
5265 self.above_skip_mode[c + cell] = skip_mode;
5266 self.above_inter[c + cell] = is_inter;
5267 self.above_ref[c + cell] = ref_frame;
5268 // lane-av1comp: no caller of `record_inter` ever decodes a
5269 // compound block yet (see [`Self::above_ref1`]'s doc); the
5270 // parameter this becomes lands with `read_ref_frames`.
5271 self.above_ref1[c + cell] = None;
5272 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
5273 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
5274 // as `3`/`1` even though this block has no second reference.
5275 // `record_compound_ctx` overwrites this with the real bit for an
5276 // actual compound block's cells, called right after this one.
5277 self.above_comp_group_idx[c + cell] = if altref { 3 } else { 0 };
5278 self.above_compound_idx[c + cell] = u8::from(altref);
5279 self.above_filter[c + cell] = filter;
5280 }
5281 for cell in 0..h_mi {
5282 self.left_skip[r + cell] = skip;
5283 self.left_skip_mode[r + cell] = skip_mode;
5284 self.left_inter[r + cell] = is_inter;
5285 self.left_ref[r + cell] = ref_frame;
5286 self.left_ref1[r + cell] = None;
5287 self.left_comp_group_idx[r + cell] = if altref { 3 } else { 0 };
5288 self.left_compound_idx[r + cell] = u8::from(altref);
5289 self.left_filter[r + cell] = filter;
5290 }
5291 }
5292
5293 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
5294 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
5295 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
5296 /// `get_comp_index_context`) -- called right after `record_inter` for
5297 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
5298 /// stamps `above_ref1`/`left_ref1` with the block's real second
5299 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
5300 /// this is the one caller that actually knows it) -- so the next block's
5301 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
5302 /// neighbour instead of `record_inter`'s single-ref default.
5303 fn record_compound_ctx(
5304 &mut self,
5305 at: (usize, usize),
5306 side: usize,
5307 ref1: i8,
5308 comp_group_idx: u8,
5309 compound_idx: u8,
5310 ) {
5311 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
5312 }
5313
5314 /// [`Self::record_compound_ctx`] with independent above/left extents,
5315 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
5316 #[allow(clippy::too_many_arguments)]
5317 fn record_compound_ctx_rect(
5318 &mut self,
5319 at: (usize, usize),
5320 w_sub: usize,
5321 h_sub: usize,
5322 ref1: i8,
5323 comp_group_idx: u8,
5324 compound_idx: u8,
5325 ) {
5326 let (r, c) = at;
5327 self.record_compound_ctx_rect_mi(
5328 (r * (SUB / MI), c * (SUB / MI)),
5329 w_sub / MI,
5330 h_sub / MI,
5331 ref1,
5332 comp_group_idx,
5333 compound_idx,
5334 );
5335 }
5336
5337 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
5338 /// [`Self::record_inter_rect_mi`]).
5339 fn record_compound_ctx_rect_mi(
5340 &mut self,
5341 at_mi: (usize, usize),
5342 w_mi: usize,
5343 h_mi: usize,
5344 ref1: i8,
5345 comp_group_idx: u8,
5346 compound_idx: u8,
5347 ) {
5348 let (r, c) = at_mi;
5349 for cell in 0..w_mi {
5350 self.above_ref1[c + cell] = Some(ref1);
5351 self.above_comp_group_idx[c + cell] = comp_group_idx;
5352 self.above_compound_idx[c + cell] = compound_idx;
5353 }
5354 for cell in 0..h_mi {
5355 self.left_ref1[r + cell] = Some(ref1);
5356 self.left_comp_group_idx[r + cell] = comp_group_idx;
5357 self.left_compound_idx[r + cell] = compound_idx;
5358 }
5359 }
5360
5361 /// The context of a block's partition symbol: delegates to the mi-precise
5362 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
5363 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
5364 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
5365 /// only touches the finer mi arrays -- leaves them stale for the *next*
5366 /// sibling's own partition symbol.
5367 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
5368 let (r, c) = at;
5369 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
5370 }
5371
5372 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
5373 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
5374 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
5375 /// than the enclosing 16x16 slot's stale, shared state.
5376 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
5377 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side)
5378 + usize::from(self.above_side_mi[mi_c] * 2 <= side)
5379 }
5380
5381 /// The gathered coded/DC-sign state of the blocks above and to the left
5382 /// of a block `side` samples across, per plane.
5383 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
5384 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
5385 }
5386
5387 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
5388 /// units, for the same reason [`Self::record_mi`] does.
5389 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
5390 let side_mi = side / MI;
5391 std::array::from_fn(|plane| {
5392 let mut above_coded = false;
5393 let mut left_coded = false;
5394 let mut vote = 0;
5395 for cell in 0..side_mi {
5396 let above = &self.above[mi_c + cell][plane];
5397 let left = &self.left[mi_r + cell][plane];
5398 above_coded |= above.level != 0;
5399 left_coded |= left.level != 0;
5400 vote += dc_vote(above.dc) + dc_vote(left.dc);
5401 }
5402 (above_coded, left_coded, vote)
5403 })
5404 }
5405
5406 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
5407 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
5408 /// extent pattern for a true rectangular strip's own coefficient context.
5409 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
5410 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
5411 }
5412
5413 /// [`Self::around_rect`] taking the block's position directly in 4x4
5414 /// mode-info units, mirroring [`Self::around_mi`].
5415 fn around_mi_rect(&self, (mi_r, mi_c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
5416 let (w_mi, h_mi) = (w / MI, h / MI);
5417 std::array::from_fn(|plane| {
5418 let mut above_coded = false;
5419 let mut left_coded = false;
5420 let mut vote = 0;
5421 for cell in 0..w_mi {
5422 let above = &self.above[mi_c + cell][plane];
5423 above_coded |= above.level != 0;
5424 vote += dc_vote(above.dc);
5425 }
5426 for cell in 0..h_mi {
5427 let left = &self.left[mi_r + cell][plane];
5428 left_coded |= left.level != 0;
5429 vote += dc_vote(left.dc);
5430 }
5431 if std::env::var_os("EC_DCDUMP").is_some() {
5432 let ab: Vec<String> = (0..w_mi)
5433 .map(|k| format!("{:?}/{}", self.above[mi_c + k][plane].dc, self.above[mi_c + k][plane].level))
5434 .collect();
5435 let lf: Vec<String> = (0..h_mi)
5436 .map(|k| format!("{:?}/{}", self.left[mi_r + k][plane].dc, self.left[mi_r + k][plane].level))
5437 .collect();
5438 eprintln!("EC_DCDUMP mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]", ab.join(","), lf.join(","));
5439 }
5440 (above_coded, left_coded, vote)
5441 })
5442 }
5443
5444 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
5445 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
5446 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
5447 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
5448 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
5449 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
5450 /// is always 0, spec's `plane_bsize == tx_size` branch).
5451 fn luma_skip_ctx(&self, at_mi: (usize, usize), side_mi: usize) -> usize {
5452 self.luma_skip_ctx_rect(at_mi, side_mi, side_mi)
5453 }
5454
5455 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi
5456 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above
5457 /// context over `tx_size_wide` and the left one over `tx_size_high`.
5458 fn luma_skip_ctx_rect(
5459 &self,
5460 (mi_r, mi_c): (usize, usize),
5461 w_mi: usize,
5462 h_mi: usize,
5463 ) -> usize {
5464 let side_mi = w_mi;
5465 let mut top = 0u8;
5466 let mut left = 0u8;
5467 for cell in 0..w_mi {
5468 top |= self.above[mi_c + cell][0].level;
5469 }
5470 for cell in 0..h_mi {
5471 left |= self.left[mi_r + cell][0].level;
5472 }
5473 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
5474 if std::env::var_os("EC_AV1_TRACE").is_some() {
5475 eprintln!(
5476 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx} band={:?}",
5477 self.left.iter().map(|e| e[0].level).collect::<Vec<_>>()
5478 );
5479 }
5480 ctx
5481 }
5482
5483 /// Writes one coded block into every cell it covers, on both grids: the
5484 /// mode/side arrays up to `side`'s own width, and the coefficient-context
5485 /// arrays up to the true frame edge — the units past it are left at their
5486 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
5487 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
5488 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
5489 /// not from this block's own side).
5490 fn record(
5491 &mut self,
5492 at: (usize, usize),
5493 side: usize,
5494 mode: usize,
5495 uv_mode: usize,
5496 grids: &[Vec<i32>; 3],
5497 ) {
5498 self.record_rect(at, side, side, mode, uv_mode, grids);
5499 }
5500
5501 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
5502 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
5503 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
5504 /// spec's per-edge partition-context rule, so a true rectangular block
5505 /// naturally wants two different values here rather than one.
5506 /// Writes this block's luma `mode` into the mi-granular
5507 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
5508 /// position a *later* neighbour would read it from: the block's LAST mi
5509 /// row for every column it spans (what the block below reads via
5510 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
5511 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
5512 /// read these back, and only when the recorded position is exactly their
5513 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
5514 fn record_mode_mi(
5515 &mut self,
5516 mi_r: usize,
5517 mi_c: usize,
5518 mi_w: usize,
5519 mi_h: usize,
5520 mode: usize,
5521 ) {
5522 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
5523 for cell in 0..mi_w {
5524 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
5525 *slot = (last_r, mode);
5526 }
5527 }
5528 for cell in 0..mi_h {
5529 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
5530 *slot = (last_c, mode);
5531 }
5532 }
5533 }
5534
5535 /// The mi-exact above/left neighbour luma mode for a block whose top-left
5536 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
5537 /// mi position (then the coarse [`SUB`]-grid slot is right by
5538 /// construction). See [`Self::record_mode_mi`].
5539 fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
5540 match self.sub8_mode_col.get(mi_c) {
5541 Some(&(row, m)) if mi_r > self.tile_row0_mi && row == mi_r - 1 => Some(m),
5542 _ => None,
5543 }
5544 }
5545
5546 fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
5547 match self.sub8_mode_row.get(mi_r) {
5548 Some(&(col, m)) if mi_c > self.tile_col0_mi && col == mi_c - 1 => Some(m),
5549 _ => None,
5550 }
5551 }
5552
5553 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
5554 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
5555 fn record_uv_mode_mi(
5556 &mut self,
5557 mi_r: usize,
5558 mi_c: usize,
5559 mi_w: usize,
5560 mi_h: usize,
5561 uv_mode: usize,
5562 ) {
5563 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
5564 for cell in 0..mi_w {
5565 if let Some(slot) = self.uv_mode_col.get_mut(mi_c + cell) {
5566 *slot = (last_r, uv_mode);
5567 }
5568 }
5569 for cell in 0..mi_h {
5570 if let Some(slot) = self.uv_mode_row.get_mut(mi_r + cell) {
5571 *slot = (last_c, uv_mode);
5572 }
5573 }
5574 }
5575
5576 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
5577 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
5578 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
5579 /// block has recorded the exact neighbouring mi.
5580 fn smooth_uv_neighbour(&self, mi_r: usize, mi_c: usize, r: usize, c: usize) -> bool {
5581 // lane-kf900 r2: libaom reads the chroma neighbours off the CHROMA
5582 // REFERENCE block, not off the mi that carries the chroma syntax.
5583 // `set_mi_row_col` (`blockd.h`) takes
5584 // `base_mi = &xd->mi[-(mi_row & ss_y) * stride - (mi_col & ss_x)]` and
5585 // only then `chroma_above_mbmi = base_mi[-stride]` /
5586 // `chroma_left_mbmi = base_mi[-1]`. A sub-8 pair codes its chroma at
5587 // the ODD mi, so without the snap we looked one mi row/column too far
5588 // down/right -- the mi-exact slot never matched and the coarse
5589 // fallback answered instead. Measured on a 4K 10-bit key frame, chroma
5590 // 8x4 at (688, 100) = mi (51, 344): libaom's
5591 // `get_intra_edge_filter_type` is 1 (the chroma block above it is
5592 // `UV_SMOOTH_PRED`), ours was 0, which flips
5593 // `av1_use_intra_edge_upsample(8, 4, -6, type)` (`blk_wh == 12`:
5594 // false for type 1, TRUE for type 0) and upsampled an edge libaom
5595 // leaves alone -- +1 on rows 2/3 of that block and every chroma block
5596 // predicting from it (class `context-read-from-one-cell`).
5597 self.smooth_uv_neighbour_unsnapped(mi_r & !1, mi_c & !1, r, c)
5598 }
5599
5600 /// [`Self::smooth_uv_neighbour`] without the chroma-reference snap, i.e.
5601 /// read off the mi passed in exactly. Only the 16x4/4x16 pair witness
5602 /// counter wants this: it measures how often the snap CHANGES the answer,
5603 /// which is what the lane-kf1200/kf900 chroma-reference fix buys. Every
5604 /// decode path uses the snapping form.
5605 fn smooth_uv_neighbour_unsnapped(
5606 &self,
5607 mi_r: usize,
5608 mi_c: usize,
5609 r: usize,
5610 c: usize,
5611 ) -> bool {
5612 // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the
5613 // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid
5614 // array that `start_tile` does not clear, so a block on a tile's first
5615 // mi row used to read the uv_mode of the block above it in the tile
5616 // ABOVE and filter its chroma edge at that neighbour's strength
5617 // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block
5618 // at chroma (120, 32), the top-right tile's first block).
5619 let have_above = mi_r > self.tile_row0_mi;
5620 let have_left = mi_c > self.tile_col0_mi;
5621 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
5622 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
5623 {
5624 UV_TILE_EDGE_SUPPRESSED_HITS.with(|h| h.set(h.get() + 1));
5625 }
5626 let above = match self.uv_mode_col.get(mi_c) {
5627 Some(&(row, m)) if have_above && row == mi_r - 1 => m,
5628 _ if have_above => self.above_uv_mode[c],
5629 _ => DC_PRED,
5630 };
5631 let left = match self.uv_mode_row.get(mi_r) {
5632 Some(&(col, m)) if have_left && col == mi_c - 1 => m,
5633 _ if have_left => self.left_uv_mode[r],
5634 _ => DC_PRED,
5635 };
5636 // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs
5637 // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would
5638 // have been filtered at the wrong strength by the coarse map alone.
5639 if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] {
5640 UV_MODE_MI_OVERRIDE_HITS.with(|h| h.set(h.get() + 1));
5641 }
5642 is_smooth_mode(above) || is_smooth_mode(left)
5643 }
5644
5645 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
5646 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
5647 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
5648 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
5649 /// holding an OLDER, larger block's mode -- it only ever recorded into the
5650 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
5651 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
5652 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
5653 /// a different CDF for the same mode value).
5654 /// lane-rectsplitx r2: availability-correct above/left luma modes for a
5655 /// block whose top-left mi is `(mi_r, mi_c)`. libaom reads `above_mbmi`
5656 /// only when `up_available` and `left_mbmi` only when `left_available`;
5657 /// the coarse [`SUB`] bands cannot express that, and with 8-px strips they
5658 /// actively lie -- four 32x8 strips of one `HORZ_4` share ONE 16x16
5659 /// `left_mode` cell, so the second strip at tile column 0 read the FIRST
5660 /// strip's mode as its "left neighbour" (measured on the band fixture at
5661 /// mi(10,0): mode 2 where libaom has DC, a different `kf_y_mode` row).
5662 fn modes_above_left_mi(
5663 &self,
5664 mi_r: usize,
5665 mi_c: usize,
5666 fallback: (usize, usize),
5667 ) -> (usize, usize) {
5668 let above = if mi_r > self.tile_row0_mi {
5669 self.mode_above_mi(mi_r, mi_c).unwrap_or(fallback.0)
5670 } else {
5671 DC_PRED
5672 };
5673 let left = if mi_c > self.tile_col0_mi {
5674 self.mode_left_mi(mi_r, mi_c).unwrap_or(fallback.1)
5675 } else {
5676 DC_PRED
5677 };
5678 (above, left)
5679 }
5680
5681 /// lane-modectx r1: the coarse-[`SUB`]-grid entry point, now availability
5682 /// correct. The mi-exact lookups already refuse to cross a tile edge, but
5683 /// their FALLBACK (`above_mode`/`left_mode`) did not: `left_mode` is reset
5684 /// per superblock row and never per tile, so the first block column of
5685 /// tile 2..N read the previous tile's mode as its left neighbour, and the
5686 /// above band survives across a tile ROW boundary the same way lane-mtfix's
5687 /// `above_uv_mode` did. libaom reads `above_mbmi`/`left_mbmi` only when
5688 /// `up_available`/`left_available` and uses DC_PRED otherwise
5689 /// ([`Self::modes_above_left_mi`]).
5690 fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
5691 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
5692 let (above, left) =
5693 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));
5694 if above != self.above_mode[c] || left != self.left_mode[r] {
5695 MODE_MI_OVERRIDE_HITS.with(|h| h.set(h.get() + 1));
5696 }
5697 // A neighbour the coarse band offered where the tile edge makes it
5698 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).
5699 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)
5700 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)
5701 {
5702 MODE_TILE_EDGE_COARSE_LEAKS.with(|h| h.set(h.get() + 1));
5703 }
5704 (above, left)
5705 }
5706
5707 fn record_rect(
5708 &mut self,
5709 at: (usize, usize),
5710 w: usize,
5711 h: usize,
5712 mode: usize,
5713 uv_mode: usize,
5714 grids: &[Vec<i32>; 3],
5715 ) {
5716 self.record_rect_mi(sub16_to_mi(at), w, h, mode, uv_mode, grids);
5717 }
5718
5719 /// [`Self::record_rect`] in mi (4 px) units -- lane-inter4 r1: a
5720 /// 32x8/8x32 strip of a 32-level 1:4 partition sits at an 8-px offset the
5721 /// [`SUB`]-unit `at` cannot name. The coarse 16-px bands are still keyed
5722 /// by the enclosing cell (a sub-16 extent writes none of them, exactly as
5723 /// the [`SUB`]-unit path does).
5724 fn record_rect_mi(
5725 &mut self,
5726 at_mi: (usize, usize),
5727 w: usize,
5728 h: usize,
5729 mode: usize,
5730 uv_mode: usize,
5731 grids: &[Vec<i32>; 3],
5732 ) {
5733 let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI));
5734 // lane-inter4 r2: a strip whose own footprint runs past the frame's
5735 // last 16-px column/row stamps only the cells that exist (libaom's
5736 // arrays are padded past the frame and those cells are never read).
5737 for cell in 0..w / SUB {
5738 if c + cell >= self.above_mode.len() {
5739 break;
5740 }
5741 self.above_mode[c + cell] = mode;
5742 self.above_uv_mode[c + cell] = uv_mode;
5743 self.above_side[c + cell] = w;
5744 }
5745 for cell in 0..h / SUB {
5746 if r + cell >= self.left_mode.len() {
5747 break;
5748 }
5749 self.left_mode[r + cell] = mode;
5750 self.left_uv_mode[r + cell] = uv_mode;
5751 self.left_side[r + cell] = h;
5752 }
5753 self.record_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, mode);
5754 self.record_uv_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, uv_mode);
5755 self.record_mi_rect(at_mi, w, h, grids);
5756 }
5757
5758 /// The coefficient-context half of [`Self::record`], taking the block's
5759 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
5760 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
5761 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
5762 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
5763 self.record_mi_rect(at_mi, side, side, grids);
5764 }
5765
5766 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
5767 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
5768 fn record_mi_rect(
5769 &mut self,
5770 at_mi: (usize, usize),
5771 w: usize,
5772 h: usize,
5773 grids: &[Vec<i32>; 3],
5774 ) {
5775 let (mi_r, mi_c) = at_mi;
5776 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
5777 let (w_mi, h_mi) = (w / MI, h / MI);
5778 for cell in 0..h_mi {
5779 if let Some(slot) = self.left_side_mi.get_mut(mi_r + cell) {
5780 *slot = h;
5781 }
5782 }
5783 for cell in 0..w_mi {
5784 if let Some(slot) = self.above_side_mi.get_mut(mi_c + cell) {
5785 *slot = w;
5786 }
5787 }
5788 // A chroma 4x4 unit straddling the true luma edge is still whole in
5789 // chroma's own halved grid, so libaom rounds the luma bound up to the
5790 // plane's own 4x4 unit before clamping a subsampled plane
5791 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
5792 let round_up_even = |n: usize| n.div_ceil(2) * 2;
5793 let bound_h = [
5794 self.mi_rows,
5795 round_up_even(self.mi_rows),
5796 round_up_even(self.mi_rows),
5797 ];
5798 let bound_w = [
5799 self.mi_cols,
5800 round_up_even(self.mi_cols),
5801 round_up_even(self.mi_cols),
5802 ];
5803 for cell in 0..h_mi {
5804 // lane-sb128c r7: a 128x64 at the bottom frame edge names mi rows
5805 // past the padded side arrays (mi_rows 198, block rows 192..208);
5806 // libaom's own arrays are superblock-sized, so those cells simply
5807 // have no reader. Same guard the `left_side_mi` loop above uses.
5808 let Some(left_slot) = self.left.get_mut(mi_r + cell) else {
5809 break;
5810 };
5811 *left_slot = std::array::from_fn(|plane| {
5812 if cell < h_mi.min(bound_h[plane].saturating_sub(mi_r)) {
5813 states[plane]
5814 } else {
5815 Default::default()
5816 }
5817 });
5818 }
5819 for cell in 0..w_mi {
5820 let Some(above_slot) = self.above.get_mut(mi_c + cell) else {
5821 break;
5822 };
5823 *above_slot = std::array::from_fn(|plane| {
5824 if cell < w_mi.min(bound_w[plane].saturating_sub(mi_c)) {
5825 states[plane]
5826 } else {
5827 Default::default()
5828 }
5829 });
5830 }
5831 }
5832
5833 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
5834 /// inside a coded block whose luma transform is smaller than its own
5835 /// side (`TxMode::Select`): the real per-transform-unit coefficient
5836 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
5837 /// coarse per-block `tx_grid`/`fill_lf_grid` state
5838 /// [`Self::record_split_luma`] still writes once for the whole block.
5839 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
5840 /// the caller's own [`Self::record_split_luma`] call sets those once,
5841 /// at the block's own true side, not this TU's.
5842 fn record_mi_luma(&mut self, at_mi: (usize, usize), tx_px: usize, grid: &[i32]) {
5843 self.record_mi_luma_rect(at_mi, tx_px, tx_px, grid);
5844 }
5845
5846 /// [`Self::record_mi_luma`] for ONE CHROMA transform unit of a block whose
5847 /// uv plane block is several units (lane-sb128b r2: a 128x128 block's
5848 /// 64x64 uv plane block is four TX_32X32 units, `av1_get_max_uv_txsize`).
5849 /// `w_px`/`h_px` are the unit's extent in LUMA pixels -- the chroma
5850 /// coefficient-context arrays are indexed by luma mi, the convention
5851 /// [`Self::record_split_luma_rect_mi`] already writes them in, frame-edge
5852 /// clamp included.
5853 fn record_mi_chroma(
5854 &mut self,
5855 (mi_r, mi_c): (usize, usize),
5856 w_px: usize,
5857 h_px: usize,
5858 plane: usize,
5859 grid: &[i32],
5860 ) {
5861 let round_up_even = |n: usize| n.div_ceil(2) * 2;
5862 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
5863 let state = neighbour_state(grid);
5864 for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) {
5865 self.left[mi_r + cell][plane] = state;
5866 }
5867 for cell in 0..(w_px / MI).min(bound_w.saturating_sub(mi_c)) {
5868 self.above[mi_c + cell][plane] = state;
5869 }
5870 }
5871
5872 /// [`Self::record_mi_luma`] for a RECTANGULAR transform unit (lane-rectsplitx
5873 /// r1): the above context spans the unit's width, the left context its
5874 /// height, which for a square unit is the same loop it always was.
5875 fn record_mi_luma_rect(
5876 &mut self,
5877 (mi_r, mi_c): (usize, usize),
5878 w_px: usize,
5879 h_px: usize,
5880 grid: &[i32],
5881 ) {
5882 let state = neighbour_state(grid);
5883 for cell in 0..h_px / MI {
5884 if mi_r + cell < self.mi_rows {
5885 self.left[mi_r + cell][0] = state;
5886 }
5887 }
5888 for cell in 0..w_px / MI {
5889 if mi_c + cell < self.mi_cols {
5890 self.above[mi_c + cell][0] = state;
5891 }
5892 }
5893 }
5894
5895 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
5896 /// block whose luma was decoded as several transform units through
5897 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
5898 /// whole-block luma write -- everything [`Self::record`] does except
5899 /// plane 0, which is already correct per-TU by the time this runs.
5900 fn record_split_luma(
5901 &mut self,
5902 at: (usize, usize),
5903 side: usize,
5904 mode: usize,
5905 uv_mode: usize,
5906 chroma_grids: [&[i32]; 2],
5907 ) {
5908 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
5909 }
5910
5911 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
5912 /// extents in pixels (lane-rectsplit r1), the same relationship
5913 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
5914 /// luma transform split into several square units needs exactly this
5915 /// bookkeeping, at its own true rectangular extents.
5916 fn record_split_luma_rect(
5917 &mut self,
5918 at: (usize, usize),
5919 w: usize,
5920 h: usize,
5921 mode: usize,
5922 uv_mode: usize,
5923 chroma_grids: [&[i32]; 2],
5924 ) {
5925 let (r, c) = at;
5926 self.record_split_luma_rect_mi(
5927 (r * (SUB / MI), c * (SUB / MI)),
5928 w,
5929 h,
5930 mode,
5931 uv_mode,
5932 chroma_grids,
5933 );
5934 }
5935
5936 /// [`Self::record_split_luma_rect`] addressed in mi units (lane-rectsplitx
5937 /// r1) -- a strip 8 px tall starts mid-[`SUB`]-cell, which the coarse
5938 /// `(r, c)` form cannot name. The coarse mode/side arrays are stamped for
5939 /// every cell the strip TOUCHES (`div_ceil`), last writer wins, the
5940 /// convention [`decode_block_rect4`] already established for 1:4 strips.
5941 fn record_split_luma_rect_mi(
5942 &mut self,
5943 at_mi: (usize, usize),
5944 w: usize,
5945 h: usize,
5946 mode: usize,
5947 uv_mode: usize,
5948 chroma_grids: [&[i32]; 2],
5949 ) {
5950 let (mi_r, mi_c) = at_mi;
5951 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
5952 for cell in 0..w.div_ceil(SUB) {
5953 if c + cell >= self.above_mode.len() {
5954 break;
5955 }
5956 self.above_mode[c + cell] = mode;
5957 self.above_uv_mode[c + cell] = uv_mode;
5958 self.above_side[c + cell] = w;
5959 }
5960 for cell in 0..h.div_ceil(SUB) {
5961 if r + cell >= self.left_mode.len() {
5962 break;
5963 }
5964 self.left_mode[r + cell] = mode;
5965 self.left_uv_mode[r + cell] = uv_mode;
5966 self.left_side[r + cell] = h;
5967 }
5968
5969 let (w_mi, h_mi) = (w / MI, h / MI);
5970 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
5971 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
5972 for cell in 0..h_mi {
5973 if let Some(slot) = self.left_side_mi.get_mut(mi_r + cell) {
5974 *slot = h;
5975 }
5976 }
5977 for cell in 0..w_mi {
5978 if let Some(slot) = self.above_side_mi.get_mut(mi_c + cell) {
5979 *slot = w;
5980 }
5981 }
5982 let round_up_even = |n: usize| n.div_ceil(2) * 2;
5983 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
5984 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
5985 let plane = plane_idx + 1;
5986 let state = neighbour_state(grid);
5987 for cell in 0..h_mi {
5988 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
5989 self.left[mi_r + cell][plane] = state;
5990 }
5991 }
5992 for cell in 0..w_mi {
5993 if cell < w_mi.min(bound_w.saturating_sub(mi_c)) {
5994 self.above[mi_c + cell][plane] = state;
5995 }
5996 }
5997 }
5998 }
5999}
6000
6001/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
6002/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
6003/// exactly — including its skip context, which the real key-frame writer
6004/// always writes at a fixed context of zero (it never tracks a neighbour-based
6005/// one for intra blocks; that is the inter-frame writer's rule instead).
6006/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
6007/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
6008/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
6009/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
6010/// plain DC chroma.
6011/// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which
6012/// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's
6013/// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode
6014/// instead (the defect commit 1a89ed9 fixed at the square sites).
6015fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize {
6016 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
6017 filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi])
6018}
6019
6020/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
6021/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
6022/// bound (spec `filter_intra_mode_info` never reads a symbol there).
6023fn filter_intra_size_class(side: usize) -> Option<usize> {
6024 match side {
6025 4 => Some(0),
6026 8 => Some(1),
6027 16 => Some(2),
6028 32 => Some(3),
6029 _ => None,
6030 }
6031}
6032
6033/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
6034/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
6035/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
6036/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
6037fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
6038 match (bw, bh) {
6039 (32, 16) => Some(4),
6040 (16, 32) => Some(5),
6041 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
6042 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
6043 // here dropped that symbol on every DC_PRED strip of that size and
6044 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
6045 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
6046 (16, 8) => Some(6),
6047 (8, 16) => Some(7),
6048 // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <=
6049 // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of
6050 // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0.
6051 (4, 8) => Some(8),
6052 (8, 4) => Some(9),
6053 // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair
6054 // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no
6055 // `use_filter_intra` symbol on those strips although aomenc writes
6056 // one for every DC_PRED block of that shape with
6057 // `--enable-filter-intra=1` (its default), silently desyncing the
6058 // tile (class symbol-consumption-gap).
6059 (32, 8) => Some(10),
6060 (8, 32) => Some(11),
6061 // lane-r14: the 16x16-level 1:4 pair (`decode_rect4_16`'s 16x4/4x16
6062 // strips), rows 17/16 of `default_filter_intra_cdfs`.
6063 (16, 4) => Some(12),
6064 (4, 16) => Some(13),
6065 _ if bw == bh => filter_intra_size_class(bw),
6066 _ => None,
6067 }
6068}
6069
6070/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
6071/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
6072/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
6073/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
6074/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
6075fn palette_bsize_ctx(side: usize) -> Option<usize> {
6076 palette_bsize_ctx_wh(side, side)
6077}
6078
6079/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
6080/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
6081/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
6082/// for ANY bsize, not just the square ones a hand-picked table happened to
6083/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
6084/// row breaks the moment its indexing field moves off the diagonal, and a
6085/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
6086/// block dimension is a power of two, so `bw*bh` always is too and
6087/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
6088/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
6089fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
6090 // lane-r14: `av1_allow_palette`'s bound is `sb_type >= BLOCK_8X8` by the
6091 // BLOCK_SIZES_ALL enum INDEX, which the 1:4 shapes BLOCK_4X16 (16) and
6092 // BLOCK_16X4 (17) clear -- a 64-pixel block, so `av1_get_palette_bsize_ctx`
6093 // (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`) is 0 for them, exactly as
6094 // for an 8x8. Reading the dimension bound as "both sides >= 8" dropped
6095 // `palette_y_mode` on every 16x4/4x16 strip of a screen-content frame.
6096 if bw > 64 || bh > 64 || bw * bh < 64 {
6097 return None;
6098 }
6099 Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
6100}
6101
6102/// A just-decoded palette-Y block's own size, base colours (only the first
6103/// `size` entries are real), and per-pixel colour-index map (`side*side`,
6104/// row-major, each entry `< size`).
6105struct PaletteY {
6106 size: usize,
6107 colors: [u16; 8],
6108 map: Vec<u8>,
6109}
6110
6111/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
6112/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
6113/// shared between U and V, both co-located after 4:2:0 subsampling) plus
6114/// each plane's own base colours.
6115struct PaletteUv {
6116 size: usize,
6117 u_colors: [u16; 8],
6118 v_colors: [u16; 8],
6119 map: Vec<u8>,
6120}
6121
6122/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
6123/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
6124/// `get_unsigned_bits`, which is the same formula): smallest `n` with
6125/// `2^n >= x`, `0` for `x <= 1`.
6126fn ceil_log2(x: u32) -> u32 {
6127 if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() }
6128}
6129
6130/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
6131/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
6132fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
6133 let l = ceil_log2(n as u32);
6134 let m = (1usize << l) - n;
6135 let v = dec.literal(l - 1) as usize;
6136 if v < m {
6137 v
6138 } else {
6139 (v << 1) - m + dec.literal(1) as usize
6140 }
6141}
6142
6143/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
6144/// colours (already-known, from the above/left neighbours) with the
6145/// ascending `transmitted` ones (delta-coded off the wire) back into one
6146/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
6147/// value picks the cached copy first, matching the C `<=`.
6148fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
6149 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
6150 let (mut ci, mut ti) = (0, 0);
6151 while ci < cached.len() && ti < transmitted.len() {
6152 if cached[ci] <= transmitted[ti] {
6153 out.push(cached[ci]);
6154 ci += 1;
6155 } else {
6156 out.push(transmitted[ti]);
6157 ti += 1;
6158 }
6159 }
6160 out.extend_from_slice(&cached[ci..]);
6161 out.extend_from_slice(&transmitted[ti..]);
6162 out
6163}
6164
6165/// `read_palette_colors_y` (decodemv.c:478), at the sequence's real
6166/// `bit_depth` -- lane-kf900 r3: every raw literal here (the first colour,
6167/// each delta's width, the `range` bound and the clamp) is sized by
6168/// `bit_depth`, and hardcoding 8 read 2 bits too few per colour on every
6169/// 10-bit palette block. Raw literals are EQUIPROBABLE, and at the ranges
6170/// this stream reaches (e.g. 62728) an equiprobable read is a FIXED POINT of
6171/// the msac range, so a cross-decoder range ladder stays bit-identical
6172/// through the whole miscount -- only the decoded VALUE differs (class
6173/// `compare-range-not-tell`'s blind spot). (this
6174/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
6175/// (one flag bit each, in cache order), then delta-codes the remainder
6176/// (first value raw, each following delta `>= 1` off a shrinking bit width),
6177/// and merges the two ascending lists back together.
6178fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> [u16; 8] {
6179 let mut cached = Vec::with_capacity(n);
6180 for &c in cache {
6181 if cached.len() >= n {
6182 break;
6183 }
6184 if dec.literal(1) == 1 {
6185 cached.push(c);
6186 }
6187 }
6188 let bd = u32::from(bit_depth());
6189 let max_val = (1i32 << bd) - 1;
6190 let mut colors = [0u16; 8];
6191 let n_cached = cached.len();
6192 if n_cached < n {
6193 let mut transmitted = Vec::with_capacity(n - n_cached);
6194 let first = dec.literal(bd) as u16;
6195 transmitted.push(first);
6196 if n_cached + 1 < n {
6197 let min_bits = bd - 3;
6198 let mut bits = min_bits + dec.literal(2);
6199 let mut range = (1i32 << bd) - i32::from(first) - 1;
6200 for _ in (n_cached + 1)..n {
6201 let delta = dec.literal(bits) as i32 + 1;
6202 let prev = *transmitted.last().unwrap();
6203 let val = (i32::from(prev) + delta).clamp(0, max_val) as u16;
6204 range -= i32::from(val) - i32::from(prev);
6205 bits = bits.min(ceil_log2(range.max(0) as u32));
6206 transmitted.push(val);
6207 }
6208 }
6209 let merged = merge_colors(&transmitted, &cached);
6210 colors[..n].copy_from_slice(&merged);
6211 } else {
6212 colors[..n].copy_from_slice(&cached[..n]);
6213 }
6214 colors
6215}
6216
6217/// `read_palette_colors_uv` (decodemv.c:509), at the sequence's real
6218/// `bit_depth` (see [`read_palette_colors_y`]): U reads
6219/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
6220/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
6221/// unbiased by `+1` -- both differences from Y's own reader, matching the C
6222/// side by side). V never uses a cache: a leading bit picks either `n` raw
6223/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
6224/// rather than clamp.
6225fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> ([u16; 8], [u16; 8]) {
6226 let mut cached = Vec::with_capacity(n);
6227 for &c in cache {
6228 if cached.len() >= n {
6229 break;
6230 }
6231 if dec.literal(1) == 1 {
6232 cached.push(c);
6233 }
6234 }
6235 let bd = u32::from(bit_depth());
6236 let max_val = 1i32 << bd;
6237 let mut u_colors = [0u16; 8];
6238 let n_cached = cached.len();
6239 if n_cached < n {
6240 let mut transmitted = Vec::with_capacity(n - n_cached);
6241 let first = dec.literal(bd) as u16;
6242 transmitted.push(first);
6243 if n_cached + 1 < n {
6244 let min_bits = bd - 3;
6245 let mut bits = min_bits + dec.literal(2);
6246 let mut range = max_val - i32::from(first);
6247 for _ in (n_cached + 1)..n {
6248 let delta = dec.literal(bits) as i32;
6249 let prev = *transmitted.last().unwrap();
6250 let val = (i32::from(prev) + delta).clamp(0, max_val - 1) as u16;
6251 range -= i32::from(val) - i32::from(prev);
6252 bits = bits.min(ceil_log2(range.max(0) as u32));
6253 transmitted.push(val);
6254 }
6255 }
6256 let merged = merge_colors(&transmitted, &cached);
6257 u_colors[..n].copy_from_slice(&merged);
6258 } else {
6259 u_colors[..n].copy_from_slice(&cached[..n]);
6260 }
6261 let mut v_colors = [0u16; 8];
6262 if dec.literal(1) == 1 {
6263 let min_bits_v = bd - 4;
6264 let bits = min_bits_v + dec.literal(2);
6265 v_colors[0] = dec.literal(bd) as u16;
6266 for i in 1..n {
6267 let mut delta = dec.literal(bits) as i32;
6268 if delta != 0 && dec.literal(1) == 1 {
6269 delta = -delta;
6270 }
6271 let mut val = i32::from(v_colors[i - 1]) + delta;
6272 if val < 0 {
6273 val += max_val;
6274 }
6275 if val >= max_val {
6276 val -= max_val;
6277 }
6278 v_colors[i] = val as u16;
6279 }
6280 } else {
6281 for i in 0..n {
6282 v_colors[i] = dec.literal(bd) as u16;
6283 }
6284 }
6285 (u_colors, v_colors)
6286}
6287
6288/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
6289/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
6290/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
6291const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
6292
6293/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
6294/// map's own per-pixel context and colour-order permutation, from the
6295/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
6296/// selection sort). `map`'s stride is `side` (this decoder never crops a
6297/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
6298/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
6299/// actual colour index to store.
6300fn palette_color_index_context(
6301 map: &[u8],
6302 side: usize,
6303 row: usize,
6304 col: usize,
6305 n: usize,
6306) -> (usize, [u8; 8]) {
6307 let left = if col >= 1 { Some(map[row * side + col - 1]) } else { None };
6308 let up_left = if col >= 1 && row >= 1 {
6309 Some(map[(row - 1) * side + col - 1])
6310 } else {
6311 None
6312 };
6313 let up = if row >= 1 { Some(map[(row - 1) * side + col]) } else { None };
6314 let mut scores = [0i32; 8];
6315 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
6316 if let Some(v) = neighbour {
6317 scores[v as usize] += weight;
6318 }
6319 }
6320 let mut color_order = [0u8; 8];
6321 for i in 0..8 {
6322 color_order[i] = i as u8;
6323 }
6324 for i in 0..3 {
6325 let mut max = scores[i];
6326 let mut max_idx = i;
6327 for j in (i + 1)..n {
6328 if scores[j] > max {
6329 max = scores[j];
6330 max_idx = j;
6331 }
6332 }
6333 if max_idx != i {
6334 let max_score = scores[max_idx];
6335 let max_color = color_order[max_idx];
6336 for k in (i + 1..=max_idx).rev() {
6337 scores[k] = scores[k - 1];
6338 color_order[k] = color_order[k - 1];
6339 }
6340 scores[i] = max_score;
6341 color_order[i] = max_color;
6342 }
6343 }
6344 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
6345 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
6346 (ctx as usize, color_order)
6347}
6348
6349/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
6350/// map's wavefront decode over a `side x side` grid -- this decoder's
6351/// palette blocks are always square and never straddle the frame's true
6352/// (possibly odd) edge without already allocating the full `side*side`
6353/// region (every other skip/residual path here does the same), so no
6354/// rows/cols-vs-plane_width/height cropping special case is needed, unlike
6355/// libaom's own non-block-aligned split.
6356fn decode_color_index_map(
6357 dec: &mut SymbolDecoder,
6358 cdfs: &mut Cdfs,
6359 n: usize,
6360 side: usize,
6361 uv: bool,
6362) -> Vec<u8> {
6363 decode_color_index_map_wh(dec, cdfs, n, side, side, uv)
6364}
6365
6366/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
6367/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
6368/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
6369/// independently rather than one shared `side` -- the square call above is
6370/// just `bw == bh`.
6371fn decode_color_index_map_wh(
6372 dec: &mut SymbolDecoder,
6373 cdfs: &mut Cdfs,
6374 n: usize,
6375 bw: usize,
6376 bh: usize,
6377 uv: bool,
6378) -> Vec<u8> {
6379 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
6380 let mut map = vec![0u8; bw * bh];
6381 if trace {
6382 let (rng, _) = dec.debug_state();
6383 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
6384 }
6385 map[0] = read_uniform(dec, n) as u8;
6386 if trace {
6387 let (rng, _) = dec.debug_state();
6388 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
6389 }
6390 for i in 1..(bw + bh - 1) {
6391 let j_hi = i.min(bw - 1);
6392 let j_lo = i.saturating_sub(bh - 1);
6393 for j in (j_lo..=j_hi).rev() {
6394 let row = i - j;
6395 let col = j;
6396 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
6397 if trace {
6398 let (rng, _) = dec.debug_state();
6399 eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} rng={rng}");
6400 }
6401 let symbol = if uv {
6402 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
6403 } else {
6404 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
6405 };
6406 map[row * bw + col] = color_order[symbol];
6407 if trace {
6408 let (rng, _) = dec.debug_state();
6409 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
6410 }
6411 }
6412 }
6413 map
6414}
6415
6416/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
6417/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
6418/// size class comes from [`filter_intra_size_class_rect`] instead of the
6419/// square-only [`filter_intra_size_class`], and the palette read (when
6420/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
6421/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
6422/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
6423/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
6424#[allow(clippy::too_many_arguments)]
6425fn read_intra_mode_rect(
6426 dec: &mut SymbolDecoder,
6427 cdfs: &mut Cdfs,
6428 above_mode: usize,
6429 left_mode: usize,
6430 cfl: bool,
6431 // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall
6432 // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads
6433 // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's
6434 // chroma is coded once, on the closing strip). Every other caller is a
6435 // block big enough to own its chroma and passes `true`.
6436 has_chroma: bool,
6437 bw: usize,
6438 bh: usize,
6439 enable_filter_intra: bool,
6440 skip_ctx: usize,
6441 allow_screen_content_tools: bool,
6442 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
6443 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
6444 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
6445 palette: Option<(usize, &[u16])>,
6446 palette_uv_cache: &[u16],
6447 mi_r: usize,
6448 mi_c: usize,
6449) -> Result<(
6450 bool,
6451 usize,
6452 i32,
6453 usize,
6454 i32,
6455 Option<(i32, i32)>,
6456 Option<usize>,
6457 Option<PaletteY>,
6458 Option<PaletteUv>,
6459)> {
6460 let ec_istep = std::env::var_os("EC_TRACE_MODE_STEP").is_some();
6461 if ec_istep {
6462 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
6463 // (decodemv.c:818), printed at the same point: before the first
6464 // mode-info symbol of the block, so a cross-decoder range ladder can
6465 // be keyed on the BLOCK, not just on the symbol sequence.
6466 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);
6467 }
6468 macro_rules! istep {
6469 ($name:literal, $val:expr) => {
6470 if ec_istep {
6471 let (rng, _) = dec.debug_state();
6472 eprintln!(
6473 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
6474 $name, $val
6475 );
6476 }
6477 };
6478 }
6479 // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is
6480 // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at
6481 // the one point every rect caller routes through, so no call site can
6482 // offer the 14-symbol CFL alphabet on a 64-axis block (class
6483 // wrong-alphabet-same-value: same value, wrong interval, silent desync).
6484 let cfl = if cfl && bw.max(bh) > 32 {
6485 NOCFL_UV_MODE_HITS.with(|c| c.set(c.get() + 1));
6486 false
6487 } else {
6488 cfl
6489 };
6490 // lane-intra14 r1: on the INTER block path everything up to and including
6491 // `is_inter` was already read by [`decode_inter_block`], so this reader
6492 // starts at the mode syntax with the `skip` that caller read.
6493 let inter = INTRA_IN_INTER_MODE.with(std::cell::Cell::get);
6494 let skip = if let Some((_, skip)) = inter {
6495 skip
6496 } else {
6497 // Same `intra_segment_id` placement as the square reader above.
6498 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
6499 if seg_id_pre_skip() {
6500 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);
6501 }
6502 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
6503 istep!("skip", skip as i32);
6504 if !seg_id_pre_skip() {
6505 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);
6506 }
6507 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
6508 istep!("cdef", 0);
6509 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
6510 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
6511 // `false`.
6512 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip);
6513 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip);
6514 istep!("dq", 0);
6515 // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after
6516 // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the
6517 // `use_intrabc` symbol is read for EVERY intra block of an `allow_intrabc`
6518 // frame -- `av1_allow_intrabc` is a frame-level test with no shape term, so
6519 // rect strips read it exactly like square leaves ([`read_intra_mode`],
6520 // [`read_intra_mode_sub8`]). Missing it here desynced the arithmetic
6521 // decoder at the FIRST symbol of the first rect block of every
6522 // `--tune-content=screen` key frame. Reconstruction of a real intrabc
6523 // block at this shape is out of scope, so the flag is consumed and
6524 // refused by name when it fires.
6525 if allow_intrabc_frame() {
6526 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
6527 RECT_INTRABC_READS.with(|c| c.set(c.get() + 1));
6528 istep!("intrabc", use_intrabc as i32);
6529 if use_intrabc {
6530 INTRABC_HITS.with(|c| c.set(c.get() + 1));
6531 return Err(unsupported(
6532 "intra block copy on a HORZ/VERT/1:4 rect intra strip (reconstruction is not ported at this shape)",
6533 ));
6534 }
6535 }
6536 skip
6537 };
6538 // libaom `read_intra_block_mode_info` (decodemv.c:1189) vs the key
6539 // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode`
6540 // off `kf_y_mode_cdf[above][left]`).
6541 let mode = if let Some((size_group, _)) = inter {
6542 dec.symbol(&mut cdfs.y_mode[size_group])
6543 } else {
6544 let above_ctx = INTRA_MODE_CTX[above_mode];
6545 let left_ctx = INTRA_MODE_CTX[left_mode];
6546 dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx])
6547 };
6548 istep!("mode", mode as i32);
6549 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
6550 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
6551 } else {
6552 0
6553 };
6554 istep!("angle_y", angle_delta_y);
6555 // lane-sb128c r3 (class sweep): libaom `read_intra_mode_uv(.., is_cfl_allowed(xd), ..)`
6556 // and `is_cfl_allowed` (blockd.h) is `block_size_wide[bsize] <= 32 &&
6557 // block_size_high[bsize] <= 32` on the LUMA bsize. Deciding the alphabet
6558 // here, from the block's own size, is the single point every caller routes
6559 // through -- a caller passing `true` for a >32 strip used to pick the
6560 // 14-symbol CFL CDF, same value but a different range (class
6561 // wrong-alphabet-same-value).
6562 let cfl = cfl && bw <= 32 && bh <= 32;
6563 let uv_mode = if !has_chroma {
6564 DC_PRED
6565 } else if cfl {
6566 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
6567 } else {
6568 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
6569 };
6570 istep!("uv_mode", uv_mode as i32);
6571 let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED {
6572 Some(read_cfl_alphas(dec, cdfs))
6573 } else {
6574 None
6575 };
6576 if has_chroma && (9..=12).contains(&uv_mode) {
6577 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
6578 }
6579 let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) {
6580 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
6581 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
6582 } else {
6583 0
6584 };
6585 istep!("angle_uv", angle_delta_uv);
6586 if angle_delta_uv != 0 {
6587 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
6588 }
6589 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
6590 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
6591 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
6592 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
6593 // colours only here, the colour-index maps deferred past `filter_intra`
6594 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
6595 // runs from the caller, after the whole mode-info read).
6596 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
6597 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
6598 if allow_screen_content_tools
6599 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
6600 {
6601 // r6: this is the exact site the removed blanket refusal used to
6602 // guard -- reached for EVERY rect strip in a screen-content frame,
6603 // independent of whether the block ends up using a palette.
6604 RECT_SCREEN_CONTENT_HITS.with(|c| c.set(c.get() + 1));
6605 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
6606 let use_palette_y =
6607 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
6608 if use_palette_y {
6609 if palette.is_none() {
6610 return Err(unsupported(
6611 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
6612 ));
6613 }
6614 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
6615 let colors = read_palette_colors_y(dec, n, cache);
6616 palette_y_pending = Some((n, colors));
6617 }
6618 let palette_uv_mode_ctx = usize::from(use_palette_y);
6619 // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard.
6620 if has_chroma
6621 && uv_mode == DC_PRED
6622 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
6623 {
6624 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
6625 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache);
6626 palette_uv_pending = Some((n, u_colors, v_colors));
6627 }
6628 }
6629 let mut filter_intra = None;
6630 if std::env::var_os("EC_AV1_TRACE").is_some() {
6631 let (rng, _) = dec.debug_state();
6632 eprintln!(
6633 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
6634 class={:?} rng={rng}",
6635 enable_filter_intra as i32,
6636 filter_intra_size_class_rect(bw, bh)
6637 );
6638 }
6639 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
6640 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
6641 if mode == DC_PRED
6642 && enable_filter_intra
6643 && palette_y_pending.is_none()
6644 && let Some(class) = filter_intra_size_class_rect(bw, bh)
6645 {
6646 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
6647 if std::env::var_os("EC_AV1_TRACE").is_some() {
6648 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
6649 }
6650 istep!("use_filter_intra", use_filter_intra as i32);
6651 if use_filter_intra {
6652 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
6653 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
6654 istep!("filter_intra_mode", fi_mode as i32);
6655 filter_intra = Some(fi_mode);
6656 }
6657 }
6658 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
6659 // same order as [`read_intra_mode`]'s own square path.
6660 let palette_y = palette_y_pending.map(|(n, colors)| {
6661 let map = decode_color_index_map_wh(dec, cdfs, n, bw, bh, false);
6662 PALETTE_HITS.with(|c| c.set(c.get() + 1));
6663 PALETTE_RECT_HITS.with(|c| c.set(c.get() + 1));
6664 PaletteY { size: n, colors, map }
6665 });
6666 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
6667 // `av1_get_plane_block_size(bsize, 1, 1)` (`ss_size_lookup`), NOT a
6668 // plain halving: BLOCK_16X4 subsamples to BLOCK_8X4 and BLOCK_4X16 to
6669 // BLOCK_4X8, both floored at the 4-px transform. Halving the short
6670 // axis to 2 read HALF the colour-index symbols of a 1:4 strip's
6671 // chroma palette and desynced the tile from there.
6672 let (cw, ch) = ((bw / 2).max(4), (bh / 2).max(4));
6673 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, true);
6674 PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
6675 PaletteUv { size: n, u_colors, v_colors, map }
6676 });
6677 Ok((
6678 skip,
6679 mode,
6680 angle_delta_y,
6681 uv_mode,
6682 angle_delta_uv,
6683 alpha,
6684 filter_intra,
6685 palette_y,
6686 palette_uv,
6687 ))
6688}
6689
6690/// Stamps a 1:4 strip's palette state into the mi-granular above/left arrays,
6691/// at the strip's REAL mi position. `av1_get_palette_cache` reads
6692/// `xd->above_mbmi`/`xd->left_mbmi`, i.e. the mi cell above/left of the
6693/// block, so each strip owns its own rows and columns and no aliasing rule
6694/// is needed (lane-kf900 r6).
6695#[allow(clippy::too_many_arguments)]
6696fn record_strip_palette(
6697 n: &mut Neighbours,
6698 mi: (usize, usize),
6699 bw: usize,
6700 bh: usize,
6701 y_size: usize,
6702 y_colors: [u16; 8],
6703 uv_size: usize,
6704 uv_colors: [u16; 8],
6705) {
6706 let (r, c) = mi;
6707 // lane-kf900 r6: the palette side bands are mi-granular now, so a strip
6708 // writes its OWN span on BOTH axes -- the old `last` split-axis rule only
6709 // existed because the 16px [`SUB`] cell held one slot for all the strips
6710 // of a HORZ_4/VERT_4 and leaf 0 zeroing the other axis threw away the
6711 // real neighbour leaf 1 reads.
6712 {
6713 for cell in 0..(bw / MI).max(1) {
6714 if let Some(e) = n.above_palette_size.get_mut(c + cell) {
6715 *e = y_size;
6716 n.above_palette_colors[c + cell] = y_colors;
6717 n.above_palette_uv_size[c + cell] = uv_size;
6718 n.above_palette_uv_colors[c + cell] = uv_colors;
6719 }
6720 }
6721 }
6722 {
6723 for cell in 0..(bh / MI).max(1) {
6724 if n.left_palette_size.get(r + cell).is_none() {
6725 break;
6726 }
6727 n.left_palette_size[r + cell] = y_size;
6728 n.left_palette_colors[r + cell] = y_colors;
6729 n.left_palette_uv_size[r + cell] = uv_size;
6730 n.left_palette_uv_colors[r + cell] = uv_colors;
6731 }
6732 }
6733}
6734
6735/// [`tx_size_context`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
6736/// `get_tx_size_context` (libaom `pred_common.h`) compares the neighbour
6737/// above against this block's own *width* and the neighbour to the left
6738/// against its own *height* -- for a square block those are the same value,
6739/// which is why the square-only version can get away with one `own_side`.
6740fn tx_size_context_rect(
6741 n: &Neighbours,
6742 (mi_r, mi_c): (usize, usize),
6743 own_w: usize,
6744 own_h: usize,
6745) -> usize {
6746 // `get_tx_size_context` compares against `max_txsize_rect_lookup[bsize]`,
6747 // not the block's own side: no transform is wider or taller than 64, so a
6748 // block with a 128 side resolves against 64 (the square path already caps
6749 // this way, lane-sb128b r1). Without the cap the 64x128 half of a 128-root
6750 // VERT reads the tx-depth symbol off row 0 where libaom uses row 1.
6751 let (own_w, own_h) = (own_w.min(64), own_h.min(64));
6752 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w;
6753 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h;
6754 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
6755 eprintln!(
6756 "EC_TXCTX mi_row={mi_r} mi_col={mi_c} w={own_w} h={own_h} above_px={} left_px={} ctx={}",
6757 if mi_r > n.tile_row0_mi { tx_px_at(n, false, mi_r - 1, mi_c) } else { 0 },
6758 if mi_c > n.tile_col0_mi { tx_h_px_at(n, false, mi_r, mi_c - 1) } else { 0 },
6759 usize::from(above) + usize::from(left)
6760 );
6761 }
6762 usize::from(above) + usize::from(left)
6763}
6764
6765/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
6766fn cfl_ac_q3_rect(y: &PlaneBuf, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
6767 let (cw, ch) = (bw / 2, bh / 2);
6768 let mut ac = vec![0i32; cw * ch];
6769 let mut sum = 0i32;
6770 for cy in 0..ch {
6771 for cx in 0..cw {
6772 let (lx, ly) = (px + cx * 2, py + cy * 2);
6773 let q3 = (i32::from(y.data[ly * y.width + lx])
6774 + i32::from(y.data[ly * y.width + lx + 1])
6775 + i32::from(y.data[(ly + 1) * y.width + lx])
6776 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
6777 << 1;
6778 ac[cy * cw + cx] = q3;
6779 sum += q3;
6780 }
6781 }
6782 let num_pel = (cw * ch) as i32;
6783 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
6784 ac.iter_mut().for_each(|v| *v -= avg);
6785 ac
6786}
6787
6788/// Everything a rect strip already read out of the stream before its luma
6789/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
6790/// (nine values that would otherwise be nine more parameters).
6791struct RectStripModes {
6792 skip: bool,
6793 mode: usize,
6794 angle_delta_y: i32,
6795 uv_predict_mode: usize,
6796 angle_delta_uv: i32,
6797 alpha: Option<(i32, i32)>,
6798 filter_intra: Option<usize>,
6799 smooth_neighbor: bool,
6800 smooth_neighbor_uv: bool,
6801 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
6802 /// mapped through the colour table), sliced per transform unit below --
6803 /// palette prediction reads no edge pixels, so a unit's slice of the
6804 /// whole-block map IS its prediction. Without this a palette strip whose
6805 /// transform splits predicted DC and came out flat grey while the entropy
6806 /// stream stayed in sync (the coefficients are read either way).
6807 palette_y: Option<Vec<u16>>,
6808 /// As `palette_y`, for the un-split chroma transform (U, V).
6809 palette_uv: Option<(Vec<u16>, Vec<u16>)>,
6810}
6811
6812/// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth`
6813/// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times
6814/// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the
6815/// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's
6816/// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 ->
6817/// TX_32X16`) and only the second reaches a square -- the reason
6818/// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
6819/// already square) mis-tiled 1:4 strips.
6820fn depth_to_tx_wh(bw: usize, bh: usize, depth: usize) -> (usize, usize) {
6821 let (mut w, mut h) = (bw.min(64), bh.min(64));
6822 for _ in 0..depth {
6823 match w.cmp(&h) {
6824 std::cmp::Ordering::Greater => w /= 2,
6825 std::cmp::Ordering::Less => h /= 2,
6826 std::cmp::Ordering::Equal => {
6827 w /= 2;
6828 h /= 2;
6829 }
6830 }
6831 }
6832 (w, h)
6833}
6834
6835/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
6836/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
6837/// rect path here refused by name until now ("per-unit rect prediction is not
6838/// ported").
6839///
6840/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
6841/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
6842/// strip the very first step already lands on a SQUARE transform
6843/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
6844/// every further step halves a square) -- so each unit is square and reads
6845/// through the ordinary square [`read_plane`]. What is genuinely rectangular
6846/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
6847/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
6848/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
6849/// split by luma's depth.
6850///
6851/// Each unit predicts off whatever the earlier units of this same block
6852/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
6853/// inside `av1_foreach_transformed_block`, raster order), which is exactly
6854/// what predicting the whole strip in one shot got wrong.
6855#[allow(clippy::too_many_arguments)]
6856fn decode_rect_split(
6857 dec: &mut SymbolDecoder,
6858 cdfs: &mut Cdfs,
6859 neighbours: &mut Neighbours,
6860 at_mi: (usize, usize),
6861 bw: usize,
6862 bh: usize,
6863 // The transform unit's own width and height in pixels. Square for every
6864 // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
6865 // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
6866 // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
6867 tx_w: usize,
6868 tx_h: usize,
6869 m: &RectStripModes,
6870 y: &mut PlaneBuf,
6871 u: &mut PlaneBuf,
6872 v: &mut PlaneBuf,
6873 base_q_idx: u8,
6874 reduced_tx_set: bool,
6875) -> Result<()> {
6876 let (mi_r, mi_c) = at_mi;
6877 let (px, py) = (mi_c * MI, mi_r * MI);
6878 let (cpx, cpy) = (px / 2, py / 2);
6879 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
6880 // The chroma transform is picked before any symbol is read, so an
6881 // unsupported chroma shape refuses before this strip desyncs the tile.
6882 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
6883 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
6884 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
6885 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
6886 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
6887 // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32
6888 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx`
6889 // squares a rect transform down to a CDF set by
6890 // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set,
6891 // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets
6892 // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`)
6893 // paths already prove for these same shapes.
6894 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
6895 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
6896 (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])),
6897 (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])),
6898 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
6899 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
6900 _ => None,
6901 };
6902 if !m.skip {
6903 if let Some(i) = match (chroma_w, chroma_h) {
6904 (32, 8) => Some(0),
6905 (8, 32) => Some(1),
6906 (8, 4) => Some(2),
6907 (4, 8) => Some(3),
6908 _ => None,
6909 } {
6910 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
6911 let mut hits = c.get();
6912 hits[i] += 1;
6913 c.set(hits);
6914 });
6915 }
6916 if chroma.is_none() {
6917 // Diagnostic for the next caller that lands here (class
6918 // refusal-names-a-correlate: the message names the tool, not the
6919 // shape); the refusal below keeps its inventory-pinned wording.
6920 eprintln!("EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} chroma={chroma_w}x{chroma_h}");
6921 }
6922 }
6923 // lane-rectsplit r2 (verifier finding): with both callers wired
6924 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
6925 // 64x32/32x64) every shape that reaches here has a table above, so this
6926 // arm is UNREACHABLE today. It stays as the shape guard for the next
6927 // caller -- a new strip size would otherwise hit the `expect` below and
6928 // panic instead of refusing by name -- and so stays in
6929 // `refusal_inventory::REFUSALS`.
6930 if !m.skip && chroma.is_none() {
6931 return Err(unsupported(
6932 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
6933 ));
6934 }
6935 RECT_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
6936 if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 {
6937 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.set(c.get() + 1));
6938 }
6939 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
6940 // A square unit reads through the ordinary square [`read_plane`]; a rect
6941 // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with
6942 // the very tables the unsplit 16x8/32x16 paths use.
6943 let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) {
6944 (w, h) if w == h => None,
6945 (16, 8) | (8, 16) => Some((
6946 if reduced_tx_set {
6947 TxbSet::LumaRect16x8
6948 } else {
6949 TxbSet::LumaRect16x8Set1
6950 },
6951 if tx_w == 16 { &SCAN_16X8[..] } else { &SCAN_8X16[..] },
6952 )),
6953 (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])),
6954 (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])),
6955 // lane-rect64port r1: the un-split TX_64X32/TX_32X64 of a 64-level
6956 // strip, read through the `luma_64corner` arm below instead of a rect
6957 // table -- a 64-length axis codes only its low 32 coefficients
6958 // (`av1_get_max_eob` / the zero-out of `av1_get_adjusted_tx_size`), so
6959 // the coded unit is the 32x32 corner [`decode_block_rect64`]'s own
6960 // depth-0 arm already reads on the key-frame path.
6961 //
6962 // lane-sub8x4 r3: WITNESS FOUND, so this is no longer behind
6963 // `EC_RECT64_SPLIT`. r1's "no witness" was true only while the
6964 // sub-8x8 intra leaves still refused: with those lifted (r2) the
6965 // first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode
6966 // all 33 frames pixel-exact against ffmpeg while this arm fires 90x
6967 // 64x32 + 5x 32x64 -- pinned as `fixtures/reelb_rect64_intra16x4_witness.obu`
6968 // and gated by `a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact`.
6969 // lane-wit16x4 r1 re-measured that fixture on the merged tip: this arm
6970 // fires 64x32=148 32x64=123 (the 90/5 above were counted out of the
6971 // frame-33 desync lane-frame36 r2 fixed), all 33 frames pixel-exact.
6972 (64, 32) | (32, 64) => None,
6973 _ => {
6974 return Err(unsupported(format!(
6975 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \
6976 coefficient tables for that shape here)"
6977 )))
6978 }
6979 };
6980 // The `None` above that is NOT the square arm.
6981 let luma_64corner = tx_w != tx_h;
6982 // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact
6983 // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole
6984 // frame exactly, two sub-16 split strips in it), but the RECT-unit arm --
6985 // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the
6986 // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the
6987 // per-unit rect walk stay wired above/below; the round that finds that
6988 // defect deletes this refusal and nothing else.
6989 let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set);
6990 let luma_scan = default_scan(tx_w.min(tx_h));
6991 let zero_tu = vec![0i32; tx_w * tx_h];
6992 // The strip's OWN edge availability, the fallback for a transform unit
6993 // whose top-right/bottom-left pixels fall outside the strip.
6994 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
6995 for tu_row in 0..bh / tx_h {
6996 for tu_col in 0..bw / tx_w {
6997 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
6998 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
6999 let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h);
7000 // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged):
7001 // libaom clips `av1_foreach_transformed_block_in_plane` to
7002 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
7003 // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose
7004 // TOP-LEFT sample falls outside the frame is never coded. We read
7005 // coefficients for those phantom units and desynced the stream at
7006 // the very next symbol.
7007 if tu_px >= y.true_width || tu_py >= y.true_height {
7008 continue;
7009 }
7010 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
7011 // transform unit INSIDE a block, which is a different rule from
7012 // the standalone-block table [`Reach::of`] applies -- and the
7013 // reason a depth-2 superblock strip came out one sample off
7014 // before this: `Reach::of(tx, ..)` answered as if the unit were
7015 // its own block at that superblock position.
7016 // * top-right: if the unit's right neighbour is still inside the
7017 // strip the pixels are already reconstructed (`col_off +
7018 // tx_wide < plane_bw`); otherwise only the strip's own top row
7019 // of units can reach past it, through the block-level answer.
7020 // * bottom-left: a unit that is not in the strip's left column
7021 // has none (`col_off > 0` returns 0); inside the strip
7022 // (`row_off + tx_high < plane_bh`) they are the left
7023 // neighbour's, already reconstructed; the last row falls back
7024 // to the block-level answer.
7025 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach);
7026 // The unit's own window on the block's palette prediction.
7027 if let Some(buf) = &m.palette_y {
7028 let tu_buf: Vec<u16> = (0..tx_h)
7029 .flat_map(|i| {
7030 let base = (row_off + i) * bw + col_off;
7031 buf[base..base + tx_w].iter().copied()
7032 })
7033 .collect();
7034 set_palette_pred(tu_buf);
7035 }
7036 if m.skip {
7037 y.reconstruct_rect(
7038 tu_px,
7039 tu_py,
7040 tx_w,
7041 tx_h,
7042 m.mode,
7043 m.angle_delta_y,
7044 tu_reach,
7045 &zero_tu,
7046 None,
7047 m.filter_intra,
7048 m.smooth_neighbor,
7049 );
7050 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
7051 } else if luma_64corner && luma_rect.is_none() {
7052 // The un-split 64-level luma transform: `read_coeffs` on the
7053 // 32x32 CDF set [`TxbSet::Luma64`] with `default_scan(TX32)`
7054 // and the real rect shape passed through for
7055 // `av1_nz_map_ctx_offset` -- byte for byte
7056 // [`decode_block_rect64`]'s depth-0 read, which the key-frame
7057 // 64-level strip gate already proves. `tx_type` is not coded
7058 // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once
7059 // the square-up size is TX_64X64), and this unit covers its
7060 // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat.
7061 if std::env::var_os("EC_RECT64TU").is_some() {
7062 eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode);
7063 }
7064 RECT64_CORNER_TU_HITS.with(|c| {
7065 let mut v = c.get();
7066 v[usize::from(tx_h > tx_w)] += 1;
7067 c.set(v);
7068 });
7069 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
7070 let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra));
7071 let (corner, tu_tx_type) = read_coeffs(
7072 dec,
7073 &mut coding,
7074 &default_scan(TX32),
7075 0,
7076 dc_sign_ctx(tu_around.2),
7077 TxType::DctDct,
7078 Some((tx_w, tx_h)),
7079 )?;
7080 let (cw, ch) = (tx_w.min(TX32), tx_h.min(TX32));
7081 let mut tu_grid = vec![0i32; tx_w * tx_h];
7082 for row in 0..ch {
7083 tu_grid[row * tx_w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
7084 }
7085 let residual = dequant_and_inverse_typed_wh(
7086 &tu_grid,
7087 tx_w,
7088 tx_h,
7089 crate::decode::bit_depth(),
7090 block_q_idx(),
7091 plane_q_delta(0).0,
7092 plane_q_delta(0).1,
7093 tu_tx_type,
7094 );
7095 y.reconstruct_rect(
7096 tu_px,
7097 tu_py,
7098 tx_w,
7099 tx_h,
7100 m.mode,
7101 m.angle_delta_y,
7102 tu_reach,
7103 &residual,
7104 None,
7105 m.filter_intra,
7106 m.smooth_neighbor,
7107 );
7108 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
7109 } else if let Some((rect_set, rect_scan)) = luma_rect {
7110 // The rect-unit twin of the square arm below: same contexts,
7111 // same order, through the rect coefficient reader. The
7112 // `tx_type` CDF row of a filter-intra block is
7113 // `fimode_to_intradir[filter_intra_mode]`, never the block's
7114 // own (always DC_PRED) mode -- [`read_plane`] applies that
7115 // for the square arm, so this one must too.
7116 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
7117 // libaom `get_txb_ctx`: a LUMA transform that covers its whole
7118 // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the
7119 // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the
7120 // neighbour-magnitude table is for a unit SMALLER than its
7121 // block. [`decode_block_rect`]'s own unsplit read passes a
7122 // literal 0 for the same reason; this arm applied the table
7123 // unconditionally and desynced every depth-0 rect strip that
7124 // reached it (lane-intrarect r2: ctx 5 where aomdec read 0).
7125 let tu_skip_ctx = if tx_w == bw && tx_h == bh {
7126 0
7127 } else {
7128 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI)
7129 };
7130 let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra));
7131 let (tu_grid, tu_tx_type) = read_coeffs_rect(
7132 dec,
7133 &mut coding,
7134 rect_scan,
7135 tx_w,
7136 tx_h,
7137 tu_skip_ctx,
7138 dc_sign_ctx(tu_around.2),
7139 TxType::DctDct,
7140 )?;
7141 let residual = dequant_and_inverse_typed_wh(
7142 &tu_grid,
7143 tx_w,
7144 tx_h,
7145 crate::decode::bit_depth(),
7146 block_q_idx(),
7147 plane_q_delta(0).0,
7148 plane_q_delta(0).1,
7149 tu_tx_type,
7150 );
7151 y.reconstruct_rect(
7152 tu_px,
7153 tu_py,
7154 tx_w,
7155 tx_h,
7156 m.mode,
7157 m.angle_delta_y,
7158 tu_reach,
7159 &residual,
7160 None,
7161 m.filter_intra,
7162 m.smooth_neighbor,
7163 );
7164 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
7165 } else {
7166 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
7167 // This unit is smaller than the block it sits in, so
7168 // `txb_skip_ctx` is the neighbour-magnitude table, not the
7169 // lone-TU 0 (spec `get_txb_ctx_general`).
7170 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
7171 let tu_grid = read_plane(
7172 dec,
7173 cdfs,
7174 luma_set,
7175 &luma_scan,
7176 0,
7177 tu_around,
7178 m.mode,
7179 m.mode,
7180 m.angle_delta_y,
7181 tu_reach,
7182 y,
7183 tu_px,
7184 tu_py,
7185 tx_w,
7186 tx_w,
7187 base_q_idx,
7188 None,
7189 m.filter_intra,
7190 Some(tu_skip_ctx),
7191 m.smooth_neighbor,
7192 )?;
7193 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
7194 }
7195 }
7196 }
7197 // CHROMA: one un-split rect transform for the whole strip.
7198 let ac = m.alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
7199 let reach = block_reach;
7200 let (u_grid, v_grid) = if m.skip {
7201 let zero = vec![0i32; chroma_w * chroma_h];
7202 if let Some((ub, _)) = &m.palette_uv {
7203 set_palette_pred(ub.clone());
7204 }
7205 u.reconstruct_rect(
7206 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
7207 m.alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv,
7208 );
7209 if let Some((_, vb)) = &m.palette_uv {
7210 set_palette_pred(vb.clone());
7211 }
7212 v.reconstruct_rect(
7213 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
7214 m.alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv,
7215 );
7216 (zero.clone(), zero)
7217 } else {
7218 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
7219 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
7220 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
7221 // so only the 16x8/8x16 pair takes the mode-indexed default.
7222 let default_tx = if chroma_w.max(chroma_h) >= 32 {
7223 TxType::DctDct
7224 } else {
7225 default_intra_tx_type(m.uv_predict_mode as u8)
7226 };
7227 let around = neighbours.around_mi_rect(at_mi, bw, bh);
7228 let mut grids: Vec<Vec<i32>> = Vec::with_capacity(2);
7229 for plane_idx in 1..=2 {
7230 let skip_ctx =
7231 usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
7232 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
7233 let (levels, tx_type) = read_coeffs_rect(
7234 dec,
7235 &mut coding,
7236 chroma_scan,
7237 chroma_w,
7238 chroma_h,
7239 skip_ctx,
7240 dc_sign_ctx(around[plane_idx].2),
7241 default_tx,
7242 )?;
7243 // The same delta_q proof the unsplit rect64 path records
7244 // (lane-rectsplit r4: lifting the split-transform refusal moved
7245 // superblock strips onto this path, so only counting there would
7246 // leave the delta_q gate's counter silent for them).
7247 if bw.max(bh) == 64 && CURRENT_Q_IDX.with(|c| c.get()) != i32::from(base_q_idx) {
7248 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
7249 }
7250 let residual = dequant_and_inverse_typed_wh(
7251 &levels,
7252 chroma_w,
7253 chroma_h,
7254 crate::decode::bit_depth(),
7255 CURRENT_Q_IDX.with(|c| c.get()),
7256 plane_q_delta(plane_idx).0,
7257 plane_q_delta(plane_idx).1,
7258 tx_type,
7259 );
7260 let cfl = m
7261 .alpha
7262 .zip(ac.as_deref())
7263 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
7264 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
7265 if let Some((ub, vb)) = &m.palette_uv {
7266 let buf = if plane_idx == 1 { ub } else { vb };
7267 set_palette_pred(buf.clone());
7268 }
7269 plane.reconstruct_rect(
7270 cpx,
7271 cpy,
7272 chroma_w,
7273 chroma_h,
7274 m.uv_predict_mode,
7275 m.angle_delta_uv,
7276 reach,
7277 &residual,
7278 cfl,
7279 None,
7280 m.smooth_neighbor_uv,
7281 );
7282 grids.push(levels);
7283 }
7284 let mut it = grids.into_iter();
7285 (it.next().unwrap(), it.next().unwrap())
7286 };
7287 neighbours.record_split_luma_rect_mi(
7288 at_mi,
7289 bw,
7290 bh,
7291 m.mode,
7292 m.uv_predict_mode,
7293 [&u_grid, &v_grid],
7294 );
7295 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
7296 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
7297 if std::env::var_os("EC_AV1_TRACE").is_some() {
7298 let (rng, _) = dec.debug_state();
7299 eprintln!(
7300 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
7301 tx={tx_w}x{tx_h} rng={rng}"
7302 );
7303 }
7304 Ok(())
7305}
7306
7307/// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect
7308/// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name
7309/// because it predicts squares only. Every pixel here goes through the rect
7310/// machinery the key-frame paths already prove: [`decode_rect_split`], which
7311/// at `depth == 0` is the unsplit strip as a single transform unit and
7312/// beyond it the per-unit walk of [`depth_to_tx_wh`].
7313///
7314/// What is genuinely different from [`decode_block_rect`] is the mode
7315/// syntax: on an inter frame an intra block reads `y_mode[size_group]` and
7316/// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never
7317/// the key frame's `kf_y_mode` above/left pair. This mirrors the square
7318/// intra-in-inter arm's own reads at the rect footprint, including its
7319/// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe
7320/// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the
7321/// square and this arm) and a nonzero luma angle delta refused by name.
7322///
7323/// The strip's own neighbour records (luma per transform unit, chroma, skip
7324/// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the
7325/// inter-side bands and the mi map.
7326#[allow(clippy::too_many_arguments)]
7327fn decode_intra_rect_in_inter(
7328 dec: &mut SymbolDecoder,
7329 cdfs: &mut Cdfs,
7330 neighbours: &mut Neighbours,
7331 at: (usize, usize),
7332 bw: usize,
7333 bh: usize,
7334 skip: bool,
7335 allow_screen_content_tools: bool,
7336 // `(PARTITION_HORZ_4, is_chroma_reference)` when this strip is one of the
7337 // four 16x4 / 4x16 strips of a 16x16-level 1:4 partition (lane-intra16x4).
7338 strip16: Option<(bool, bool)>,
7339 y: &mut PlaneBuf,
7340 u: &mut PlaneBuf,
7341 v: &mut PlaneBuf,
7342 base_q_idx: u8,
7343) -> Result<()> {
7344 // `at` is in MI units (the inter path's own unit since lane-inter4);
7345 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands
7346 // below are still keyed by.
7347 let (mi_r, mi_c) = at;
7348 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
7349 // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat`
7350 // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 /
7351 // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx
7352 // finding -- the category is NOT the same for every strip size).
7353 // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so
7354 // it is refused by name rather than read from the wrong CDF row.
7355 // lane-intra16x4: the 16x16-level 1:4 strip. `size_group_lookup`
7356 // (common_data.h:61) puts BLOCK_16X4/BLOCK_4X16 in group 0 and its
7357 // tx-depth category is 1 -- but nothing here has to know either, because
7358 // the strip decodes through the very body the KEY FRAME path proves for
7359 // this shape ([`decode_rect4_16_strip`]), including the 4:2:0 chroma
7360 // pairing (`is_chroma_reference`: strips 0 and 2 read no chroma at all,
7361 // strips 1 and 3 code one 8x4 (4x8) unit at the PAIR's origin). The only
7362 // inter-frame difference is the mode-info read, which
7363 // [`INTRA_IN_INTER_MODE`] switches to `read_intra_block_mode_info`'s
7364 // `y_mode[0]` plus the `skip` this caller already read.
7365 if let Some((horz, has_chroma)) = strip16 {
7366 if allow_screen_content_tools {
7367 return Err(unsupported(
7368 "a HORZ/VERT intra strip in a screen-content frame (palette syntax \
7369 is consumed for square blocks only)",
7370 ));
7371 }
7372 debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) });
7373 INTRA_IN_INTER_MODE.with(|c| c.set(Some((0, skip))));
7374 let res = decode_rect4_16_strip(
7375 dec,
7376 cdfs,
7377 neighbours,
7378 (mi_r, mi_c),
7379 horz,
7380 has_chroma,
7381 // The inter strips of the same partition publish their own
7382 // mi-exact mode, so the key-frame caller's coarse-cell stand-in
7383 // has nothing to add here.
7384 None,
7385 y,
7386 u,
7387 v,
7388 ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get),
7389 allow_screen_content_tools,
7390 base_q_idx,
7391 TX_SELECT_INTER.with(std::cell::Cell::get),
7392 REDUCED_TX_SET_INTER.with(std::cell::Cell::get),
7393 );
7394 INTRA_IN_INTER_MODE.with(|c| c.set(None));
7395 let (mode, uv, (tx_w, tx_h)) = res?;
7396 // lane-intra16x4, the same publication the 2:1 intra-in-inter strip
7397 // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs
7398 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` for EVERY
7399 // block of an inter frame, intra ones included, and
7400 // `txfm_partition_update` for the var-tx context. The key-frame body
7401 // writes neither (a key frame has no var-tx tree and its own readers
7402 // use the deblock grid), so the block AFTER this strip read a stale
7403 // band -- measured: a 128x128 8-bit stream decoded the two intra 16x4
7404 // strips at mi(23,16)/(23,20) exactly and then broke on the very next
7405 // 16x16 row.
7406 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
7407 for i in 0..bw / MI {
7408 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
7409 *cell = tx_w as u8;
7410 }
7411 }
7412 for i in 0..bh / MI {
7413 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
7414 *cell = tx_h as u8;
7415 }
7416 }
7417 // [`decode_rect4_16`]'s own post-loop publication, per strip (the
7418 // coarse 16-px cell holds one entry for the whole 16x16 and the last
7419 // block to write it wins).
7420 neighbours.above_mode[c] = mode;
7421 neighbours.left_mode[r] = mode;
7422 if let Some(uvm) = uv {
7423 neighbours.above_uv_mode[c] = uvm;
7424 neighbours.left_uv_mode[r] = uvm;
7425 }
7426 neighbours.above_side[c] = bw;
7427 neighbours.left_side[r] = bh;
7428 if std::env::var_os("EC_INTRA16X4").is_some() {
7429 eprintln!(
7430 "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}",
7431 mi_c * MI,
7432 mi_r * MI
7433 );
7434 }
7435 INTRA16X4_IN_INTER_HITS.with(|h| {
7436 let mut v = h.get();
7437 v[usize::from(!horz)] += 1;
7438 v[2] += usize::from(has_chroma);
7439 h.set(v);
7440 });
7441 return Ok(());
7442 }
7443 // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half
7444 // coded INTRA inside an inter frame. `size_group_lookup` (common_data.h:61)
7445 // puts BLOCK_128X64/64X128/128X128 in group 3 and
7446 // `max_txsize_rect_lookup` caps them at TX_64X64, i.e. the same
7447 // `tx_size_cat3` row [`decode_block_128rect`] already reads -- so the whole
7448 // block decodes through the very body the KEY FRAME path proves for this
7449 // shape (square 64x64 luma units, one TX_32X32 chroma unit per 64x64 mu
7450 // chunk on the offset-10 txb_skip rows, per-TU prediction, the mu-chunk
7451 // `Reach` rule and the frame-edge write clip). The only inter-frame
7452 // differences live inside that body: the mode-info read
7453 // ([`INTRA_IN_INTER_MODE`] -> `y_mode[3]` plus the `skip` this caller
7454 // already read), the `tx_depth` context (the real TXFM_CONTEXT bands) and
7455 // the `set_txfm_ctxs` publication. CfL (>32), filter intra (>32) and
7456 // palette (>64) do not exist at this size and are refused by name there.
7457 // lane-inter128intra r1: OPT-IN ONLY (`EC_INTRA128_IN_INTER=1`) until a
7458 // gate exists. The body below is believed right (it is the key frame's own
7459 // proven body plus the three inter-frame differences), but the three 1080p
7460 // cuts that reach this shape reach it AFTER a pre-existing desync (see the
7461 // lane report: their frame 2 diverges from aomdec inside the superblock at
7462 // mi(0,320), long before mi(128,416)), and no aomenc recipe found so far
7463 // emits a 128-root HORZ/VERT half coded intra in an inter frame -- so
7464 // nothing can currently prove this arm. A refusal is lifted only with a
7465 // gate (COMMON), so the default path still refuses by name below.
7466 if bw.max(bh) == 128 && std::env::var_os("EC_INTRA128_IN_INTER").is_some() {
7467 if allow_screen_content_tools {
7468 return Err(unsupported(
7469 "a HORZ/VERT intra strip in a screen-content frame (palette syntax \
7470 is consumed for square blocks only)",
7471 ));
7472 }
7473 INTRA_IN_INTER_MODE.with(|c| c.set(Some((3, skip))));
7474 let res = decode_block_128rect(
7475 dec,
7476 cdfs,
7477 neighbours,
7478 (r, c),
7479 bw,
7480 bh,
7481 y,
7482 u,
7483 v,
7484 base_q_idx,
7485 ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get),
7486 allow_screen_content_tools,
7487 TX_SELECT_INTER.with(std::cell::Cell::get),
7488 REDUCED_TX_SET_INTER.with(std::cell::Cell::get),
7489 );
7490 INTRA_IN_INTER_MODE.with(|c| c.set(None));
7491 return res;
7492 }
7493 let (size_group, tx_cat) = match (bw.min(bh), bw.max(bh)) {
7494 (8, 16) => (1usize, 1usize),
7495 (16, 32) => (2, 2),
7496 (32, 64) => (3, 3),
7497 // lane-intra14 r1: the 1:4 strips, read off libaom's own tables --
7498 // `size_group_lookup` (common_data.h:61) gives BLOCK_8X32/32X8 group
7499 // 1 and BLOCK_16X64/64X16 group 2, while
7500 // `bsize_to_tx_size_depth_table` (blockd.h:1347) gives them depth
7501 // 3 and 4, i.e. tx categories 2 and 3 -- the diagonal a 2:1 strip
7502 // keeps is genuinely broken here, which is why the shape was refused
7503 // rather than read from the 2:1 row.
7504 (8, 32) => (1, 2),
7505 (16, 64) => (2, 3),
7506 _ => {
7507 if std::env::var_os("EC_OBMCREC").is_some() {
7508 eprintln!(
7509 "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}"
7510 );
7511 }
7512 // lane-obmcrec r1: the message used to name a 16x4/4x16 strip
7513 // (class refusal-names-a-correlate). Measured with `EC_OBMCREC=1`
7514 // on three 2 s cuts of the 10-bit 1920x792 128-superblock stream:
7515 // every arrival here is a 128x64 block -- a PARTITION_HORZ half of
7516 // a 128 superblock coded INTRA inside an inter frame, at mi
7517 // (128,416) / (192,0) / (192,0) -- not a strip at all.
7518 return Err(unsupported(format!(
7519 "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"
7520 )));
7521 }
7522 };
7523 // [`read_intra_mode_rect`]'s own refusal: palette/intrabc syntax is
7524 // consumed for square blocks only, so a strip in a screen-content frame
7525 // would skip symbols the encoder wrote.
7526 if allow_screen_content_tools {
7527 return Err(unsupported(
7528 "a HORZ/VERT intra strip in a screen-content frame (palette syntax \
7529 is consumed for square blocks only)",
7530 ));
7531 }
7532 // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY
7533 // FRAME path already proves for this shape ([`decode_block_rect4`] at the
7534 // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4
7535 // luma/chroma transform tables, the per-unit split walk and the strip's
7536 // own neighbour records). The ONLY difference on an inter frame is the
7537 // mode-info read, which [`INTRA_IN_INTER_MODE`] switches to
7538 // `read_intra_block_mode_info`'s `y_mode[size_group]` plus the `skip`
7539 // this caller already read. `tx_cat` above is the same category those
7540 // readers hardcode (cat 2 in `decode_block_rect4`, cat 3 in
7541 // `decode_block_rect64`), asserted here so a future shape cannot drift.
7542 if bw.max(bh) == 4 * bw.min(bh) {
7543 debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 });
7544 INTRA_IN_INTER_MODE.with(|c| c.set(Some((size_group, skip))));
7545 let res = if bw.max(bh) == 64 {
7546 decode_block_rect64(
7547 dec,
7548 cdfs,
7549 neighbours,
7550 (mi_r / (SUB / MI), mi_c / (SUB / MI)),
7551 bw,
7552 bh,
7553 y,
7554 u,
7555 v,
7556 ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get),
7557 allow_screen_content_tools,
7558 base_q_idx,
7559 TX_SELECT_INTER.with(std::cell::Cell::get),
7560 REDUCED_TX_SET_INTER.with(std::cell::Cell::get),
7561 )
7562 } else {
7563 decode_block_rect4(
7564 dec,
7565 cdfs,
7566 neighbours,
7567 (mi_r, mi_c),
7568 bw,
7569 bh,
7570 None,
7571 y,
7572 u,
7573 v,
7574 ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get),
7575 allow_screen_content_tools,
7576 base_q_idx,
7577 TX_SELECT_INTER.with(std::cell::Cell::get),
7578 )
7579 .map(|_| ())
7580 };
7581 INTRA_IN_INTER_MODE.with(|c| c.set(None));
7582 res?;
7583 let shape = match (bw, bh) {
7584 (64, 16) => 0,
7585 (16, 64) => 1,
7586 (32, 8) => 2,
7587 _ => 3,
7588 };
7589 INTRA_RECT4_IN_INTER_HITS.with(|h| {
7590 let mut v = h.get();
7591 v[shape] += 1;
7592 h.set(v);
7593 });
7594 return Ok(());
7595 }
7596 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
7597 // lane-t900 r1: this arm read six mode symbols with no ladder rung of its
7598 // own, so a cross-decoder bisection could only see the block's first
7599 // coefficient. Same names/format as [`read_tx_size`]'s rung.
7600 let step_trace = std::env::var_os("EC_TRACE_MODE_STEP").is_some();
7601 if step_trace {
7602 eprintln!(
7603 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}",
7604 dec.debug_state().0
7605 );
7606 }
7607 if mode >= 13 {
7608 return Err(unsupported(
7609 "an intra mode this decoder does not code (round 2)",
7610 ));
7611 }
7612 // lane-angleinter (merged on main for the square intra-in-inter arm):
7613 // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the
7614 // directional predictor; this arm refused a nonzero one before the merge.
7615 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
7616 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
7617 } else {
7618 0
7619 };
7620 if angle_delta_y != 0 {
7621 INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.set(c.get() + 1));
7622 }
7623 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
7624 // superblock-level strip reads the no-CFL alphabet -- the same split
7625 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
7626 let cfl_allowed = bw.max(bh) <= 32;
7627 let uv_mode = if cfl_allowed {
7628 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
7629 } else {
7630 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
7631 };
7632 if step_trace {
7633 eprintln!(
7634 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}",
7635 u8::from(cfl_allowed),
7636 dec.debug_state().0
7637 );
7638 }
7639 if (9..=12).contains(&uv_mode) {
7640 SMOOTH_UV_HITS.with(|h| h.set(h.get() + 1));
7641 }
7642 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
7643 Some(read_cfl_alphas(dec, cdfs))
7644 } else {
7645 None
7646 };
7647 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
7648 DC_PRED
7649 } else {
7650 uv_mode
7651 };
7652 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
7653 DIRECTIONAL_UV_HITS.with(|h| h.set(h.get() + 1));
7654 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
7655 } else {
7656 0
7657 };
7658 if angle_delta_uv != 0 {
7659 UV_ANGLE_DELTA_HITS.with(|h| h.set(h.get() + 1));
7660 INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|h| h.set(h.get() + 1));
7661 }
7662 // lane-fiinter (merged on main for the square intra-in-inter arm):
7663 // `read_filter_intra_mode_info` is the tail of
7664 // `read_intra_block_mode_info`, after the palette syntax (refused whole
7665 // above for this shape), and `av1_filter_intra_allowed_bsize` admits the
7666 // 2:1 strips with both sides <= 32 -- their own CDF rows
7667 // ([`filter_intra_size_class_rect`]).
7668 let mut filter_intra = None;
7669 if mode == DC_PRED
7670 && ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get)
7671 && let Some(class) = filter_intra_size_class_rect(bw, bh)
7672 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
7673 {
7674 FILTER_INTRA_HITS.with(|h| h.set(h.get() + 1));
7675 INTRA_IN_INTER_FILTER_INTRA_HITS.with(|h| h.set(h.get() + 1));
7676 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
7677 }
7678 // The intra-edge filter type is the NEIGHBOUR's mode (libaom
7679 // `get_filt_type`), luma's off the luma neighbours and chroma's off the
7680 // chroma ones -- [`decode_block_rect`]'s own pair.
7681 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
7682 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
7683 if smooth_neighbor {
7684 SMOOTH_LUMA_HITS.with(|h| h.set(h.get() + 1));
7685 }
7686 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
7687 let depth = if TX_SELECT_INTER.with(std::cell::Cell::get) {
7688 // The INTER frame's own `TXFM_CONTEXT` bands, not the key frame's
7689 // deblock-grid approximation -- [`tx_size_context_txfm_rect`].
7690 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64));
7691 let d = match tx_cat {
7692 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
7693 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
7694 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
7695 };
7696 if step_trace {
7697 eprintln!(
7698 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}",
7699 dec.debug_state().0
7700 );
7701 }
7702 d
7703 } else {
7704 0
7705 };
7706 if depth != 0 {
7707 TX_DEPTH_HITS.with(|h| h.set(h.get() + 1));
7708 // lane-intrasplit r1: a split intra strip in an inter frame walks the
7709 // key frame's own per-TU path ([`decode_rect_split`] below); what was
7710 // wrong when this refusal was written was the depth SYMBOL, not the walk.
7711 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(|h| {
7712 let mut v = h.get();
7713 v[depth.min(2)] += 1;
7714 h.set(v);
7715 });
7716 }
7717 // lane-intrasplit r3: print EVERY intra strip with its depth, not only the
7718 // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and
7719 // the two are indistinguishable when the diagnostic fires on splits alone.
7720 if std::env::var_os("EC_SPLITSTRIP").is_some() {
7721 eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}");
7722 }
7723 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
7724 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,
7725 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block
7726 // of an inter frame, intra ones included -- with the skip term 0 it
7727 // memsets `above_txfm_context` to `tx_size_wide` over the block's width
7728 // and `left_txfm_context` to `tx_size_high` over its height. This strip
7729 // wrote neither, so the next block's var-tx `txfm_partition` context read
7730 // a stale band: on a 192x128 8-bit stream the 16x8 intra strip at
7731 // mi(14,0) left 8 where libaom has 16, giving ctx 13 instead of 12 at
7732 // mi(16,0) and desyncing the tile at that symbol.
7733 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
7734 let modes = RectStripModes {
7735 skip,
7736 mode,
7737 angle_delta_y,
7738 uv_predict_mode,
7739 angle_delta_uv,
7740 alpha,
7741 filter_intra,
7742 smooth_neighbor,
7743 smooth_neighbor_uv,
7744 // screen-content frames are refused whole above, so this strip can
7745 // carry no palette.
7746 palette_y: None,
7747 palette_uv: None,
7748 };
7749 decode_rect_split(
7750 dec,
7751 cdfs,
7752 neighbours,
7753 (mi_r, mi_c),
7754 bw,
7755 bh,
7756 tx_w,
7757 tx_h,
7758 &modes,
7759 y,
7760 u,
7761 v,
7762 base_q_idx,
7763 REDUCED_TX_SET_INTER.with(std::cell::Cell::get),
7764 )?;
7765 // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of
7766 // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in
7767 // both `TXFM_CONTEXT` bands -- the above row over the block's width, the
7768 // left column over its height. This arm wrote neither before lane-intrasplit
7769 // r1, so every later block in the frame read a stale `tx_size`/`txfm_split`
7770 // context across the strip's footprint.
7771 for i in 0..bw / MI {
7772 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
7773 *cell = tx_w as u8;
7774 }
7775 }
7776 for i in 0..bh / MI {
7777 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
7778 *cell = tx_h as u8;
7779 }
7780 }
7781 let class = match bw.max(bh) {
7782 64 => 0,
7783 32 => 1,
7784 _ => 2,
7785 };
7786 INTRA_RECT_IN_INTER_HITS.with(|h| {
7787 let mut v = h.get();
7788 v[class] += 1;
7789 h.set(v);
7790 });
7791 Ok(())
7792}
7793
7794/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
7795/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
7796/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
7797/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
7798/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
7799/// has no rectangular-transform coefficient reader, and a chroma plane here
7800/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
7801/// with no depth-based square-tiling escape the way luma's own resolved
7802/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
7803/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
7804#[allow(clippy::too_many_arguments)]
7805fn decode_block_rect(
7806 dec: &mut SymbolDecoder,
7807 cdfs: &mut Cdfs,
7808 neighbours: &mut Neighbours,
7809 at: (usize, usize),
7810 bw: usize,
7811 bh: usize,
7812 y: &mut PlaneBuf,
7813 u: &mut PlaneBuf,
7814 v: &mut PlaneBuf,
7815 enable_filter_intra: bool,
7816 allow_screen_content_tools: bool,
7817 base_q_idx: u8,
7818 tx_select: bool,
7819 reduced_tx_set: bool,
7820) -> Result<()> {
7821 let (r, c) = at;
7822 let (px, py) = (c * SUB, r * SUB);
7823 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
7824 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
7825 let palette_uv_cache = neighbours.palette_uv_cache(at);
7826 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
7827 read_intra_mode_rect(
7828 dec,
7829 cdfs,
7830 nb_above_mode,
7831 nb_left_mode,
7832 true,
7833 true,
7834 bw,
7835 bh,
7836 enable_filter_intra,
7837 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
7838 allow_screen_content_tools,
7839 Some((palette_ctx, &palette_cache)),
7840 &palette_uv_cache,
7841 r * (SUB / MI),
7842 c * (SUB / MI),
7843 )?;
7844 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
7845 if smooth_neighbor {
7846 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
7847 }
7848 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
7849 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
7850 // `uv_mode`, not the luma one.
7851 let smooth_neighbor_uv =
7852 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
7853 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
7854 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
7855 // rectangle just as happily), so a `use_filter_intra` strip at this level
7856 // predicts instead of refusing. The below-16x16 leaf arm
7857 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
7858 if filter_intra.is_some() {
7859 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
7860 }
7861 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
7862 DC_PRED
7863 } else {
7864 uv_mode
7865 };
7866 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
7867 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
7868 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
7869 // one did not, so with `--enable-tx-size-search=0` -- which several gate
7870 // recipes use -- the decoder consumed a symbol the encoder never wrote and
7871 // desynced the tile from that point on. That is why both strips of the
7872 // pinned HORZ quadrant were wrong from their very first pixel, and why our
7873 // range after the read equalled the oracle's range for the whole block.
7874 let depth = if tx_select {
7875 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
7876 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
7877 // the 16x4 intra-in-inter strips already do); the key frame's
7878 // deblock-grid approximation is only right where those bands were never
7879 // written. Measured on the 10-bit 1920x792 128-superblock stream,
7880 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
7881 // `tx_size_cat2` row 1 where libaom reads row 2.
7882 let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {
7883 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh)
7884 } else {
7885 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
7886 };
7887 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
7888 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
7889 eprintln!(
7890 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
7891 dec.debug_state().0
7892 );
7893 }
7894 d
7895 } else {
7896 0
7897 };
7898 if depth != 0 {
7899 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
7900 // lane-rectsplit r1: a split transform is predicted and reconstructed
7901 // per transform unit, each unit taking its edges from the previous
7902 // unit's reconstruction inside this same strip (spec 5.11.36) --
7903 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
7904 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
7905 if std::env::var_os("EC_SBPART_DUMP64").is_some() {
7906 eprintln!(
7907 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
7908 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
7909 angle_y={angle_delta_y}"
7910 );
7911 }
7912 let modes = RectStripModes {
7913 skip,
7914 mode,
7915 angle_delta_y,
7916 uv_predict_mode,
7917 angle_delta_uv,
7918 alpha,
7919 filter_intra,
7920 smooth_neighbor,
7921 smooth_neighbor_uv,
7922 palette_y: palette_y
7923 .as_ref()
7924 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
7925 palette_uv: palette_uv.as_ref().map(|p| {
7926 (
7927 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
7928 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
7929 )
7930 }),
7931 };
7932 if palette_y.is_some() || palette_uv.is_some() {
7933 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
7934 }
7935 decode_rect_split(
7936 dec,
7937 cdfs,
7938 neighbours,
7939 (mi_r, mi_c),
7940 bw,
7941 bh,
7942 tx_w,
7943 tx_h,
7944 &modes,
7945 y,
7946 u,
7947 v,
7948 base_q_idx,
7949 reduced_tx_set,
7950 )?;
7951 // This early return skips this fn's own tail, so the palette
7952 // neighbour state has to be stamped HERE too: without it a split-tx
7953 // strip left the above/left palette arrays holding a DEAD block's
7954 // colours, and the next block's colour cache
7955 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
7956 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
7957 // and only those pixels were wrong (lane-palette2 r10).
7958 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
7959 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
7960 let (puv_size, puv_colors) =
7961 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
7962 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
7963 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
7964 return Ok(());
7965 }
7966 let (tx_w, tx_h) = (bw, bh);
7967 let (cpx, cpy) = (px / 2, py / 2);
7968 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
7969 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
7970 if std::env::var_os("EC_AV1_TRACE").is_some() {
7971 let (rng, _) = dec.debug_state();
7972 eprintln!(
7973 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
7974 skip={} tx={depth} rng={rng}",
7975 skip as i32
7976 );
7977 }
7978 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
7979 // block's prediction is the reconstructed colour-index map, set fresh
7980 // right before each `reconstruct_rect` call below (lane-palette2 r4).
7981 if let Some(ref pyv) = palette_y {
7982 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
7983 set_palette_pred(buf);
7984 }
7985 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
7986 (
7987 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
7988 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
7989 )
7990 });
7991 if skip {
7992 y.reconstruct_rect(
7993 px,
7994 py,
7995 bw,
7996 bh,
7997 mode,
7998 angle_delta_y,
7999 reach,
8000 &vec![0i32; bw * bh],
8001 None,
8002 filter_intra,
8003 smooth_neighbor,
8004 );
8005 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
8006 if let Some((ub, _)) = &palette_uv_bufs {
8007 set_palette_pred(ub.clone());
8008 }
8009 u.reconstruct_rect(
8010 cpx,
8011 cpy,
8012 chroma_w,
8013 chroma_h,
8014 uv_predict_mode,
8015 angle_delta_uv,
8016 reach,
8017 &vec![0i32; chroma_w * chroma_h],
8018 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8019 None,
8020 smooth_neighbor_uv,
8021 );
8022 if let Some((_, vb)) = &palette_uv_bufs {
8023 set_palette_pred(vb.clone());
8024 }
8025 v.reconstruct_rect(
8026 cpx,
8027 cpy,
8028 chroma_w,
8029 chroma_h,
8030 uv_predict_mode,
8031 angle_delta_uv,
8032 reach,
8033 &vec![0i32; chroma_w * chroma_h],
8034 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8035 None,
8036 smooth_neighbor_uv,
8037 );
8038 neighbours.record_rect(
8039 at,
8040 bw,
8041 bh,
8042 mode,
8043 uv_predict_mode,
8044 &[
8045 vec![0i32; bw * bh],
8046 vec![0i32; chroma_w * chroma_h],
8047 vec![0i32; chroma_w * chroma_h],
8048 ],
8049 );
8050 } else {
8051 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
8052 // reduces both size pairs to their square-up CDF sets
8053 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
8054 // doc comments); the scan order and 2D context tables are the real
8055 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
8056 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 32 {
8057 (&SCAN_32X16, &SCAN_16X8)
8058 } else {
8059 (&SCAN_16X32, &SCAN_8X16)
8060 };
8061 // lane-rectwire r3: real coefficients desync a pixel-exact gate
8062 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
8063 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
8064 // pixel (not a subtle context-table off-by-one), while the sibling
8065 // non-rect quadrants of the same frame match. Range-ladder bisection
8066 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
8067 // but the intra key-frame path has no traced symbol between the
8068 // partition read and the first coefficient block (mode/skip/tx_depth
8069 // reads are all untraced in libaom's decodeframe.c intra path, unlike
8070 // the inter EC_TRACE_MODE this round added), so a same-length range
8071 // comparison wasn't reachable within budget -- see
8072 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
8073 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
8074 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
8075 // libaom and match). lane-rectwire r4: range-ladder against the
8076 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
8077 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
8078 // both confirmed in sync -- rng=58692 on both sides right after
8079 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
8080 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
8081 // immediately after: ours moves rng 58692 -> 43570, which cannot be
8082 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
8083 // its own tx_size read) unless oracle's tx symbol is a near-certainty
8084 // CDF that barely narrows the range -- i.e. this decoder's
8085 // `tx_size_context_rect` ctx or `cdfs.tx_size_cat2` CDF selection for
8086 // a 32x16/16x32 strip is the first diverging symbol, not the
8087 // coefficient-context math r3 already cleared. Not confirmed byte-
8088 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
8089 // `read_tx_size`'s own rng, not attempted this round -- budget), so
8090 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
8091 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
8092 // it unconditionally where both square paths gate on `tx_select`. With
8093 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
8094 // decoder consumed one that was never there.
8095 {
8096 let around = neighbours.around_rect(at, bw, bh);
8097 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
8098 let (luma_levels, luma_tx_type) = read_coeffs_rect(
8099 dec,
8100 &mut luma_coding,
8101 luma_scan,
8102 bw,
8103 bh,
8104 0,
8105 dc_sign_ctx(around[0].2),
8106 TxType::DctDct,
8107 )?;
8108 if std::env::var_os("EC_AV1_TRACE").is_some() {
8109 let (rng, _) = dec.debug_state();
8110 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
8111 }
8112 let luma_residual = dequant_and_inverse_typed_wh(
8113 &luma_levels,
8114 bw,
8115 bh,
8116 crate::decode::bit_depth(),
8117 block_q_idx(),
8118 plane_q_delta(0).0,
8119 plane_q_delta(0).1,
8120 luma_tx_type,
8121 );
8122 y.reconstruct_rect(
8123 px,
8124 py,
8125 bw,
8126 bh,
8127 mode,
8128 angle_delta_y,
8129 reach,
8130 &luma_residual,
8131 None,
8132 filter_intra,
8133 smooth_neighbor,
8134 );
8135 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
8136 if let Some((ub, _)) = &palette_uv_bufs {
8137 set_palette_pred(ub.clone());
8138 }
8139 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
8140 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
8141 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
8142 let (u_levels, u_tx_type) = read_coeffs_rect(
8143 dec,
8144 &mut u_coding,
8145 chroma_scan,
8146 chroma_w,
8147 chroma_h,
8148 u_skip_ctx,
8149 dc_sign_ctx(around[1].2),
8150 u_default_tx,
8151 )?;
8152 if std::env::var_os("EC_AV1_TRACE").is_some() {
8153 let (rng, _) = dec.debug_state();
8154 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
8155 }
8156 let u_residual = dequant_and_inverse_typed_wh(
8157 &u_levels,
8158 chroma_w,
8159 chroma_h,
8160 crate::decode::bit_depth(),
8161 block_q_idx(),
8162 plane_q_delta(1).0,
8163 plane_q_delta(1).1,
8164 u_tx_type,
8165 );
8166 u.reconstruct_rect(
8167 cpx,
8168 cpy,
8169 chroma_w,
8170 chroma_h,
8171 uv_predict_mode,
8172 angle_delta_uv,
8173 reach,
8174 &u_residual,
8175 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8176 None,
8177 smooth_neighbor_uv,
8178 );
8179 if let Some((_, vb)) = &palette_uv_bufs {
8180 set_palette_pred(vb.clone());
8181 }
8182 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
8183 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
8184 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
8185 let (v_levels, v_tx_type) = read_coeffs_rect(
8186 dec,
8187 &mut v_coding,
8188 chroma_scan,
8189 chroma_w,
8190 chroma_h,
8191 v_skip_ctx,
8192 dc_sign_ctx(around[2].2),
8193 v_default_tx,
8194 )?;
8195 if std::env::var_os("EC_AV1_TRACE").is_some() {
8196 let (rng, _) = dec.debug_state();
8197 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
8198 }
8199 let v_residual = dequant_and_inverse_typed_wh(
8200 &v_levels,
8201 chroma_w,
8202 chroma_h,
8203 crate::decode::bit_depth(),
8204 block_q_idx(),
8205 plane_q_delta(2).0,
8206 plane_q_delta(2).1,
8207 v_tx_type,
8208 );
8209 v.reconstruct_rect(
8210 cpx,
8211 cpy,
8212 chroma_w,
8213 chroma_h,
8214 uv_predict_mode,
8215 angle_delta_uv,
8216 reach,
8217 &v_residual,
8218 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8219 None,
8220 smooth_neighbor_uv,
8221 );
8222 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
8223 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
8224 }
8225 }
8226 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
8227 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
8228 let (puv_size, puv_colors) =
8229 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
8230 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
8231 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
8232 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
8233 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
8234 if std::env::var_os("EC_AV1_TRACE").is_some() {
8235 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
8236 }
8237 Ok(())
8238}
8239
8240/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
8241/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
8242/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
8243/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
8244/// the second strip of a HORZ/VERT split sits offset by half the 16x16
8245/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
8246/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
8247/// previous strip is directly above (same column, `mi_h` rows up) or
8248/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
8249/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
8250/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
8251/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
8252/// this strip's real position, never the coarse `record_rect` (which the
8253/// caller uses once, after both strips, exactly like the `VERT_B` arm next
8254/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
8255/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
8256/// chroma half (`TxbSet::ChromaRect8x4`), the two size classes one level
8257/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
8258#[allow(clippy::too_many_arguments)]
8259fn decode_leaf_rect(
8260 dec: &mut SymbolDecoder,
8261 cdfs: &mut Cdfs,
8262 neighbours: &mut Neighbours,
8263 outer_at: (usize, usize),
8264 leaf_mi: (usize, usize),
8265 bw: usize,
8266 bh: usize,
8267 prev_leaf: Option<((usize, usize), usize)>,
8268 y: &mut PlaneBuf,
8269 u: &mut PlaneBuf,
8270 v: &mut PlaneBuf,
8271 enable_filter_intra: bool,
8272 allow_screen_content_tools: bool,
8273 base_q_idx: u8,
8274 tx_select: bool,
8275 reduced_tx_set: bool,
8276) -> Result<usize> {
8277 let _ = base_q_idx;
8278 if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() {
8279 eprintln!(
8280 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
8281 dec.debug_state().0
8282 );
8283 }
8284 let (r, c) = outer_at;
8285 let mut above_mode = neighbours.above_mode[c];
8286 let mut left_mode = neighbours.left_mode[r];
8287 let (mi_w, mi_h) = (bw / MI, bh / MI);
8288 if let Some(((pr, pc), pmode)) = prev_leaf {
8289 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
8290 above_mode = pmode;
8291 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
8292 left_mode = pmode;
8293 }
8294 }
8295 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
8296 // cannot hold the modes a split (or a pair of strips) leaves behind, so
8297 // when the map holds the block at exactly this strip's above/left mi it
8298 // is the neighbour libaom's `above_mi`/`left_mi` reads.
8299 // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND
8300 // availability-correct -- four 16x8 strips share one coarse 16x16
8301 // `left_mode` cell too, so the fallback must not stand in for an absent
8302 // tile-edge neighbour.
8303 let (above_mode, left_mode) =
8304 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
8305 let smooth_neighbor =
8306 is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
8307 if smooth_neighbor {
8308 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
8309 }
8310 // The palette-Y mode CDF row is picked by the neighbours' palette use
8311 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
8312 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
8313 // a palette narrows the wrong interval and desyncs the tile even when the
8314 // decoded bit is the same. The cell is the 16px-SUB cell containing the
8315 // leaf (the palette neighbour arrays have no finer granularity).
8316 // lane-kf900 r6: the leaf's REAL mi position -- the second leaf of a 16x8
8317 // pair sits 8 px into the 16px cell, and both the cache's superblock-top-row
8318 // exclusion and the neighbour palette lookup itself are mi-granular
8319 // (see [`Neighbours::palette_ctx_and_cache_mi`]).
8320 let pal_at = leaf_mi;
8321 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
8322 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
8323 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
8324 read_intra_mode_rect(
8325 dec,
8326 cdfs,
8327 above_mode,
8328 left_mode,
8329 true,
8330 true,
8331 bw,
8332 bh,
8333 enable_filter_intra,
8334 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
8335 allow_screen_content_tools,
8336 Some((palette_ctx, &palette_cache)),
8337 &palette_uv_cache,
8338 leaf_mi.0,
8339 leaf_mi.1,
8340 )?;
8341 // lane-kf900 r4: palette prediction on this shape, the same colour-index
8342 // map -> base colours buffer [`decode_block_rect`] hands each
8343 // `reconstruct_rect` through [`set_palette_pred`].
8344 if palette_y.is_some() || palette_uv.is_some() {
8345 RECT4_PALETTE_HITS.with(|c| c.set(c.get() + 1));
8346 }
8347 let palette_y_buf: Option<Vec<u16>> = palette_y
8348 .as_ref()
8349 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
8350 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
8351 (
8352 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
8353 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
8354 )
8355 });
8356 let (pal_y_size, pal_y_colors) =
8357 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
8358 let (pal_uv_size, pal_uv_colors) =
8359 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
8360 if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() {
8361 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
8362 }
8363 if filter_intra.is_some() {
8364 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
8365 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
8366 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
8367 // below already makes; this refusal was square-only prose.
8368 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
8369 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.set(c.get() + 1));
8370 }
8371 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
8372 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
8373 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
8374 // a constant `false`.
8375 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
8376 let depth = if tx_select {
8377 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read
8378 // every other rect reader now does -- a no-op on a key frame.
8379 let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {
8380 tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh)
8381 } else {
8382 tx_size_context_rect(neighbours, leaf_mi, bw, bh)
8383 };
8384 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
8385 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
8386 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
8387 // count (3), different CDF row: a wrong-table read of a real symbol,
8388 // the class that cost lane-rectsplit r1 its 64x32 depth.
8389 // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's
8390 // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and
8391 // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this
8392 // function also decodes) sit at depth 2, so they read
8393 // `tx_size_cdf[1]` -- the same table a 16x16 square block reads --
8394 // while `tx_size_cat2` belongs to the 32-level shapes
8395 // ([`decode_block_rect`]). Both tables carry three symbols, so the
8396 // wrong one decodes a plausible depth from the wrong probabilities:
8397 // the range diverges silently at the first such leaf and every later
8398 // symbol in the tile is read from the wrong place (class
8399 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
8400 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
8401 } else {
8402 0
8403 };
8404 if depth != 0 {
8405 // The same per-transform-unit walk the bigger strips take
8406 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
8407 // depth 2), addressed at this leaf's own mi position.
8408 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
8409 SUB16_SPLIT_HITS.with(|c| c.set(c.get() + 1));
8410 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
8411 let modes = RectStripModes {
8412 skip,
8413 mode,
8414 angle_delta_y,
8415 uv_predict_mode,
8416 angle_delta_uv,
8417 alpha,
8418 filter_intra,
8419 smooth_neighbor,
8420 // lane-rectsplitx r3: the split arm hard-coded `false` here while
8421 // the unsplit arm below passes the real neighbour answer -- chroma
8422 // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type.
8423 smooth_neighbor_uv,
8424 palette_y: palette_y_buf.clone(),
8425 palette_uv: palette_uv_bufs.clone(),
8426 };
8427 if palette_y.is_some() || palette_uv.is_some() {
8428 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
8429 }
8430 decode_rect_split(
8431 dec,
8432 cdfs,
8433 neighbours,
8434 leaf_mi,
8435 bw,
8436 bh,
8437 tx_w,
8438 tx_h,
8439 &modes,
8440 y,
8441 u,
8442 v,
8443 base_q_idx,
8444 reduced_tx_set,
8445 )?;
8446 record_strip_palette(
8447 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
8448 );
8449 return Ok(mode);
8450 }
8451 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
8452 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
8453 let (cpx, cpy) = (px / 2, py / 2);
8454 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
8455 let (luma_levels, u_levels, v_levels);
8456 if skip {
8457 luma_levels = vec![0i32; bw * bh];
8458 u_levels = vec![0i32; chroma_w * chroma_h];
8459 v_levels = vec![0i32; chroma_w * chroma_h];
8460 if let Some(b) = &palette_y_buf {
8461 set_palette_pred(b.clone());
8462 }
8463 y.reconstruct_rect(
8464 px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra,
8465 smooth_neighbor,
8466 );
8467 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
8468 if let Some((ub, _)) = &palette_uv_bufs {
8469 set_palette_pred(ub.clone());
8470 }
8471 u.reconstruct_rect(
8472 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels,
8473 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv,
8474 );
8475 if let Some((_, vb)) = &palette_uv_bufs {
8476 set_palette_pred(vb.clone());
8477 }
8478 v.reconstruct_rect(
8479 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels,
8480 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv,
8481 );
8482 } else {
8483 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
8484 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
8485 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
8486 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
8487 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
8488 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
8489 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 16 {
8490 (&SCAN_16X8, &SCAN_8X4)
8491 } else {
8492 (&SCAN_8X16, &SCAN_4X8)
8493 };
8494 let around = neighbours.around_mi_rect(leaf_mi, bw, bh);
8495 let luma_set = if reduced_tx_set {
8496 TxbSet::LumaRect16x8
8497 } else {
8498 TxbSet::LumaRect16x8Set1
8499 };
8500 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
8501 let (l_levels, luma_tx_type) = read_coeffs_rect(
8502 dec, &mut luma_coding, luma_scan, bw, bh, 0, dc_sign_ctx(around[0].2), TxType::DctDct,
8503 )?;
8504 if std::env::var_os("EC_AV1_RECTX_TRACE").is_some() {
8505 let nz: Vec<(usize, i32)> = l_levels.iter().copied().enumerate().filter(|(_, v)| *v != 0).collect();
8506 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
8507 }
8508 luma_levels = l_levels;
8509 let luma_residual = dequant_and_inverse_typed_wh(
8510 &luma_levels, bw, bh, crate::decode::bit_depth(),
8511 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(0).0, plane_q_delta(0).1, luma_tx_type,
8512 );
8513 if let Some(b) = &palette_y_buf {
8514 set_palette_pred(b.clone());
8515 }
8516 y.reconstruct_rect(
8517 px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra,
8518 smooth_neighbor,
8519 );
8520 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
8521 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
8522 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
8523 let mut u_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
8524 let (u_l, u_tx_type) = read_coeffs_rect(
8525 dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx,
8526 dc_sign_ctx(around[1].2), u_default_tx,
8527 )?;
8528 u_levels = u_l;
8529 let u_residual = dequant_and_inverse_typed_wh(
8530 &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(),
8531 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(1).0, plane_q_delta(1).1, u_tx_type,
8532 );
8533 if let Some((ub, _)) = &palette_uv_bufs {
8534 set_palette_pred(ub.clone());
8535 }
8536 u.reconstruct_rect(
8537 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual,
8538 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv,
8539 );
8540 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
8541 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
8542 let mut v_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
8543 let (v_l, v_tx_type) = read_coeffs_rect(
8544 dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx,
8545 dc_sign_ctx(around[2].2), v_default_tx,
8546 )?;
8547 v_levels = v_l;
8548 let v_residual = dequant_and_inverse_typed_wh(
8549 &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(),
8550 CURRENT_Q_IDX.with(|c| c.get()), plane_q_delta(2).0, plane_q_delta(2).1, v_tx_type,
8551 );
8552 if let Some((_, vb)) = &palette_uv_bufs {
8553 set_palette_pred(vb.clone());
8554 }
8555 v.reconstruct_rect(
8556 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual,
8557 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv,
8558 );
8559 RECT_LEAF_COEFF_HITS.with(|c| c.set(c.get() + 1));
8560 }
8561 neighbours.record_mi_rect(leaf_mi, bw, bh, &[luma_levels, u_levels, v_levels]);
8562 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
8563 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0);
8564 // The leaf's own palette state (`0` clears, as this site always did
8565 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT
8566 // AXIS only until the pair's closing leaf: the coarse cell holds one
8567 // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the
8568 // real left neighbour leaf 1 reads (lane-kf900 r4).
8569 record_strip_palette(
8570 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
8571 );
8572 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
8573 // rows -- record the whole span, not one cell.
8574 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
8575 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
8576 Ok(mode)
8577}
8578
8579/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
8580/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
8581/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
8582/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
8583/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
8584/// strip's mode so this one's mode context sees its true above/left
8585/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
8586///
8587/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
8588/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
8589/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
8590/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
8591/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
8592/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
8593/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
8594///
8595/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
8596/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
8597/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
8598/// unexamined.
8599#[allow(clippy::too_many_arguments)]
8600fn decode_block_rect4(
8601 dec: &mut SymbolDecoder,
8602 cdfs: &mut Cdfs,
8603 neighbours: &mut Neighbours,
8604 strip_mi: (usize, usize),
8605 bw: usize,
8606 bh: usize,
8607 prev_strip: Option<((usize, usize), usize)>,
8608 y: &mut PlaneBuf,
8609 u: &mut PlaneBuf,
8610 v: &mut PlaneBuf,
8611 enable_filter_intra: bool,
8612 allow_screen_content_tools: bool,
8613 base_q_idx: u8,
8614 tx_select: bool,
8615) -> Result<(usize, usize)> {
8616 let _ = base_q_idx;
8617 let (mi_r, mi_c) = strip_mi;
8618 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
8619 let (mi_w, mi_h) = (bw / MI, bh / MI);
8620 let mut above_mode = neighbours.above_mode[c];
8621 let mut left_mode = neighbours.left_mode[r];
8622 if let Some(((pr, pc), pmode)) = prev_strip {
8623 if pc == mi_c && mi_r == pr + mi_h {
8624 above_mode = pmode;
8625 } else if pr == mi_r && mi_c == pc + mi_w {
8626 left_mode = pmode;
8627 }
8628 }
8629 // lane-rectsplitx r2, ROOT CAUSE of the 1:4 mismatch: mi-exact +
8630 // availability-correct neighbour modes (see
8631 // [`Neighbours::modes_above_left_mi`]). The coarse 16x16 bands alias every
8632 // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell.
8633 let (above_mode, left_mode) =
8634 neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode));
8635 // lane-kf900 r4: this strip's own palette-Y mode ctx and colour cache.
8636 // Passing `None`/`&[]` read `palette_y_mode` off CDF row 0 and every
8637 // `palette_colors_y` cache hit off an EMPTY cache -- right symbol count,
8638 // wrong interval, so a screen-content tile desynced at the first strip
8639 // whose neighbour used a palette (class [[cdf-row-held-constant]]).
8640 let pal_at = (mi_r, mi_c);
8641 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
8642 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
8643 let (
8644 skip,
8645 mode,
8646 angle_delta_y,
8647 uv_mode,
8648 angle_delta_uv,
8649 alpha,
8650 filter_intra,
8651 palette_y,
8652 palette_uv,
8653 ) = read_intra_mode_rect(
8654 dec,
8655 cdfs,
8656 above_mode,
8657 left_mode,
8658 true,
8659 true,
8660 bw,
8661 bh,
8662 enable_filter_intra,
8663 neighbours.skip_txfm_ctx(mi_r, mi_c),
8664 allow_screen_content_tools,
8665 Some((palette_ctx, &palette_cache)),
8666 &palette_uv_cache,
8667 mi_r,
8668 mi_c,
8669 )?;
8670 // lane-kf900 r4: palette prediction on this shape, exactly as
8671 // [`decode_block_rect`] does one aspect ratio up -- the colour-index map
8672 // mapped through the base colours IS the prediction (it reads no edge
8673 // pixels), handed to each `reconstruct_rect` through [`set_palette_pred`].
8674 if palette_y.is_some() || palette_uv.is_some() {
8675 RECT4_PALETTE_HITS.with(|c| c.set(c.get() + 1));
8676 }
8677 let palette_y_buf: Option<Vec<u16>> = palette_y
8678 .as_ref()
8679 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
8680 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
8681 (
8682 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
8683 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
8684 )
8685 });
8686 let (pal_y_size, pal_y_colors) =
8687 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
8688 let (pal_uv_size, pal_uv_colors) =
8689 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
8690 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
8691 if smooth_neighbor {
8692 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
8693 }
8694 // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's
8695 // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so
8696 // `r * (SUB / MI)` names a different mi column and the chroma
8697 // edge-filter strength was read from the wrong neighbour (measured:
8698 // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch
8699 // with luma bit-exact).
8700 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
8701 if filter_intra.is_some() {
8702 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
8703 if bw > bh {
8704 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.set(c.get() + 1));
8705 } else {
8706 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.set(c.get() + 1));
8707 }
8708 }
8709 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
8710 DC_PRED
8711 } else {
8712 uv_mode
8713 };
8714 let depth = if tx_select {
8715 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
8716 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
8717 // the 16x4 intra-in-inter strips already do); the key frame's
8718 // deblock-grid approximation is only right where those bands were never
8719 // written. Measured on the 10-bit 1920x792 128-superblock stream,
8720 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
8721 // `tx_size_cat2` row 1 where libaom reads row 2.
8722 let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {
8723 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh)
8724 } else {
8725 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
8726 };
8727 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
8728 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
8729 eprintln!(
8730 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
8731 dec.debug_state().0
8732 );
8733 }
8734 d
8735 } else {
8736 0
8737 };
8738 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
8739 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
8740 publish_txfm_bands_if_in_inter(
8741 neighbours,
8742 (mi_r, mi_c),
8743 depth_to_tx_wh(bw, bh, depth),
8744 (bw, bh),
8745 );
8746 if depth != 0 {
8747 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
8748 // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a
8749 // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16
8750 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8;
8751 // both interleave in every real stream.
8752 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
8753 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
8754 // lane-rectsplitx r2: both depths ship together, as the r1 handoff
8755 // predicted -- depth 1 fires FIRST in every attempt that splits at
8756 // all, so a depth-2-only lift could never be gated. The r1 mismatch
8757 // was never the rect unit: it was the neighbour MODE the strip reads
8758 // (see `modes_above_left_mi`).
8759 let which = if depth == 1 {
8760 &RECT4_SPLIT_DEPTH1_HITS
8761 } else {
8762 &RECT4_SPLIT_DEPTH2_HITS
8763 };
8764 which.with(|c| c.set(c.get() + 1));
8765 let modes = RectStripModes {
8766 skip,
8767 mode,
8768 angle_delta_y,
8769 uv_predict_mode,
8770 angle_delta_uv,
8771 alpha,
8772 filter_intra,
8773 smooth_neighbor,
8774 smooth_neighbor_uv,
8775 palette_y: palette_y_buf.clone(),
8776 palette_uv: palette_uv_bufs.clone(),
8777 };
8778 if palette_y.is_some() || palette_uv.is_some() {
8779 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
8780 }
8781 decode_rect_split(
8782 dec,
8783 cdfs,
8784 neighbours,
8785 (mi_r, mi_c),
8786 bw,
8787 bh,
8788 tx_w,
8789 tx_h,
8790 &modes,
8791 y,
8792 u,
8793 v,
8794 base_q_idx,
8795 false,
8796 )?;
8797 record_strip_palette(
8798 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
8799 pal_uv_colors,
8800 );
8801 if bw > bh {
8802 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
8803 } else {
8804 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
8805 }
8806 if !skip {
8807 RECT4_COEFF_HITS.with(|c| c.set(c.get() + 1));
8808 }
8809 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
8810 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
8811 // frame, so this 1:4 strip -- which is also the INTER frame's reader
8812 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
8813 // transform size in both TXFM_CONTEXT bands. Without it the next block
8814 // reads the row's stale value.
8815 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
8816 return Ok((mode, uv_predict_mode));
8817 }
8818 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
8819 // that is 8 px tall, so each strip stamps every cell it touches and the
8820 // LAST strip wins -- which is the right answer for the block below/right
8821 // of the 32x32, the only reader outside it. Written after this strip's
8822 // own context read above, never before.
8823 for cell in 0..bw.div_ceil(SUB) {
8824 neighbours.above_mode[c + cell] = mode;
8825 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
8826 neighbours.above_side[c + cell] = bw;
8827 }
8828 for cell in 0..bh.div_ceil(SUB) {
8829 neighbours.left_mode[r + cell] = mode;
8830 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
8831 neighbours.left_side[r + cell] = bh;
8832 }
8833 // ...and the mi-EXACT maps the coarse cells alias away, exactly as
8834 // [`decode_leaf_rect`] does (the split arm above records these through
8835 // `record_mi_luma_rect`). Without this an unsplit 32x8 strip left
8836 // `sub8_mode_row` holding the previous block, and the next 32x32's
8837 // strips read a stale `kf_y_mode` row (measured: mi(4,8) on the band
8838 // fixture).
8839 neighbours.record_mode_mi(mi_r, mi_c, mi_w, mi_h, mode);
8840 neighbours.record_uv_mode_mi(mi_r, mi_c, mi_w, mi_h, uv_predict_mode);
8841 let (px, py) = (mi_c * MI, mi_r * MI);
8842 let (cpx, cpy) = (px / 2, py / 2);
8843 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
8844 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
8845 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw > bh {
8846 (&SCAN_32X8, &SCAN_16X4)
8847 } else {
8848 (&SCAN_8X32, &SCAN_4X16)
8849 };
8850 let (luma_levels, u_levels, v_levels) = if skip {
8851 (
8852 vec![0i32; bw * bh],
8853 vec![0i32; chroma_w * chroma_h],
8854 vec![0i32; chroma_w * chroma_h],
8855 )
8856 } else {
8857 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
8858 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
8859 let (luma_levels, luma_tx_type) = read_coeffs_rect(
8860 dec,
8861 &mut luma_coding,
8862 luma_scan,
8863 bw,
8864 bh,
8865 0,
8866 dc_sign_ctx(around[0].2),
8867 TxType::DctDct,
8868 )?;
8869 let mut planes = Vec::with_capacity(2);
8870 for plane in 1..3 {
8871 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
8872 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
8873 let mut coding = cdfs.txb(TxbSet::Chroma8, uv_predict_mode);
8874 let (levels, tx_type) = read_coeffs_rect(
8875 dec,
8876 &mut coding,
8877 chroma_scan,
8878 chroma_w,
8879 chroma_h,
8880 skip_ctx,
8881 dc_sign_ctx(around[plane].2),
8882 default_tx,
8883 )?;
8884 planes.push((levels, tx_type));
8885 }
8886 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
8887 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
8888 RECT4_COEFF_HITS.with(|c| c.set(c.get() + 1));
8889 let luma_residual = dequant_and_inverse_typed_wh(
8890 &luma_levels,
8891 bw,
8892 bh,
8893 crate::decode::bit_depth(),
8894 block_q_idx(),
8895 plane_q_delta(0).0,
8896 plane_q_delta(0).1,
8897 luma_tx_type,
8898 );
8899 if let Some(b) = &palette_y_buf {
8900 set_palette_pred(b.clone());
8901 }
8902 y.reconstruct_rect(
8903 px,
8904 py,
8905 bw,
8906 bh,
8907 mode,
8908 angle_delta_y,
8909 reach,
8910 &luma_residual,
8911 None,
8912 filter_intra,
8913 smooth_neighbor,
8914 );
8915 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
8916 for (plane, buf, levels, tx_type) in [
8917 (1usize, &mut *u, &u_levels, u_tx_type),
8918 (2, &mut *v, &v_levels, v_tx_type),
8919 ] {
8920 let residual = dequant_and_inverse_typed_wh(
8921 levels,
8922 chroma_w,
8923 chroma_h,
8924 crate::decode::bit_depth(),
8925 block_q_idx(),
8926 plane_q_delta(plane).0,
8927 plane_q_delta(plane).1,
8928 tx_type,
8929 );
8930 if let Some((ub, vb)) = &palette_uv_bufs {
8931 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() });
8932 }
8933 buf.reconstruct_rect(
8934 cpx,
8935 cpy,
8936 chroma_w,
8937 chroma_h,
8938 uv_predict_mode,
8939 angle_delta_uv,
8940 reach,
8941 &residual,
8942 alpha
8943 .zip(ac.as_deref())
8944 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
8945 None,
8946 smooth_neighbor_uv,
8947 );
8948 }
8949 neighbours.record_mi_rect(
8950 (mi_r, mi_c),
8951 bw,
8952 bh,
8953 &[luma_levels, u_levels, v_levels],
8954 );
8955 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
8956 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0);
8957 record_strip_palette(
8958 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
8959 pal_uv_colors,
8960 );
8961 if bw > bh {
8962 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
8963 } else {
8964 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
8965 }
8966 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
8967 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
8968 // frame, so this 1:4 strip -- which is also the INTER frame's reader
8969 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
8970 // transform size in both TXFM_CONTEXT bands. Without it the next block
8971 // reads the row's stale value.
8972 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
8973 return Ok((mode, uv_predict_mode));
8974 };
8975 if let Some(b) = &palette_y_buf {
8976 set_palette_pred(b.clone());
8977 }
8978 y.reconstruct_rect(
8979 px,
8980 py,
8981 bw,
8982 bh,
8983 mode,
8984 angle_delta_y,
8985 reach,
8986 &luma_levels,
8987 None,
8988 filter_intra,
8989 smooth_neighbor,
8990 );
8991 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
8992 if let Some((ub, _)) = &palette_uv_bufs {
8993 set_palette_pred(ub.clone());
8994 }
8995 u.reconstruct_rect(
8996 cpx,
8997 cpy,
8998 chroma_w,
8999 chroma_h,
9000 uv_predict_mode,
9001 angle_delta_uv,
9002 reach,
9003 &u_levels,
9004 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
9005 None,
9006 smooth_neighbor_uv,
9007 );
9008 if let Some((_, vb)) = &palette_uv_bufs {
9009 set_palette_pred(vb.clone());
9010 }
9011 v.reconstruct_rect(
9012 cpx,
9013 cpy,
9014 chroma_w,
9015 chroma_h,
9016 uv_predict_mode,
9017 angle_delta_uv,
9018 reach,
9019 &v_levels,
9020 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
9021 None,
9022 smooth_neighbor_uv,
9023 );
9024 neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[luma_levels.to_vec(), u_levels, v_levels]);
9025 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
9026 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0);
9027 record_strip_palette(
9028 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
9029 );
9030 if bw > bh {
9031 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
9032 } else {
9033 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
9034 }
9035 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
9036 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
9037 // frame, so this 1:4 strip -- which is also the INTER frame's reader
9038 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
9039 // transform size in both TXFM_CONTEXT bands. Without it the next block
9040 // reads the row's stale value.
9041 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
9042 Ok((mode, uv_predict_mode))
9043}
9044
9045/// Decodes the four 16x4 / 4x16 strips of a 16x16-level `PARTITION_HORZ_4` /
9046/// `PARTITION_VERT_4` (lane-r14) -- [`decode_block_rect4`]'s pair one level
9047/// down, and the first shape here whose luma block is a single mi row (or
9048/// column).
9049///
9050/// What is new at this size is CHROMA. `is_chroma_reference`
9051/// (`av1_common_int.h`) is false for a 4:2:0 block one mi tall (wide) on an
9052/// EVEN mi row (column), so strips 0 and 2 read no `uv_mode`/`cfl_alpha`/
9053/// `angle_delta_uv` at all and code no chroma residual; strips 1 and 3 close
9054/// the pair and carry the chroma of the whole 16x8 (8x16) luma pair --
9055/// `setup_pred_plane`'s own `if (subsampling_y && (mi_row & 1) &&
9056/// mi_size_high[bsize] == 1) mi_row -= 1` offset, i.e. an 8x4 (4x8) chroma
9057/// transform at the PAIR's origin, with CfL averaging over the pair's luma.
9058///
9059/// Tables: LUMA `TX_16X4`/`TX_4X16` averages to the 8x8 entropy context
9060/// ((0 + 2 + 1) >> 1 = 1) with 64 coded positions, so its CDF set is
9061/// [`TxbSet::LumaRect16x4`] (`Luma8`'s tables, the `TX_4X4` `tx_type` row);
9062/// scans are [`SCAN_16X4`]/[`SCAN_4X16`]. CHROMA `TX_8X4`/`TX_4X8` is
9063/// [`TxbSet::ChromaRect8x4`] with [`SCAN_8X4`]/[`SCAN_4X8`]. Angle deltas ARE
9064/// coded (`av1_use_angle_delta` compares the BLOCK_SIZES_ALL enum index, and
9065/// BLOCK_16X4 is 17), and so is `use_filter_intra` (both sides <= 32) off this
9066/// shape's own CDF row.
9067///
9068/// A split transform (`tx_depth != 0`, `sub_tx_size_map[TX_16X4] == TX_8X4`)
9069/// refuses by name rather than guess-decode.
9070#[allow(clippy::too_many_arguments)]
9071fn decode_rect4_16(
9072 dec: &mut SymbolDecoder,
9073 cdfs: &mut Cdfs,
9074 neighbours: &mut Neighbours,
9075 at16: (usize, usize),
9076 horz: bool,
9077 y: &mut PlaneBuf,
9078 u: &mut PlaneBuf,
9079 v: &mut PlaneBuf,
9080 enable_filter_intra: bool,
9081 allow_screen_content_tools: bool,
9082 base_q_idx: u8,
9083 tx_select: bool,
9084 reduced_tx_set: bool,
9085) -> Result<()> {
9086 let (r, c) = at16;
9087 let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI));
9088 let (bw, bh) = if horz { (16, 4) } else { (4, 16) };
9089 let (mi_w, mi_h) = (bw / MI, bh / MI);
9090 let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
9091 let chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
9092 let mut prev: Option<((usize, usize), usize)> = None;
9093 let mut last_mode = DC_PRED;
9094 let mut last_uv_mode = DC_PRED;
9095 for i in 0..4usize {
9096 let lmi = if horz {
9097 (mi_row0 + i, mi_col0)
9098 } else {
9099 (mi_row0, mi_col0 + i)
9100 };
9101 let has_chroma = i % 2 == 1;
9102 let (mode, uv, _tx) = decode_rect4_16_strip(
9103 dec,
9104 cdfs,
9105 neighbours,
9106 lmi,
9107 horz,
9108 has_chroma,
9109 prev,
9110 y,
9111 u,
9112 v,
9113 enable_filter_intra,
9114 allow_screen_content_tools,
9115 base_q_idx,
9116 tx_select,
9117 reduced_tx_set,
9118 )?;
9119 if let Some(m) = uv {
9120 last_uv_mode = m;
9121 }
9122 last_mode = mode;
9123 prev = Some((lmi, mode));
9124 }
9125 // The coarse 16-px cell holds one entry for the whole 16x16: the last
9126 // strip is what a block below (right) sees through it, the mi-exact maps
9127 // above answering everything finer.
9128 neighbours.above_mode[c] = last_mode;
9129 neighbours.left_mode[r] = last_mode;
9130 neighbours.above_uv_mode[c] = last_uv_mode;
9131 neighbours.left_uv_mode[r] = last_uv_mode;
9132 neighbours.above_side[c] = bw;
9133 neighbours.left_side[r] = bh;
9134 Ok(())
9135}
9136
9137/// One 16x4 / 4x16 strip of a 16x16-level 1:4 partition, intra-coded --
9138/// [`decode_rect4_16`]'s per-strip body, lifted (lane-intra16x4) so the INTER
9139/// block path can decode a SINGLE intra strip of a partition whose other
9140/// strips are inter. `prev` is the previous strip's `(mi, mode)` (the
9141/// key-frame caller's coarse-cell stand-in; `None` on the inter path, where
9142/// every strip publishes its own mi-exact mode). Returns
9143/// `(y_mode, uv_predict_mode when this strip closes the 4:2:0 chroma pair)`.
9144#[allow(clippy::too_many_arguments)]
9145fn decode_rect4_16_strip(
9146 dec: &mut SymbolDecoder,
9147 cdfs: &mut Cdfs,
9148 neighbours: &mut Neighbours,
9149 lmi: (usize, usize),
9150 horz: bool,
9151 has_chroma: bool,
9152 prev: Option<((usize, usize), usize)>,
9153 y: &mut PlaneBuf,
9154 u: &mut PlaneBuf,
9155 v: &mut PlaneBuf,
9156 enable_filter_intra: bool,
9157 allow_screen_content_tools: bool,
9158 base_q_idx: u8,
9159 tx_select: bool,
9160 reduced_tx_set: bool,
9161) -> Result<(usize, Option<usize>, (usize, usize))> {
9162 let (r, c) = (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI));
9163 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
9164 let (mi_w, mi_h) = (bw / MI, bh / MI);
9165 let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
9166 let chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
9167 let mut last_uv_mode: Option<usize> = None;
9168 // `decode_block_rect4`'s own neighbour rule: the coarse 16-px cell
9169 // aliases all four strips onto one entry, so the mi-exact map wins and
9170 // the previous strip stands in on the split axis.
9171 let mut above_mode = neighbours.above_mode[c];
9172 let mut left_mode = neighbours.left_mode[r];
9173 if let Some(((pr, pc), pmode)) = prev {
9174 if pc == lmi.1 && lmi.0 == pr + mi_h {
9175 above_mode = pmode;
9176 } else if pr == lmi.0 && lmi.1 == pc + mi_w {
9177 left_mode = pmode;
9178 }
9179 }
9180 let (above_mode, left_mode) =
9181 neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode));
9182 // lane-kf900 r4: the strip's real palette ctx + colour cache (see
9183 // [`decode_block_rect4`]); `None`/`&[]` here read `palette_y_mode`
9184 // off CDF row 0 and every cache hit off an empty cache.
9185 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(lmi);
9186 let palette_uv_cache = neighbours.palette_uv_cache_mi(lmi);
9187 let (
9188 skip,
9189 mode,
9190 angle_delta_y,
9191 uv_mode,
9192 angle_delta_uv,
9193 alpha,
9194 filter_intra,
9195 palette_y,
9196 palette_uv,
9197 ) = read_intra_mode_rect(
9198 dec,
9199 cdfs,
9200 above_mode,
9201 left_mode,
9202 true,
9203 has_chroma,
9204 bw,
9205 bh,
9206 enable_filter_intra,
9207 neighbours.skip_txfm_ctx(lmi.0, lmi.1),
9208 allow_screen_content_tools,
9209 Some((palette_ctx, &palette_cache)),
9210 &palette_uv_cache,
9211 lmi.0,
9212 lmi.1,
9213 )?;
9214 if palette_y.is_some() || palette_uv.is_some() {
9215 RECT4_PALETTE_HITS.with(|h| h.set(h.get() + 1));
9216 }
9217 // The colour-index map through the base colours IS the prediction.
9218 // Chroma's map is the PAIR's 8x4 (4x8) block, matching the one
9219 // chroma transform this closing strip codes.
9220 let palette_y_buf: Option<Vec<u16>> = palette_y
9221 .as_ref()
9222 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
9223 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
9224 (
9225 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
9226 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
9227 )
9228 });
9229 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
9230 if smooth_neighbor {
9231 SMOOTH_LUMA_HITS.with(|h| h.set(h.get() + 1));
9232 }
9233 if filter_intra.is_some() {
9234 FILTER_INTRA_RECT_HITS.with(|h| h.set(h.get() + 1));
9235 }
9236 // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is
9237 // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the
9238 // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol
9239 // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does.
9240 let depth = if tx_select {
9241 // lane-intra16x4: on an INTER frame `get_tx_size_context` reads the
9242 // real `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what
9243 // the 2:1 intra-in-inter strip already does); the key frame's
9244 // deblock-grid approximation is only right where those bands were
9245 // never written.
9246 let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {
9247 tx_size_context_txfm_rect(neighbours, lmi, bw, bh)
9248 } else {
9249 tx_size_context_rect(neighbours, lmi, bw, bh)
9250 };
9251 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
9252 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
9253 eprintln!(
9254 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
9255 lmi.0,
9256 lmi.1,
9257 dec.debug_state().0
9258 );
9259 }
9260 d
9261 } else {
9262 0
9263 };
9264 if depth != 0 {
9265 TX_DEPTH_HITS.with(|h| h.set(h.get() + 1));
9266 RECT4_16_SPLIT_HITS.with(|h| h.set(h.get() + 1));
9267 }
9268 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
9269 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
9270 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
9271 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode);
9272 if depth != 0 {
9273 // [`decode_rect_split`]'s per-unit walk, inlined because the
9274 // CHROMA of this shape belongs to the strip's 4:2:0 pair, not to
9275 // the strip (that function codes one chroma transform per block).
9276 // depth 1 is the 2:1 rect unit TX_8X4/TX_4X8
9277 // (`sub_tx_size_map[TX_16X4]`), depth 2 the square TX_4X4; each
9278 // unit predicts off the units before it in raster order.
9279 let rect_unit = tx_w != tx_h;
9280 let zero_tu = vec![0i32; tx_w * tx_h];
9281 for tu_row in 0..bh / tx_h {
9282 for tu_col in 0..bw / tx_w {
9283 let tu_mi = (lmi.0 + tu_row * (tx_h / MI), lmi.1 + tu_col * (tx_w / MI));
9284 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
9285 let tu_reach = Reach::of_tu(
9286 bw,
9287 bh,
9288 tu_col * tx_w,
9289 tu_row * tx_h,
9290 tx_w,
9291 tx_h,
9292 reach,
9293 );
9294 if let Some(b) = &palette_y_buf {
9295 let tu_buf: Vec<u16> = (0..tx_h)
9296 .flat_map(|i| {
9297 let base = (tu_row * tx_h + i) * bw + tu_col * tx_w;
9298 b[base..base + tx_w].iter().copied()
9299 })
9300 .collect();
9301 set_palette_pred(tu_buf);
9302 }
9303 if skip {
9304 y.reconstruct_rect(
9305 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &zero_tu,
9306 None, filter_intra, smooth_neighbor,
9307 );
9308 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
9309 } else if rect_unit {
9310 // `get_txsize_entropy_ctx(TX_8X4)` is the 8x8 class with
9311 // 32 coded positions and the `TX_4X4` `tx_type` row:
9312 // exactly [`TxbSet::LumaRect4x8`].
9313 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
9314 let tu_skip_ctx =
9315 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI);
9316 let set = if reduced_tx_set {
9317 TxbSet::LumaRect4x8
9318 } else {
9319 TxbSet::LumaRect4x8Set1
9320 };
9321 let tu_scan: &[u16] = if tx_w > tx_h { &SCAN_8X4 } else { &SCAN_4X8 };
9322 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
9323 let (tu_grid, tu_tx_type) = read_coeffs_rect(
9324 dec,
9325 &mut coding,
9326 tu_scan,
9327 tx_w,
9328 tx_h,
9329 tu_skip_ctx,
9330 dc_sign_ctx(tu_around.2),
9331 TxType::DctDct,
9332 )?;
9333 let residual = dequant_and_inverse_typed_wh(
9334 &tu_grid,
9335 tx_w,
9336 tx_h,
9337 crate::decode::bit_depth(),
9338 block_q_idx(),
9339 plane_q_delta(0).0,
9340 plane_q_delta(0).1,
9341 tu_tx_type,
9342 );
9343 y.reconstruct_rect(
9344 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &residual,
9345 None, filter_intra, smooth_neighbor,
9346 );
9347 if tu_grid.iter().any(|&l| l != 0) {
9348 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));
9349 }
9350 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
9351 } else {
9352 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
9353 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
9354 let tu_grid = read_plane(
9355 dec,
9356 cdfs,
9357 txbset_for(tx_w, reduced_tx_set),
9358 &default_scan(tx_w),
9359 0,
9360 tu_around,
9361 mode,
9362 mode,
9363 angle_delta_y,
9364 tu_reach,
9365 y,
9366 tu_px,
9367 tu_py,
9368 tx_w,
9369 tx_w,
9370 base_q_idx,
9371 None,
9372 filter_intra,
9373 Some(tu_skip_ctx),
9374 smooth_neighbor,
9375 )?;
9376 if tu_grid.iter().any(|&l| l != 0) {
9377 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));
9378 }
9379 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
9380 }
9381 }
9382 }
9383 } else {
9384 let levels = if skip {
9385 let zeros = vec![0i32; bw * bh];
9386 if let Some(b) = &palette_y_buf {
9387 set_palette_pred(b.clone());
9388 }
9389 y.reconstruct_rect(
9390 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
9391 smooth_neighbor,
9392 );
9393 zeros
9394 } else {
9395 // The strip's luma TU *is* the strip (`plane_bsize ==
9396 // txsize_to_bsize[tx_size]`), so `get_txb_ctx` fixes
9397 // `txb_skip_ctx` at 0.
9398 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
9399 let set = if reduced_tx_set {
9400 TxbSet::LumaRect16x4
9401 } else {
9402 TxbSet::LumaRect16x4Set1
9403 };
9404 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
9405 let (levels, tx_type) = read_coeffs_rect(
9406 dec,
9407 &mut coding,
9408 scan,
9409 bw,
9410 bh,
9411 0,
9412 dc_sign_ctx(around.2),
9413 TxType::DctDct,
9414 )?;
9415 let residual = dequant_and_inverse_typed_wh(
9416 &levels,
9417 bw,
9418 bh,
9419 crate::decode::bit_depth(),
9420 block_q_idx(),
9421 plane_q_delta(0).0,
9422 plane_q_delta(0).1,
9423 tx_type,
9424 );
9425 if let Some(b) = &palette_y_buf {
9426 set_palette_pred(b.clone());
9427 }
9428 y.reconstruct_rect(
9429 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
9430 smooth_neighbor,
9431 );
9432 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));
9433 levels
9434 };
9435 neighbours.record_mi_luma_rect(lmi, bw, bh, &levels);
9436 }
9437 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
9438 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0);
9439 // `update_partition_context` writes `partition_context_lookup[
9440 // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on
9441 // the left (mirrored under VERT_4).
9442 for cell in 0..mi_w {
9443 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
9444 *slot = bw;
9445 }
9446 }
9447 for cell in 0..mi_h {
9448 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
9449 *slot = bh;
9450 }
9451 }
9452 if has_chroma {
9453 RECT4_16_CHROMA_HITS.with(|h| h.set(h.get() + 1));
9454 let pair_mi = if horz {
9455 (lmi.0 - 1, lmi.1)
9456 } else {
9457 (lmi.0, lmi.1 - 1)
9458 };
9459 let (pw, ph) = if horz { (16, 8) } else { (8, 16) };
9460 let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI);
9461 let (cpx, cpy) = (ppx / 2, ppy / 2);
9462 let (cw, ch) = (pw / 2, ph / 2);
9463 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
9464 if (V_PRED..=D67_PRED).contains(&uv_predict_mode) {
9465 RECT4_16_CHROMA_DIR_HITS.with(|h| h.set(h.get() + 1));
9466 }
9467 let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height);
9468 // lane-kf1200 r1: the chroma edge-filter type reads the neighbours
9469 // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s
9470 // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/
9471 // `chroma_left_mbmi` from `mi[-((mi_row & ss_y) * stride + (mi_col
9472 // & ss_x))]` (`set_mi_offsets`, av1/common/blockd.h ~1050), i.e.
9473 // the pair's top-left luma mi, never this leaf's odd row/column.
9474 // Reading `lmi` here named the leaf directly above (a non-chroma
9475 // -reference 4-row block, `uv_mode == UV_DC_PRED`) and so lost a
9476 // SMOOTH neighbour: filt_type 0 instead of 1 turned
9477 // `av1_use_intra_edge_upsample` on (blk_wh 12 <= 16) for a
9478 // directional chroma strip, moving 4 samples by 1.
9479 let smooth_neighbor_uv =
9480 neighbours.smooth_uv_neighbour(pair_mi.0, pair_mi.1, r, c);
9481 if smooth_neighbor_uv != neighbours.smooth_uv_neighbour_unsnapped(lmi.0, lmi.1, r, c)
9482 {
9483 RECT4_16_UV_PAIR_FILT_HITS.with(|h| h.set(h.get() + 1));
9484 }
9485 let (u_levels, v_levels) = if skip {
9486 let zeros = vec![0i32; cw * ch];
9487 // libaom `predict_and_reconstruct_intra_block` (decodeframe.c
9488 // ~1000) predicts EVERY plane and only guards the residual on
9489 // `mbmi->skip_txfm`, so a skipped `UV_CFL_PRED` block is still
9490 // DC + alpha * luma-AC. Dropping the CfL term here left a
9491 // chroma-only bounded box on ReelC's key frames.
9492 let ac = alpha.map(|_| cfl_ac_q3_rect(y, ppx, ppy, pw, ph));
9493 if alpha.is_some() {
9494 CHROMA_SKIP_CFL_HITS.with(|h| h.set(h.get() + 1));
9495 }
9496 for (buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] {
9497 if let Some((ub, vb)) = &palette_uv_bufs {
9498 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() });
9499 }
9500 buf.reconstruct_rect(
9501 cpx,
9502 cpy,
9503 cw,
9504 ch,
9505 uv_predict_mode,
9506 angle_delta_uv,
9507 pair_reach,
9508 &zeros,
9509 alpha
9510 .zip(ac.as_deref())
9511 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
9512 None,
9513 smooth_neighbor_uv,
9514 );
9515 }
9516 (zeros.clone(), zeros)
9517 } else {
9518 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
9519 let mut planes = Vec::with_capacity(2);
9520 for plane in 1..3 {
9521 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
9522 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
9523 let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
9524 let (levels, tx_type) = read_coeffs_rect(
9525 dec,
9526 &mut coding,
9527 chroma_scan,
9528 cw,
9529 ch,
9530 skip_ctx,
9531 dc_sign_ctx(around[plane].2),
9532 default_tx,
9533 )?;
9534 planes.push((levels, tx_type));
9535 }
9536 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
9537 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
9538 // CfL averages the luma of the WHOLE pair, the region this one
9539 // chroma transform covers.
9540 let ac = alpha.map(|_| cfl_ac_q3_rect(y, ppx, ppy, pw, ph));
9541 for (plane, buf, levels, tx_type) in [
9542 (1usize, &mut *u, &u_levels, u_tx_type),
9543 (2, &mut *v, &v_levels, v_tx_type),
9544 ] {
9545 let residual = dequant_and_inverse_typed_wh(
9546 levels,
9547 cw,
9548 ch,
9549 crate::decode::bit_depth(),
9550 block_q_idx(),
9551 plane_q_delta(plane).0,
9552 plane_q_delta(plane).1,
9553 tx_type,
9554 );
9555 if let Some((ub, vb)) = &palette_uv_bufs {
9556 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() });
9557 }
9558 buf.reconstruct_rect(
9559 cpx,
9560 cpy,
9561 cw,
9562 ch,
9563 uv_predict_mode,
9564 angle_delta_uv,
9565 pair_reach,
9566 &residual,
9567 alpha
9568 .zip(ac.as_deref())
9569 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
9570 None,
9571 smooth_neighbor_uv,
9572 );
9573 }
9574 (u_levels, v_levels)
9575 };
9576 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, uv_predict_mode);
9577 // The chroma planes' coefficient context, over the PAIR's mi span
9578 // (`decode_leaf_rect8`'s own rule: a subsampled plane's bound is
9579 // the luma one rounded up to its 4x4 unit).
9580 let u_state = neighbour_state(&u_levels);
9581 let v_state = neighbour_state(&v_levels);
9582 let round_up_even = |n: usize| n.div_ceil(2) * 2;
9583 let bound_h = round_up_even(neighbours.mi_rows);
9584 let bound_w = round_up_even(neighbours.mi_cols);
9585 for cell in 0..(ph / MI) {
9586 if pair_mi.0 + cell < bound_h
9587 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
9588 {
9589 slot[1] = u_state;
9590 slot[2] = v_state;
9591 }
9592 }
9593 for cell in 0..(pw / MI) {
9594 if pair_mi.1 + cell < bound_w
9595 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
9596 {
9597 slot[1] = u_state;
9598 slot[2] = v_state;
9599 }
9600 }
9601 last_uv_mode = Some(uv_predict_mode);
9602 }
9603 if horz {
9604 RECT4_16_HORZ_HITS.with(|h| h.set(h.get() + 1));
9605 } else {
9606 RECT4_16_VERT_HITS.with(|h| h.set(h.get() + 1));
9607 }
9608 let (pal_y_size, pal_y_colors) =
9609 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
9610 let (pal_uv_size, pal_uv_colors) =
9611 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
9612 record_strip_palette(
9613 neighbours, lmi, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
9614 );
9615 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
9616 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
9617 // frame): the above row records `tx_size_wide` over the block's width and
9618 // the left column `tx_size_high` over its height. This 1:4 strip reader is
9619 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
9620 // and it published neither band -- so the block after a 64x16 strip read
9621 // the row's init value 64 as its left transform height and took
9622 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
9623 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
9624 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
9625 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
9626 Ok((mode, last_uv_mode, (tx_w, tx_h)))
9627}
9628
9629
9630/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
9631/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
9632/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
9633/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
9634/// cap, so LUMA needs the same corner truncation [`decode_block`] already
9635/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
9636/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
9637/// this function's own charter/report), so both strips read a real 32x32
9638/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
9639/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
9640/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
9641/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
9642/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
9643/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
9644/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
9645/// that function, only the single-transform-unit (`tx_depth == 0`) case is
9646/// supported: a split transform refuses by name rather than guess-decode.
9647#[allow(clippy::too_many_arguments)]
9648fn decode_block_rect64(
9649 dec: &mut SymbolDecoder,
9650 cdfs: &mut Cdfs,
9651 neighbours: &mut Neighbours,
9652 at: (usize, usize),
9653 bw: usize,
9654 bh: usize,
9655 y: &mut PlaneBuf,
9656 u: &mut PlaneBuf,
9657 v: &mut PlaneBuf,
9658 enable_filter_intra: bool,
9659 allow_screen_content_tools: bool,
9660 base_q_idx: u8,
9661 tx_select: bool,
9662 reduced_tx_set: bool,
9663) -> Result<()> {
9664 let (r, c) = at;
9665 let (px, py) = (c * SUB, r * SUB);
9666 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
9667 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
9668 let palette_uv_cache = neighbours.palette_uv_cache(at);
9669 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
9670 read_intra_mode_rect(
9671 dec,
9672 cdfs,
9673 nb_above_mode,
9674 nb_left_mode,
9675 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
9676 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
9677 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
9678 // correct), CFL must never be offered here -- passing `true`
9679 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
9680 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
9681 // from this block's very first symbol (lane-sbpart r3 bisect).
9682 false,
9683 true,
9684 bw,
9685 bh,
9686 enable_filter_intra,
9687 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
9688 allow_screen_content_tools,
9689 Some((palette_ctx, &palette_cache)),
9690 &palette_uv_cache,
9691 r * (SUB / MI),
9692 c * (SUB / MI),
9693 )?;
9694 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
9695 // The luma coefficient path here is the corner-cropped 32x32 real
9696 // transform embedded in a 64x32/32x64 grid ([`decode_block_rect64`]'s
9697 // own doc comment) -- a real (non-skip) palette block's residual
9698 // needs the plain, uncropped rect reader [`decode_block_rect`] already
9699 // has, not this one's truncation. `skip` (no residual at all) is
9700 // still supported below (lane-palette2 r4).
9701 //
9702 // lane-pal8 r1 MEASURED the lift and it is NOT free: dropping this
9703 // refusal decodes `testsrc2` 128x128 10-bit cq55 `--enable-palette=1
9704 // --min-partition-size=8 --tile-columns=1` with a whole-frame pixel
9705 // mismatch (the arm the gate below counts). Something in this shape's
9706 // palette prediction or its corner-cropped residual is wrong, and the
9707 // refusal stays until that is found -- it is counted, never skipped.
9708 PALETTE_SB_STRIP_HITS.with(|c| c.set(c.get() + 1));
9709 return Err(unsupported(
9710 "a palette block with a real transform on a superblock-level HORZ/VERT \
9711 strip (corner-cropped luma coefficients not ported for palette)",
9712 ));
9713 }
9714 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
9715 if smooth_neighbor {
9716 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
9717 }
9718 let smooth_neighbor_uv =
9719 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
9720 if filter_intra.is_some() {
9721 // `filter_intra_size_class_rect` already returns `None` for both
9722 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
9723 // 32 on both axes), so this symbol is never read at this level --
9724 // kept only as the same defensive refusal [`decode_block_rect`] has.
9725 return Err(unsupported(
9726 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
9727 av1_filter_intra_allowed_bsize caps at 32x32)",
9728 ));
9729 }
9730 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
9731 DC_PRED
9732 } else {
9733 uv_mode
9734 };
9735 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
9736 let depth = if tx_select {
9737 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
9738 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
9739 // the 16x4 intra-in-inter strips already do); the key frame's
9740 // deblock-grid approximation is only right where those bands were never
9741 // written. Measured on the 10-bit 1920x792 128-superblock stream,
9742 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
9743 // `tx_size_cat2` row 1 where libaom reads row 2.
9744 let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {
9745 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh)
9746 } else {
9747 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
9748 };
9749 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
9750 // counts `sub_tx_size_map` steps from the block's own max rect
9751 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
9752 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
9753 // steps, so this level's category is 3 (the same one a 64x64 square
9754 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
9755 // here was a wrong-table read of a real symbol.
9756 let d = dec.symbol(&mut cdfs.tx_size_cat3[ctx]);
9757 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
9758 eprintln!(
9759 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=3 rng={}",
9760 dec.debug_state().0
9761 );
9762 }
9763 d
9764 } else {
9765 0
9766 };
9767 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
9768 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
9769 publish_txfm_bands_if_in_inter(
9770 neighbours,
9771 (mi_r, mi_c),
9772 depth_to_tx_wh(bw, bh, depth),
9773 (bw, bh),
9774 );
9775 if depth != 0 {
9776 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
9777 // lane-rectsplit r1/r4: the superblock-level strip splits its
9778 // transform through the very same per-unit path as its 32x32-level
9779 // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64
9780 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
9781 // measured the old square formula mis-tiling exactly that strip).
9782 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
9783 if bw.max(bh) / bw.min(bh) == 4 {
9784 let which = if depth == 1 {
9785 &RECT4_SPLIT_DEPTH1_HITS
9786 } else {
9787 &RECT4_SPLIT_DEPTH2_HITS
9788 };
9789 which.with(|c| c.set(c.get() + 1));
9790 }
9791 if std::env::var_os("EC_SBPART_DUMP64").is_some() {
9792 eprintln!(
9793 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
9794 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
9795 angle_y={angle_delta_y}"
9796 );
9797 }
9798 let modes = RectStripModes {
9799 skip,
9800 mode,
9801 angle_delta_y,
9802 uv_predict_mode,
9803 angle_delta_uv,
9804 alpha,
9805 filter_intra,
9806 smooth_neighbor,
9807 smooth_neighbor_uv,
9808 palette_y: palette_y
9809 .as_ref()
9810 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
9811 palette_uv: palette_uv.as_ref().map(|p| {
9812 (
9813 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
9814 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
9815 )
9816 }),
9817 };
9818 if palette_y.is_some() || palette_uv.is_some() {
9819 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
9820 }
9821 decode_rect_split(
9822 dec,
9823 cdfs,
9824 neighbours,
9825 (mi_r, mi_c),
9826 bw,
9827 bh,
9828 tx_w,
9829 tx_h,
9830 &modes,
9831 y,
9832 u,
9833 v,
9834 base_q_idx,
9835 reduced_tx_set,
9836 )?;
9837 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
9838 // (lane-palette2 r10): this return skips the fn's own tail, so a
9839 // split-tx superblock strip would otherwise leave the above/left
9840 // palette arrays holding a dead block's colours.
9841 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
9842 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
9843 let (puv_size, puv_colors) =
9844 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
9845 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
9846 // lane-frame36 r2: `set_txfm_ctxs` runs for EVERY block and this early
9847 // return skips the fn's own tail, so a SPLIT superblock-level strip
9848 // published no TXFM_CONTEXT band and the next block read the row's init
9849 // value 64 as its left transform height. Measured on the 10-bit
9850 // 3840x1608 stream, decode-order frame 33: after the split 16x64 strip
9851 // at mi(192,140) (`tx_depth=1` -> TX_16X32) the 32x64 block at
9852 // mi(192,144) took `tx_size_cat3` row 2 where libaom takes row 1. The
9853 // bands carry the SPLIT unit's size, not the block's.
9854 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
9855 RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.set(c.get() + 1));
9856 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
9857 return Ok(());
9858 }
9859 let (tx_w, tx_h) = (bw, bh);
9860 let (cpx, cpy) = (px / 2, py / 2);
9861 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
9862 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
9863 if let Some(ref pyv) = palette_y {
9864 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
9865 set_palette_pred(buf);
9866 }
9867 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
9868 (
9869 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
9870 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
9871 )
9872 });
9873 if skip {
9874 y.reconstruct_rect(
9875 px,
9876 py,
9877 bw,
9878 bh,
9879 mode,
9880 angle_delta_y,
9881 reach,
9882 &vec![0i32; bw * bh],
9883 None,
9884 filter_intra,
9885 smooth_neighbor,
9886 );
9887 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
9888 if let Some((ub, _)) = &palette_uv_bufs {
9889 set_palette_pred(ub.clone());
9890 }
9891 u.reconstruct_rect(
9892 cpx,
9893 cpy,
9894 chroma_w,
9895 chroma_h,
9896 uv_predict_mode,
9897 angle_delta_uv,
9898 reach,
9899 &vec![0i32; chroma_w * chroma_h],
9900 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
9901 None,
9902 smooth_neighbor_uv,
9903 );
9904 if let Some((_, vb)) = &palette_uv_bufs {
9905 set_palette_pred(vb.clone());
9906 }
9907 v.reconstruct_rect(
9908 cpx,
9909 cpy,
9910 chroma_w,
9911 chroma_h,
9912 uv_predict_mode,
9913 angle_delta_uv,
9914 reach,
9915 &vec![0i32; chroma_w * chroma_h],
9916 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
9917 None,
9918 smooth_neighbor_uv,
9919 );
9920 neighbours.record_rect(
9921 at,
9922 bw,
9923 bh,
9924 mode,
9925 uv_predict_mode,
9926 &[
9927 vec![0i32; bw * bh],
9928 vec![0i32; chroma_w * chroma_h],
9929 vec![0i32; chroma_w * chroma_h],
9930 ],
9931 );
9932 } else {
9933 let around = neighbours.around_rect(at, bw, bh);
9934 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
9935 // (see this function's own doc comment). A 64-length axis codes only
9936 // its low 32 coefficients, so the corner is `min(bw, 32)` x
9937 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
9938 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
9939 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
9940 let scan32 = default_scan(TX32);
9941 if std::env::var_os("EC_TRACE_COEFF").is_some() {
9942 let (rng, _) = dec.debug_state();
9943 eprintln!("EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}");
9944 }
9945 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
9946 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
9947 read_coeffs(
9948 dec,
9949 &mut luma_coding,
9950 &scan32,
9951 0,
9952 dc_sign_ctx(around[0].2),
9953 TxType::DctDct,
9954 Some((bw, bh)),
9955 )?
9956 } else {
9957 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
9958 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
9959 // (`scan.c`) gives both the very same `default_scan_32x16` /
9960 // `default_scan_16x32` the 2:1 sizes use ("Half of the
9961 // coefficients of tx64 at higher frequencies are set to zeros. So
9962 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
9963 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
9964 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
9965 // 512-position eob group) -- BOTH identical to TX_32X16, so the
9966 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
9967 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
9968 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
9969 // what `base_ctx_rect` computes at (32, 16).
9970 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
9971 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
9972 read_coeffs_rect(
9973 dec,
9974 &mut luma_coding,
9975 luma_scan,
9976 luma_cw,
9977 luma_ch,
9978 0,
9979 dc_sign_ctx(around[0].2),
9980 TxType::DctDct,
9981 )?
9982 };
9983 if std::env::var_os("EC_TRACE_COEFF").is_some() {
9984 let (rng, _) = dec.debug_state();
9985 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
9986 }
9987 let mut luma_levels = vec![0i32; bw * bh];
9988 for row in 0..luma_ch {
9989 luma_levels[row * bw..][..luma_cw]
9990 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
9991 }
9992 {
9993 let cur = block_q_idx();
9994 if cur != i32::from(base_q_idx) {
9995 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
9996 }
9997 if std::env::var_os("EC_AV1_TRACE").is_some() {
9998 eprintln!(
9999 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
10000 );
10001 }
10002 }
10003 let luma_residual = dequant_and_inverse_typed_wh(
10004 &luma_levels,
10005 bw,
10006 bh,
10007 crate::decode::bit_depth(),
10008 block_q_idx(),
10009 plane_q_delta(0).0,
10010 plane_q_delta(0).1,
10011 luma_tx_type,
10012 );
10013 y.reconstruct_rect(
10014 px,
10015 py,
10016 bw,
10017 bh,
10018 mode,
10019 angle_delta_y,
10020 reach,
10021 &luma_residual,
10022 None,
10023 filter_intra,
10024 smooth_neighbor,
10025 );
10026 if std::env::var_os("EC_SBPART_DUMP64").is_some() {
10027 let leftcol: Vec<u16> = if px > 0 {
10028 (py..py + bh).map(|row| y.data[row * y.width + px - 1]).collect()
10029 } else {
10030 vec![]
10031 };
10032 eprintln!(
10033 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
10034 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
10035 luma_corner.iter().any(|&v| v != 0),
10036 &y.data[py * y.width + px..][..bw],
10037 leftcol,
10038 );
10039 }
10040 // CHROMA: a real, untruncated chroma_w x chroma_h transform -- no
10041 // corner crop needed (see doc comment).
10042 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
10043 // The chroma plane is never truncated (both axes <= 32 after
10044 // subsampling). Under a 1:4 strip it is a true 32x8/8x32:
10045 // `get_txsize_entropy_ctx(TX_32X8)` = (TX_8X8 + TX_32X32 + 1) >> 1 =
10046 // TX_16X16 and `txsize_log2_minus4[TX_32X8]` = 4 (256 positions),
10047 // both identical to TX_16X16 -- so [`TxbSet::Chroma16`] is the exact
10048 // set, and only the scan is new (lane-tx64x16).
10049 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (bw, bh) {
10050 (64, 16) => (TxbSet::Chroma16, &SCAN_32X8),
10051 (16, 64) => (TxbSet::Chroma16, &SCAN_8X32),
10052 (64, _) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
10053 _ => (TxbSet::ChromaRect32x16, &SCAN_16X32),
10054 };
10055 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
10056 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
10057 if std::env::var_os("EC_TRACE_COEFF").is_some() {
10058 let (rng, _) = dec.debug_state();
10059 eprintln!("EC_COEFF plane=1 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
10060 }
10061 let (u_levels, u_tx_type) = read_coeffs_rect(
10062 dec,
10063 &mut u_coding,
10064 chroma_scan,
10065 chroma_w,
10066 chroma_h,
10067 u_skip_ctx,
10068 dc_sign_ctx(around[1].2),
10069 TxType::DctDct,
10070 )?;
10071 if std::env::var_os("EC_TRACE_COEFF").is_some() {
10072 let (rng, _) = dec.debug_state();
10073 eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}");
10074 }
10075 {
10076 let cur = block_q_idx();
10077 if cur != i32::from(base_q_idx) {
10078 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
10079 }
10080 if std::env::var_os("EC_AV1_TRACE").is_some() {
10081 eprintln!(
10082 "TRACE rect64_dequant plane=1 base_q_idx={base_q_idx} current_q_idx={cur}"
10083 );
10084 }
10085 }
10086 let u_residual = dequant_and_inverse_typed_wh(
10087 &u_levels,
10088 chroma_w,
10089 chroma_h,
10090 crate::decode::bit_depth(),
10091 block_q_idx(),
10092 plane_q_delta(1).0,
10093 plane_q_delta(1).1,
10094 u_tx_type,
10095 );
10096 u.reconstruct_rect(
10097 cpx,
10098 cpy,
10099 chroma_w,
10100 chroma_h,
10101 uv_predict_mode,
10102 angle_delta_uv,
10103 reach,
10104 &u_residual,
10105 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
10106 None,
10107 smooth_neighbor_uv,
10108 );
10109 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
10110 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
10111 if std::env::var_os("EC_TRACE_COEFF").is_some() {
10112 let (rng, _) = dec.debug_state();
10113 eprintln!("EC_COEFF plane=2 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
10114 }
10115 let (v_levels, v_tx_type) = read_coeffs_rect(
10116 dec,
10117 &mut v_coding,
10118 chroma_scan,
10119 chroma_w,
10120 chroma_h,
10121 v_skip_ctx,
10122 dc_sign_ctx(around[2].2),
10123 TxType::DctDct,
10124 )?;
10125 if std::env::var_os("EC_TRACE_COEFF").is_some() {
10126 let (rng, _) = dec.debug_state();
10127 eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}");
10128 }
10129 {
10130 let cur = block_q_idx();
10131 if cur != i32::from(base_q_idx) {
10132 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
10133 }
10134 if std::env::var_os("EC_AV1_TRACE").is_some() {
10135 eprintln!(
10136 "TRACE rect64_dequant plane=2 base_q_idx={base_q_idx} current_q_idx={cur}"
10137 );
10138 }
10139 }
10140 let v_residual = dequant_and_inverse_typed_wh(
10141 &v_levels,
10142 chroma_w,
10143 chroma_h,
10144 crate::decode::bit_depth(),
10145 block_q_idx(),
10146 plane_q_delta(2).0,
10147 plane_q_delta(2).1,
10148 v_tx_type,
10149 );
10150 v.reconstruct_rect(
10151 cpx,
10152 cpy,
10153 chroma_w,
10154 chroma_h,
10155 uv_predict_mode,
10156 angle_delta_uv,
10157 reach,
10158 &v_residual,
10159 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
10160 None,
10161 smooth_neighbor_uv,
10162 );
10163 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
10164 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
10165 }
10166 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
10167 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
10168 let (puv_size, puv_colors) =
10169 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
10170 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
10171 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
10172 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
10173 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
10174 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
10175 // frame): the above row records `tx_size_wide` over the block's width and
10176 // the left column `tx_size_high` over its height. This 1:4 strip reader is
10177 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
10178 // and it published neither band -- so the block after a 64x16 strip read
10179 // the row's init value 64 as its left transform height and took
10180 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
10181 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
10182 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
10183 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
10184 SB_RECT_HITS.with(|c| c.set(c.get() + 1));
10185 match (bw, bh) {
10186 (64, 16) => SB_RECT4_HORZ_HITS.with(|c| c.set(c.get() + 1)),
10187 (16, 64) => SB_RECT4_VERT_HITS.with(|c| c.set(c.get() + 1)),
10188 _ => {}
10189 }
10190 if std::env::var_os("EC_AV1_TRACE").is_some() {
10191 let (rng, _) = dec.debug_state();
10192 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
10193 }
10194 Ok(())
10195}
10196
10197/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
10198/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
10199/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
10200/// it lands away from zero, for gate tests to prove a real stream fired one.
10201fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
10202 let symbol = dec.symbol(cdf);
10203 if symbol != ANGLE_DELTA_ZERO {
10204 ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
10205 }
10206 symbol as i32 - ANGLE_DELTA_ZERO as i32
10207}
10208
10209#[allow(clippy::too_many_arguments)]
10210fn read_intra_mode(
10211 dec: &mut SymbolDecoder,
10212 cdfs: &mut Cdfs,
10213 above_mode: usize,
10214 left_mode: usize,
10215 cfl: bool,
10216 side: usize,
10217 enable_filter_intra: bool,
10218 skip_ctx: usize,
10219 allow_screen_content_tools: bool,
10220 allow_intrabc: bool,
10221 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
10222 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
10223 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
10224 // `None` at the excluded call sites (the 8x8-leaf path), which still read
10225 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
10226 // decoder reads either way -- but refuse by name the moment it fires,
10227 // exactly the old behaviour.
10228 palette: Option<(usize, &[u16])>,
10229 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
10230 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
10231 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
10232 // `use_palette_y`, not a neighbour lookup).
10233 palette_uv_cache: &[u16],
10234 mi_r: usize,
10235 mi_c: usize,
10236) -> Result<(
10237 bool,
10238 usize,
10239 i32,
10240 usize,
10241 i32,
10242 Option<(i32, i32)>,
10243 Option<usize>,
10244 Option<PaletteY>,
10245 Option<PaletteUv>,
10246)> {
10247 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
10248 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
10249 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
10250 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
10251 // line against the instrumented aomdec, not just `tell()`.
10252 let ec_istep = std::env::var_os("EC_TRACE_MODE_STEP").is_some();
10253 if ec_istep {
10254 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
10255 // (decodemv.c:818), printed at the same point: before the first
10256 // mode-info symbol of the block, so a cross-decoder range ladder can
10257 // be keyed on the BLOCK, not just on the symbol sequence.
10258 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}", dec.debug_state().0);
10259 }
10260 macro_rules! istep {
10261 ($name:literal, $val:expr) => {
10262 if ec_istep {
10263 let (rng, _) = dec.debug_state();
10264 eprintln!(
10265 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
10266 $name, $val
10267 );
10268 }
10269 };
10270 }
10271 // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single
10272 // point every square caller routes through (see `read_intra_mode_rect`).
10273 let cfl = if cfl && side > 32 {
10274 NOCFL_UV_MODE_HITS.with(|c| c.set(c.get() + 1));
10275 false
10276 } else {
10277 cfl
10278 };
10279 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
10280 // `skip` when `SegIdPreSkip`, and after it otherwise.
10281 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
10282 if seg_id_pre_skip() {
10283 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);
10284 }
10285 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
10286 if trace {
10287 eprintln!("TRACE skip value={} rng={}", skip as i32, dec.debug_state().0);
10288 }
10289 istep!("skip", skip as i32);
10290 if !seg_id_pre_skip() {
10291 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);
10292 }
10293 // spec order (see the comment below on `read_intrabc_info`): `skip`,
10294 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
10295 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
10296 istep!("cdef", 0);
10297 // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not
10298 // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole
10299 // superblock and skips `delta_q` exactly like a 64 one under a 64 root.
10300 let whole_sb = side == sb_mi_cur() as usize * 4;
10301 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, whole_sb, skip);
10302 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, whole_sb, skip);
10303 istep!("dq", 0);
10304 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
10305 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
10306 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
10307 // intra frame whose header set `allow_intrabc`. Actual intra block copy
10308 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
10309 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
10310 // draws the line at consuming this one flag symbol and refusing by name
10311 // when it fires, so the arithmetic decoder still resyncs for a stream
10312 // that merely allows (but never uses) intrabc.
10313 if allow_intrabc {
10314 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
10315 if trace {
10316 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
10317 }
10318 if use_intrabc {
10319 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, side);
10320 if trace {
10321 eprintln!("TRACE intrabc dv={dv:?}");
10322 }
10323 INTRABC_DV.with(|c| c.set(Some(dv)));
10324 INTRABC_HITS.with(|c| c.set(c.get() + 1));
10325 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
10326 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
10327 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
10328 // `DC_PRED` (which is also what the neighbour mode contexts and
10329 // the loop filter then see).
10330 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
10331 }
10332 }
10333 let above_ctx = INTRA_MODE_CTX[above_mode];
10334 let left_ctx = INTRA_MODE_CTX[left_mode];
10335 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
10336 if trace {
10337 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
10338 }
10339 istep!("mode", mode as i32);
10340 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
10341 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
10342 if trace {
10343 eprintln!(
10344 "TRACE angle_delta value={}",
10345 delta + ANGLE_DELTA_ZERO as i32
10346 );
10347 }
10348 delta
10349 } else {
10350 0
10351 };
10352 istep!("angle_y", angle_delta_y);
10353 // lane-sb128c r3 (class sweep): `is_cfl_allowed` on the luma bsize, decided
10354 // here so every `decode_block` caller (64x64 and 128x128 roots included)
10355 // picks the right alphabet -- see [`read_intra_mode_rect`]'s twin.
10356 let cfl = cfl && side <= 32;
10357 let uv_mode = if cfl {
10358 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
10359 } else {
10360 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
10361 };
10362 if trace {
10363 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}", dec.debug_state().0);
10364 }
10365 istep!("uv_mode", uv_mode as i32);
10366 let alpha = if cfl && uv_mode == UV_CFL_PRED {
10367 Some(read_cfl_alphas(dec, cdfs))
10368 } else {
10369 None
10370 };
10371 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
10372 // from this lane's directional chroma: a corner block with neither
10373 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
10374 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
10375 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
10376 // bug in that fallback this lane's own scope does not cover. Keep it
10377 // refused here rather than ship a silently-wrong decode.
10378 if (9..=12).contains(&uv_mode) {
10379 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
10380 }
10381 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
10382 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
10383 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
10384 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
10385 // the `else` branch below and never reads one either way.
10386 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
10387 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
10388 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
10389 } else {
10390 0
10391 };
10392 istep!("angle_uv", angle_delta_uv);
10393 if angle_delta_uv != 0 {
10394 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
10395 }
10396 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
10397 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
10398 // gated by `av1_allow_palette` (blockd.h -- size bound only,
10399 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
10400 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
10401 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
10402 // read the same CDF row whenever every neighbour really is non-palette).
10403 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
10404 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
10405 // neighbour lookup at all), so it is exact even at the excluded call
10406 // sites once Y decodes real syntax there too.
10407 //
10408 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
10409 // inline from `read_palette_mode_info` -- it runs later, from
10410 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
10411 // after the WHOLE mode-info read for the block, including UV palette
10412 // mode_info (`read_palette_mode_info`'s own second half, right below)
10413 // and `read_filter_intra_mode_info`. So this branch now only reads
10414 // mode/size/colours for both planes (deferring the two colour-index-map
10415 // decodes to after `filter_intra`, below) -- r6's range trace pinned
10416 // this exact ordering bug (`compare-range-not-tell`: ranges matched
10417 // bit-for-bit through the Y colours, diverged only at the old inline
10418 // `decode_color_index_map` call).
10419 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
10420 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
10421 if allow_screen_content_tools
10422 && let Some(bsize_ctx) = palette_bsize_ctx(side)
10423 {
10424 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
10425 if mode == DC_PRED {
10426 if trace {
10427 let (rng, _) = dec.debug_state();
10428 eprintln!(
10429 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
10430 );
10431 }
10432 }
10433 let use_palette_y =
10434 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
10435 if mode == DC_PRED && trace {
10436 let (rng, _) = dec.debug_state();
10437 eprintln!("TRACE palette_y_mode value={} rng={rng}", use_palette_y as i32);
10438 }
10439 if use_palette_y {
10440 if palette.is_none() {
10441 return Err(unsupported(
10442 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
10443 ));
10444 }
10445 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
10446 if trace {
10447 let (rng, _) = dec.debug_state();
10448 eprintln!("TRACE palette_y_size n={n} rng={rng}");
10449 }
10450 let colors = read_palette_colors_y(dec, n, cache);
10451 if trace {
10452 let (rng, _) = dec.debug_state();
10453 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
10454 }
10455 palette_y_pending = Some((n, colors));
10456 }
10457 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
10458 // unconditionally at this bit position whenever `uv_mode ==
10459 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
10460 // scope always reconstructs chroma alongside luma (`decode_block`
10461 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
10462 // is always true here and does not need threading in.
10463 let palette_uv_mode_ctx = usize::from(use_palette_y);
10464 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
10465 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
10466 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache);
10467 palette_uv_pending = Some((n, u_colors, v_colors));
10468 }
10469 }
10470 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
10471 // `use_filter_intra` symbol this decoder never read at all until
10472 // lane-av1real r10 -- silently skipping it left every bit past a
10473 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
10474 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
10475 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
10476 // symbol's bits were never consumed).
10477 let mut filter_intra = None;
10478 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
10479 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
10480 // `use_filter_intra` symbol for a Y-palette block, and reading one here
10481 // desynced every screen-content stream from the first palette block on
10482 // (it surfaced as a bogus "partition below 8x8" refusal further down the
10483 // tile).
10484 if mode == DC_PRED
10485 && enable_filter_intra
10486 && palette_y_pending.is_none()
10487 && let Some(class) = filter_intra_size_class(side)
10488 {
10489 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
10490 if trace {
10491 eprintln!(
10492 "TRACE use_filter_intra side={side} rng={} value={}", dec.debug_state().0,
10493 use_filter_intra as i32
10494 );
10495 }
10496 istep!("use_filter_intra", use_filter_intra as i32);
10497 if use_filter_intra {
10498 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
10499 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
10500 if trace {
10501 eprintln!("TRACE filter_intra_mode value={fi_mode}");
10502 }
10503 istep!("filter_intra_mode", fi_mode as i32);
10504 filter_intra = Some(fi_mode);
10505 }
10506 }
10507 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
10508 // shared U/V map) -- the same order libaom's own loop visits them in.
10509 let palette_y = palette_y_pending.map(|(n, colors)| {
10510 let map = decode_color_index_map(dec, cdfs, n, side, false);
10511 PALETTE_HITS.with(|c| c.set(c.get() + 1));
10512 if trace {
10513 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
10514 }
10515 PaletteY { size: n, colors, map }
10516 });
10517 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
10518 let map = decode_color_index_map(dec, cdfs, n, side / 2, true);
10519 PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
10520 if trace {
10521 eprintln!(
10522 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
10523 &u_colors[..n],
10524 &v_colors[..n]
10525 );
10526 }
10527 PaletteUv { size: n, u_colors, v_colors, map }
10528 });
10529 Ok((
10530 skip,
10531 mode,
10532 angle_delta_y,
10533 uv_mode,
10534 angle_delta_uv,
10535 alpha,
10536 filter_intra,
10537 palette_y,
10538 palette_uv,
10539 ))
10540}
10541
10542/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
10543/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
10544/// intra modes.
10545const UV_CFL_PRED: usize = 13;
10546
10547/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
10548/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
10549/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
10550/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
10551/// joint sign the same way. Returns each plane's final signed `alpha_q3`
10552/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
10553fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
10554 CFL_BLOCK_HITS.with(|c| c.set(c.get() + 1));
10555 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
10556 let sign_u = ((joint_sign + 1) * 11) >> 5;
10557 let sign_v = (joint_sign + 1) - 3 * sign_u;
10558 let alpha_u = if sign_u == 0 {
10559 0
10560 } else {
10561 let ctx_u = (joint_sign + 1 - 3) as usize;
10562 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
10563 if sign_u == 2 { mag } else { -mag }
10564 };
10565 let alpha_v = if sign_v == 0 {
10566 0
10567 } else {
10568 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
10569 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
10570 if sign_v == 2 { mag } else { -mag }
10571 };
10572 (alpha_u, alpha_v)
10573}
10574
10575/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
10576/// the reconstructed luma samples under a `side`-square block, subsampled
10577/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
10578/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
10579/// to give the AC values [`cfl_scaled`] scales by alpha.
10580fn cfl_ac_q3(y: &PlaneBuf, px: usize, py: usize, side: usize) -> Vec<i32> {
10581 let cside = side / 2;
10582 let mut ac = vec![0i32; cside * cside];
10583 let mut sum = 0i32;
10584 for cy in 0..cside {
10585 for cx in 0..cside {
10586 let (lx, ly) = (px + cx * 2, py + cy * 2);
10587 let q3 = (i32::from(y.data[ly * y.width + lx])
10588 + i32::from(y.data[ly * y.width + lx + 1])
10589 + i32::from(y.data[(ly + 1) * y.width + lx])
10590 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
10591 << 1;
10592 ac[cy * cside + cx] = q3;
10593 sum += q3;
10594 }
10595 }
10596 let num_pel = (cside * cside) as i32;
10597 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
10598 ac.iter_mut().for_each(|v| *v -= avg);
10599 ac
10600}
10601
10602/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
10603/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
10604/// ties away from zero on the shifted-out sign).
10605fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
10606 let v = alpha_q3 * ac_q3;
10607 if v >= 0 {
10608 (v + 32) >> 6
10609 } else {
10610 -((-v + 32) >> 6)
10611 }
10612}
10613
10614/// One plane's reconstruction buffer, `width * height` samples, and the
10615/// prediction/residual reads and writes into it — the decode-side twin of
10616/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
10617/// (own-edge and reach clamps both), passing what it gathers straight to
10618/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
10619/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
10620/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
10621/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of
10622/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) --
10623/// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE).
10624/// lane-mc64 r1: the decode-order index the stage dumps below key their file
10625/// name on. `PREFILT_PICTURE_IDX` is bumped once per frame just BEFORE the
10626/// deblock/CDEF stages run, so the frame being dumped here is `idx - 1` --
10627/// without this every frame overwrote `.f0` and a per-frame bisection silently
10628/// compared the LAST decoded frame (ledger, class stale-output-faked-measurement).
10629fn stage_dump_idx() -> usize {
10630 PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst).saturating_sub(1)
10631}
10632
10633fn dump_stage16(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf, fw: usize, fh: usize) {
10634 use std::io::Write;
10635 // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by
10636 // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed
10637 // `.f0` name kept only the LAST frame, so a mid-sequence divergence could
10638 // not be read out at all.
10639 if let Ok(path) = std::env::var(var)
10640 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
10641 {
10642 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))] {
10643 for row in 0..h {
10644 let mut bytes = Vec::with_capacity(w * 2);
10645 for &s in &p.data[row * p.width..][..w] {
10646 bytes.extend_from_slice(&s.to_le_bytes());
10647 }
10648 let _ = f.write_all(&bytes);
10649 }
10650 }
10651 }
10652}
10653
10654/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a
10655/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so
10656/// every frame overwrote the previous one and only the LAST frame survived,
10657/// which silently defeats any per-frame filter-stage bisection.
10658fn dump_stage_idx(var: &str) -> usize {
10659 use std::collections::HashMap;
10660 use std::sync::{Mutex, OnceLock};
10661 static IDX: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new();
10662 let mut m = IDX.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap();
10663 let e = m.entry(var.to_string()).or_insert(0);
10664 let i = *e;
10665 *e += 1;
10666 i
10667}
10668
10669fn dump_stage(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf) {
10670 use std::io::Write;
10671 if let Ok(path) = std::env::var(var)
10672 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
10673 {
10674 for p in [y, u, v] {
10675 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
10676 let _ = f.write_all(&narrow);
10677 }
10678 }
10679}
10680
10681#[derive(Clone)]
10682struct PlaneBuf {
10683 data: Vec<u16>,
10684 width: usize,
10685 height: usize,
10686 /// The frame's true, decodable extent in this plane's own units — past
10687 /// this, samples are the padded coding surface's invented tail, never a
10688 /// real decoder's edge or reach reads.
10689 true_width: usize,
10690 true_height: usize,
10691 /// This plane's own tile's top-left pixel origin (spec: intra prediction
10692 /// never reaches across a tile boundary even though an earlier-decoded
10693 /// tile's real pixels sit right there in the shared buffer) — set via
10694 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
10695 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
10696 /// is threaded (the two-tile column-split stage 1 fixture's tile always
10697 /// ends at the frame's own right/bottom edge); a non-last tile's own
10698 /// right/bottom reach bound is still open, tracked in the report.
10699 tile_x0: usize,
10700 tile_y0: usize,
10701 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
10702 /// (exclusive) -- a non-last tile column/row's own reach must stop at
10703 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
10704 /// full padded extent) for the single-tile/last-tile case, matching the
10705 /// old unclipped behaviour exactly.
10706 tile_x1: usize,
10707 tile_y1: usize,
10708}
10709
10710/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
10711/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
10712/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
10713/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
10714/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
10715/// `ALTREF2`/`ALTREF`).
10716type RefSlots<'a> = [Option<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)>; 8];
10717
10718impl PlaneBuf {
10719 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
10720 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
10721 /// are already in this plane's own units (luma pixels for `y`, chroma
10722 /// pixels — halved — for `u`/`v`).
10723 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
10724 self.tile_x0 = x0;
10725 self.tile_y0 = y0;
10726 self.tile_x1 = x1;
10727 self.tile_y1 = y1;
10728 }
10729
10730 fn edges(
10731 &self,
10732 x: usize,
10733 y: usize,
10734 side: usize,
10735 reach: Reach,
10736 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
10737 let own_across = x + side.min(self.true_width.saturating_sub(x));
10738 let across = if reach.above_right {
10739 own_across + side.min(self.true_width.saturating_sub(own_across))
10740 } else {
10741 own_across
10742 }
10743 .min(self.width)
10744 .min(self.tile_x1);
10745 let own_down = y + side.min(self.true_height.saturating_sub(y));
10746 let down = if reach.below_left {
10747 own_down + side.min(self.true_height.saturating_sub(own_down))
10748 } else {
10749 own_down
10750 }
10751 .min(self.height)
10752 .min(self.tile_y1);
10753 let above = (y > self.tile_y0 && across > x)
10754 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
10755 let left = (x > self.tile_x0 && down > y).then(|| {
10756 (y..down)
10757 .map(|row| self.data[row * self.width + x - 1])
10758 .collect::<Vec<_>>()
10759 });
10760 let corner =
10761 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
10762 (above, left, corner)
10763 }
10764
10765 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
10766 /// the above/left reach each extend by their OWN axis (`bw` across,
10767 /// `bh` down), not one shared `side`.
10768 fn edges_rect(
10769 &self,
10770 x: usize,
10771 y: usize,
10772 bw: usize,
10773 bh: usize,
10774 reach: Reach,
10775 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
10776 let own_across = x + bw.min(self.true_width.saturating_sub(x));
10777 let across = if reach.above_right {
10778 own_across + bw.min(self.true_width.saturating_sub(own_across))
10779 } else {
10780 own_across
10781 }
10782 .min(self.width)
10783 .min(self.tile_x1);
10784 let own_down = y + bh.min(self.true_height.saturating_sub(y));
10785 let down = if reach.below_left {
10786 own_down + bh.min(self.true_height.saturating_sub(own_down))
10787 } else {
10788 own_down
10789 }
10790 .min(self.height)
10791 .min(self.tile_y1);
10792 let above = (y > self.tile_y0 && across > x)
10793 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
10794 let left = (x > self.tile_x0 && down > y).then(|| {
10795 (y..down)
10796 .map(|row| self.data[row * self.width + x - 1])
10797 .collect::<Vec<_>>()
10798 });
10799 let corner =
10800 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
10801 if matches!((bw, bh), (16, 8) | (8, 16)) {
10802 RECT_STRIP_PRED_HITS.with(|h| h.set(h.get() + 1));
10803 if across > own_across || down > own_down {
10804 RECT_STRIP_REACH_HITS.with(|h| h.set(h.get() + 1));
10805 }
10806 }
10807 (above, left, corner)
10808 }
10809
10810 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
10811 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
10812 /// already-rect-capable `(bw, bh)` pair.
10813 #[allow(clippy::too_many_arguments)]
10814 #[track_caller]
10815 fn reconstruct_rect(
10816 &mut self,
10817 x: usize,
10818 y: usize,
10819 bw: usize,
10820 bh: usize,
10821 mode: usize,
10822 angle_delta: i32,
10823 reach: Reach,
10824 residual: &[i32],
10825 cfl: Option<(i32, &[i32])>,
10826 filter_intra: Option<usize>,
10827 smooth_neighbor: bool,
10828 ) {
10829 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
10830 // (lane-palette2 r4): a palette block's prediction is the
10831 // reconstructed colour-index map, needing no edge pixels at all.
10832 let prediction = if let Some(buf) = take_palette_pred() {
10833 buf
10834 } else {
10835 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
10836 if std::env::var_os("EC_DEBUG_EDGES").is_some() {
10837 eprintln!(
10838 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
10839 above.as_ref().map(|a| (a.len(), a[0])),
10840 left.as_ref().map(|l| l.len()),
10841 left.as_ref().map(|l| l[0]),
10842 self.tile_x0, self.tile_y0, self.true_width, self.true_height
10843 );
10844 }
10845 let mut prediction = vec![0u16; bw * bh];
10846 if let Some(fi_mode) = filter_intra {
10847 crate::intra::predict_filter_intra(
10848 fi_mode,
10849 above.as_deref(),
10850 left.as_deref(),
10851 corner,
10852 bw,
10853 bh,
10854 &mut prediction,
10855 );
10856 } else {
10857 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
10858 predict(
10859 mode as u8,
10860 angle_delta,
10861 above.as_deref(),
10862 left.as_deref(),
10863 corner,
10864 bw,
10865 bh,
10866 enable_edge_filter,
10867 smooth_neighbor,
10868 &mut prediction,
10869 );
10870 }
10871 prediction
10872 };
10873 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
10874 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
10875 if std::env::var_os("EC_PRED").is_some() {
10876 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
10877 let row0: Vec<u16> = prediction[..bw.min(8)].to_vec();
10878 let col0: Vec<u16> = (0..bh.min(8)).map(|r| prediction[r * bw]).collect();
10879 eprintln!(
10880 "@{} 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()
10881 );
10882 }
10883 for row in 0..bh {
10884 // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s
10885 // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame
10886 // whose padded width is not superblock aligned hangs past it.
10887 if y + row >= self.height {
10888 break;
10889 }
10890 for col in 0..bw {
10891 if x + col >= self.width {
10892 break;
10893 }
10894 let idx = row * bw + col;
10895 let mut base = i32::from(prediction[idx]);
10896 if let Some((alpha_q3, ac_q3)) = cfl {
10897 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max());
10898 }
10899 let sample = (base + residual[idx]).clamp(0, sample_max()) as u16;
10900 self.data[(y + row) * self.width + x + col] = sample;
10901 }
10902 }
10903 }
10904
10905 /// Predicts under `mode` then adds `residual` (side*side, raster),
10906 /// writing the clamped reconstruction back into the plane at `(x, y)`.
10907 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
10908 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
10909 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
10910 /// order (cfl.c).
10911 #[track_caller]
10912 fn reconstruct(
10913 &mut self,
10914 x: usize,
10915 y: usize,
10916 side: usize,
10917 mode: usize,
10918 angle_delta: i32,
10919 reach: Reach,
10920 residual: &[i32],
10921 cfl: Option<(i32, &[i32])>,
10922 filter_intra: Option<usize>,
10923 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
10924 // libaom `get_filt_type`): true when the block's above OR left
10925 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
10926 // Callers pass their own plane's neighbour-mode check
10927 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
10928 // callers until a smooth/paeth `uv_mode` can reach this call at all
10929 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
10930 // keeps `false` exact for chroma without this fn needing to know why.
10931 smooth_neighbor: bool,
10932 ) {
10933 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
10934 // takes priority over `predict()`/`predict_filter_intra` entirely --
10935 // palette prediction needs no edge pixels at all.
10936 let prediction = if let Some(buf) = take_palette_pred() {
10937 buf
10938 } else {
10939 let (above, left, corner) = self.edges(x, y, side, reach);
10940 let mut prediction = vec![0u16; side * side];
10941 if let Some(fi_mode) = filter_intra {
10942 crate::intra::predict_filter_intra(
10943 fi_mode,
10944 above.as_deref(),
10945 left.as_deref(),
10946 corner,
10947 side,
10948 side,
10949 &mut prediction,
10950 );
10951 } else {
10952 // `enable_intra_edge_filter` is the sequence header's own flag
10953 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
10954 // call, never per-block) -- threading it through every
10955 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
10956 // dozen sites for a value that never changes mid-decode, so it
10957 // rides a thread-local instead (this decoder is single-threaded
10958 // per stream).
10959 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
10960 predict(
10961 mode as u8,
10962 angle_delta,
10963 above.as_deref(),
10964 left.as_deref(),
10965 corner,
10966 side,
10967 side,
10968 enable_edge_filter,
10969 smooth_neighbor,
10970 &mut prediction,
10971 );
10972 }
10973 prediction
10974 };
10975 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
10976 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
10977 if std::env::var_os("EC_PRED").is_some() {
10978 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
10979 let row0: Vec<u16> = prediction[..side.min(8)].to_vec();
10980 let col0: Vec<u16> = (0..side.min(8)).map(|r| prediction[r * side]).collect();
10981 eprintln!(
10982 "@{} 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()
10983 );
10984 }
10985 for row in 0..side {
10986 // lane-sb128c r8: libaom's frame buffer is superblock
10987 // aligned; ours is padded to 32 (`block_grid`), so a 64x64
10988 // transform unit of a 128x64 block at the BOTTOM frame edge
10989 // can hang past the last padded row (1920x792: a unit at
10990 // y=768 wants 832 rows of an 800-row buffer, which panicked
10991 // the film's key frames). Those samples are outside the
10992 // frame: never output, and no block below ever references
10993 // them.
10994 if y + row >= self.height {
10995 break;
10996 }
10997 for col in 0..side {
10998 if x + col >= self.width {
10999 break;
11000 }
11001 let idx = row * side + col;
11002 let mut base = i32::from(prediction[idx]);
11003 if let Some((alpha_q3, ac_q3)) = cfl {
11004 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max());
11005 }
11006 let sample = (base + residual[idx]).clamp(0, sample_max()) as u16;
11007 self.data[(y + row) * self.width + x + col] = sample;
11008 }
11009 }
11010 }
11011}
11012
11013/// Reads one plane's transform block, reconstructs it into `plane` at
11014/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
11015#[allow(clippy::too_many_arguments)]
11016fn read_plane(
11017 dec: &mut SymbolDecoder,
11018 cdfs: &mut Cdfs,
11019 set: TxbSet,
11020 scan: &[u16],
11021 plane_idx: usize,
11022 around: (bool, bool, i32),
11023 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
11024 // it for every plane's `txb` lookup (it is what an intra transform type's
11025 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
11026 tx_mode: usize,
11027 predict_mode: usize,
11028 angle_delta: i32,
11029 reach: Reach,
11030 plane: &mut PlaneBuf,
11031 x: usize,
11032 y: usize,
11033 side: usize,
11034 tx_side: usize,
11035 base_q_idx: u8,
11036 cfl: Option<(i32, &[i32])>,
11037 filter_intra: Option<usize>,
11038 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
11039 // smaller than its own block (spec `get_txb_ctx_general`'s
11040 // `plane_bsize != tx_size` branch), carrying the already-looked-up
11041 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
11042 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
11043 // formula below.
11044 luma_skip_ctx: Option<usize>,
11045 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
11046 smooth_neighbor: bool,
11047) -> Result<Vec<i32>> {
11048 let skip_ctx = if plane_idx == 0 {
11049 luma_skip_ctx.unwrap_or(0)
11050 } else {
11051 // libaom `get_txb_ctx`: a chroma unit's context is
11052 // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the
11053 // plane block is bigger than the transform. Our chroma tables hold the
11054 // offset-7 rows first, so the caller adds 3 for the bigger-block case
11055 // (only a 128x128 block's TX_32X32 chroma units, lane-sb128b r3).
11056 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
11057 };
11058 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
11059 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
11060 // not by the block's ordinary `mode` (which is always DC_PRED whenever
11061 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
11062 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
11063 // filter-intra in AV1).
11064 let tx_mode = if plane_idx == 0 { fi_tx_row(tx_mode, filter_intra) } else { tx_mode };
11065 let mut coding = cdfs.txb(set, tx_mode);
11066 // Luma's `default_tx_type` is only a fallback for the sizes whose
11067 // `TxbSet` carries no symbol at all (32-point and up), which the spec
11068 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
11069 // *never* its own coded symbol (`coding.tx_type` is always `None` for
11070 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
11071 // the plane's own predicted mode (`default_intra_tx_type`) -- except
11072 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
11073 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
11074 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
11075 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
11076 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
11077 // narrows there — only `Chroma32` and up do).
11078 let default_tx_type = if plane_idx == 0 || side >= 32 {
11079 TxType::DctDct
11080 } else if let Some(inherited) = INTRABC_CHROMA_TX.with(std::cell::Cell::get) {
11081 // See [`INTRABC_CHROMA_TX`]: an intrabc block is an inter block for
11082 // `av1_get_tx_type`, so chroma inherits luma's coded type (the
11083 // `side >= 32` arm above is already libaom's `EXT_TX_SET_DCTONLY`
11084 // clamp at `tx_size_sqr_up >= TX_32X32`, matching
11085 // [`read_inter_plane`]'s own `side < 32` guard).
11086 inherited
11087 } else {
11088 default_intra_tx_type(predict_mode as u8)
11089 };
11090 let (grid, tx_type) = read_coeffs(
11091 dec,
11092 &mut coding,
11093 scan,
11094 skip_ctx,
11095 dc_sign_ctx(around.2),
11096 default_tx_type,
11097 None,
11098 )?;
11099 note_chroma_class1(plane_idx, tx_type);
11100 if plane_idx == 0 {
11101 LUMA_TX_TYPE.with(|c| c.set(tx_type));
11102 }
11103 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
11104 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
11105 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
11106 // guard also assumes.
11107 let levels = if tx_side == side {
11108 grid
11109 } else {
11110 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
11111 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
11112 // keyed by that true size, not the coded corner's -- so the corner
11113 // goes into the top-left of a `side`-sized grid, not the reverse.
11114 let mut full = vec![0i32; side * side];
11115 for row in 0..tx_side {
11116 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
11117 }
11118 full
11119 };
11120 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
11121 let residual = dequant_and_inverse_typed(&levels, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type);
11122 if std::env::var_os("EC_AV1_TRACE").is_some() {
11123 eprintln!(
11124 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={levels:?} residual={residual:?}",
11125 );
11126 }
11127 plane.reconstruct(
11128 x,
11129 y,
11130 side,
11131 predict_mode,
11132 angle_delta,
11133 reach,
11134 &residual,
11135 cfl,
11136 filter_intra,
11137 smooth_neighbor,
11138 );
11139 Ok(if tx_side == side {
11140 residual_grid_placeholder(&levels, side)
11141 } else {
11142 levels
11143 })
11144}
11145
11146/// `record`'s neighbour state only reads whether *the coded grid* (not the
11147/// residual) has nonzero entries, so the levels this function already built
11148/// are what it wants back; this helper exists only to name that clearly at
11149/// the one call site where `tx_side == side`.
11150fn residual_grid_placeholder(levels: &[i32], _tx_side: usize) -> Vec<i32> {
11151 levels.to_vec()
11152}
11153
11154/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
11155/// three planes, reconstructing them into `y`/`u`/`v` and updating
11156/// `neighbours`.
11157#[allow(clippy::too_many_arguments)]
11158fn decode_block(
11159 dec: &mut SymbolDecoder,
11160 cdfs: &mut Cdfs,
11161 neighbours: &mut Neighbours,
11162 at: (usize, usize),
11163 side: usize,
11164 luma_set: TxbSet,
11165 chroma_set: TxbSet,
11166 luma_tx: usize,
11167 chroma_tx: usize,
11168 scans: (&[u16], &[u16]),
11169 cfl: bool,
11170 y: &mut PlaneBuf,
11171 u: &mut PlaneBuf,
11172 v: &mut PlaneBuf,
11173 base_q_idx: u8,
11174 enable_filter_intra: bool,
11175 allow_screen_content_tools: bool,
11176 allow_intrabc: bool,
11177 scan32: &[u16],
11178 scan16: &[u16],
11179 scan8: &[u16],
11180 scan4: &[u16],
11181 tx_select: bool,
11182 reduced_tx_set: bool,
11183) -> Result<()> {
11184 let (r, c) = at;
11185 let (px, py) = (c * SUB, r * SUB);
11186 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
11187 let palette_uv_cache = neighbours.palette_uv_cache(at);
11188 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
11189 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
11190 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
11191 read_intra_mode(
11192 dec,
11193 cdfs,
11194 nb_above_mode,
11195 nb_left_mode,
11196 cfl,
11197 side,
11198 enable_filter_intra,
11199 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
11200 allow_screen_content_tools,
11201 allow_intrabc,
11202 Some((palette_ctx, &palette_cache)),
11203 &palette_uv_cache,
11204 r * (SUB / MI),
11205 c * (SUB / MI),
11206 )?;
11207 if at_tile_left && palette_y.is_some() {
11208 PALETTE_TILE_LEFT_HITS.with(|c| c.set(c.get() + 1));
11209 }
11210 let intrabc_dv = INTRABC_DV.with(|c| c.take());
11211 // libaom `parse_decode_block`: an intrabc block is `inter_block_tx`, so
11212 // under `TX_MODE_SELECT` its transform size comes from the inter var-tx
11213 // partition tree (`read_var_tx_size`), a syntax element this decoder has
11214 // nowhere -- reading the intra `tx_depth` symbol instead would desync.
11215 if intrabc_dv.is_some() && tx_select && !skip {
11216 return Err(unsupported(
11217 "an intrabc block under TxMode::Select (its transform size is coded by the inter var-tx partition tree, which this decoder never reads)",
11218 ));
11219 }
11220 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
11221 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
11222 // actual chroma-from-luma correlation, same as this decoder always did.
11223 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
11224 DC_PRED
11225 } else {
11226 uv_mode
11227 };
11228 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
11229 if smooth_neighbor {
11230 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
11231 }
11232 let smooth_neighbor_uv =
11233 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
11234 if std::env::var_os("EC_AV1_TRACE").is_some() {
11235 eprintln!(
11236 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
11237 angle_delta_uv={angle_delta_uv}"
11238 );
11239 }
11240 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
11241 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
11242 // block, skipped or not. `logical_tx` is what the loop filter's edge
11243 // lookup and the next block's own `tx_size_context` want (the *nominal*
11244 // transform size -- 64 even for the 64x64 corner-scanned case, spec
11245 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
11246 // which only differs from it at that one corner case.
11247 let (logical_tx, coeff_tx_side) = if tx_select {
11248 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, None);
11249 (resolved, if resolved == 64 { 32 } else { resolved })
11250 } else {
11251 // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is
11252 // TX_64X64, so a 128x128 block is always FOUR luma transform units
11253 // even with `tx_select` off -- the TU loop below, never the
11254 // single-unit path.
11255 (side.min(64), luma_tx)
11256 };
11257 if tx_select && logical_tx < side && uv_mode != DC_PRED {
11258 SQ_CHROMA_TX_HITS.with(|c| c.set(c.get() + 1));
11259 }
11260 let luma_set = if tx_select {
11261 txbset_for(logical_tx, reduced_tx_set)
11262 } else {
11263 luma_set
11264 };
11265 let luma_set = if intrabc_dv.is_some() {
11266 txbset_for_inter(logical_tx, reduced_tx_set)
11267 } else {
11268 luma_set
11269 };
11270 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
11271 let reach = Reach::of(side, px, py, y.width, y.height);
11272 let (cpx, cpy) = (px / 2, py / 2);
11273 let chroma_side = side / 2;
11274 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
11275 // frame's own pre-loop-filter reconstruction (all loop filters are off
11276 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
11277 // block vector, with the BILINEAR kernel libaom forces for intrabc --
11278 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
11279 // odd, which is exactly what the bilinear taps then interpolate.
11280 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
11281 let mut yb = vec![0u16; side * side];
11282 mc::predict_with_filter(
11283 &y.data, y.width, y.true_width, y.true_height,
11284 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
11285 side, side, mc::InterpFilterKind::Bilinear, &mut yb,
11286 );
11287 let mut ub = vec![0u16; chroma_side * chroma_side];
11288 mc::predict_with_filter(
11289 &u.data, u.width, u.true_width, u.true_height,
11290 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
11291 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut ub,
11292 );
11293 let mut vb = vec![0u16; chroma_side * chroma_side];
11294 mc::predict_with_filter(
11295 &v.data, v.width, v.true_width, v.true_height,
11296 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
11297 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut vb,
11298 );
11299 (yb, ub, vb)
11300 });
11301 if let Some((yb, _, _)) = &intrabc_bufs {
11302 set_palette_pred(yb.clone());
11303 }
11304 // A palette-Y block's own prediction is the reconstructed colour-index
11305 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
11306 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
11307 // parameter through this function's dozen `y.reconstruct`/`read_plane`
11308 // sites. A split luma transform (`tx_select && logical_tx != side`)
11309 // would need the map sliced per-TU -- untested against a real
11310 // `--enable-palette=1` stream this round, so refuse by name rather than
11311 // guess at the slicing (charter's own named-acceptable fallback).
11312 let palette_y_buf: Option<Vec<u16>> = palette_y.as_ref().map(|py| {
11313 py.map
11314 .iter()
11315 .map(|&idx| py.colors[idx as usize])
11316 .collect()
11317 });
11318 // With one luma transform unit the whole `side`x`side` map is the
11319 // prediction; with several (`logical_tx != side`) each unit takes its own
11320 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
11321 // below (lane-palette2 r7) -- setting the full-block buffer here would be
11322 // taken by the FIRST unit and indexed at the wrong stride.
11323 if let Some(buf) = &palette_y_buf
11324 && logical_tx == side
11325 {
11326 set_palette_pred(buf.clone());
11327 }
11328 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
11329 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
11330 // plane's own `reconstruct`/`read_plane` call below (never both planes at
11331 // once), since Y's own set-then-take already emptied the slot by the time
11332 // either of these run.
11333 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
11334 (
11335 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
11336 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
11337 )
11338 });
11339 // The chroma half of the intrabc prediction rides the same per-plane
11340 // override slot the UV-palette buffers do (set fresh before each plane's
11341 // own `reconstruct`/`read_plane` call below).
11342 let palette_uv_bufs = match &intrabc_bufs {
11343 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
11344 None => palette_uv_bufs,
11345 };
11346 if skip {
11347 // A skipped block codes no residual syntax at all (spec 5.11.34):
11348 // straight prediction, on every plane.
11349 //
11350 // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it
11351 // is skipped (only an INTER skip forces the largest transform), and
11352 // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts
11353 // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units
11354 // already written left/above of it inside this same block. Predicting
11355 // the whole `side`x`side` at once gives a different (uniformly off by
11356 // ~1) answer, which is exactly the residue this lane was chasing.
11357 // The palette/intrabc override path keeps the single-call shape (its
11358 // per-TU windowing is the non-skip loop's own `palette_y_buf` slice,
11359 // untested for skip and unreachable in these streams).
11360 // lane-sb128b r2: a 128x128 block's transform is TX_64X64 even with
11361 // `tx_select` off (`max_txsize_rect_lookup[BLOCK_128X128]`), so the
11362 // per-unit prediction is keyed on the transform being smaller than
11363 // the block, not on the tx-depth syntax. The counter keeps lane-hgkf's
11364 // narrower meaning (a READ split tx depth).
11365 let split_tx_skip =
11366 logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none();
11367 if split_tx_skip {
11368 if tx_select {
11369 SKIP_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
11370 }
11371 let n_axis = side / logical_tx;
11372 for tu_row in 0..n_axis {
11373 for tu_col in 0..n_axis {
11374 let tu_px = px + tu_col * logical_tx;
11375 let tu_py = py + tu_row * logical_tx;
11376 if tu_px >= y.true_width || tu_py >= y.true_height {
11377 continue;
11378 }
11379 let tu_reach = tu_reach(
11380 side,
11381 side,
11382 tu_col * logical_tx,
11383 tu_row * logical_tx,
11384 logical_tx,
11385 reach,
11386 px,
11387 py,
11388 y.width,
11389 y.height,
11390 );
11391 y.reconstruct(
11392 tu_px,
11393 tu_py,
11394 logical_tx,
11395 mode,
11396 angle_delta_y,
11397 tu_reach,
11398 &vec![0i32; logical_tx * logical_tx],
11399 None,
11400 filter_intra,
11401 smooth_neighbor,
11402 );
11403 }
11404 }
11405 } else {
11406 y.reconstruct(
11407 px,
11408 py,
11409 side,
11410 mode,
11411 angle_delta_y,
11412 reach,
11413 &vec![0i32; side * side],
11414 None,
11415 filter_intra,
11416 smooth_neighbor,
11417 );
11418 }
11419 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
11420 let cn = (chroma_side / chroma_tx).max(1);
11421 for cu_row in 0..cn {
11422 for cu_col in 0..cn {
11423 let luma_span = chroma_tx * 2;
11424 let cu_r = if cn == 1 {
11425 reach
11426 } else {
11427 tu_reach(
11428 side, side,
11429 cu_col * luma_span, cu_row * luma_span, luma_span,
11430 reach, px, py, y.width, y.height,
11431 )
11432 };
11433 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
11434 if let Some((ub, _)) = &palette_uv_bufs {
11435 set_palette_pred(ub.clone());
11436 }
11437 u.reconstruct(
11438 cu_x,
11439 cu_y,
11440 chroma_tx,
11441 uv_predict_mode,
11442 angle_delta_uv,
11443 cu_r,
11444 &vec![0i32; chroma_tx * chroma_tx],
11445 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
11446 None,
11447 smooth_neighbor_uv,
11448 );
11449 if let Some((_, vb)) = &palette_uv_bufs {
11450 set_palette_pred(vb.clone());
11451 }
11452 v.reconstruct(
11453 cu_x,
11454 cu_y,
11455 chroma_tx,
11456 uv_predict_mode,
11457 angle_delta_uv,
11458 cu_r,
11459 &vec![0i32; chroma_tx * chroma_tx],
11460 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
11461 None,
11462 smooth_neighbor_uv,
11463 );
11464 }
11465 }
11466 let luma_grid = vec![0i32; side * side];
11467 let u_grid = vec![0i32; chroma_side * chroma_side];
11468 let v_grid = vec![0i32; chroma_side * chroma_side];
11469 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
11470 } else if logical_tx == side {
11471 // lane-sb128b r1: the test used to be `!tx_select || logical_tx == side`.
11472 // Without `tx_select` `logical_tx` IS `side` at every size <= 64, so
11473 // that arm was redundant -- and wrong at 128, where
11474 // `max_txsize_rect_lookup` caps the block's transform at 64 and the
11475 // block is four units whether or not `tx_select` is on.
11476 // A single luma transform unit -- the old path, unchanged (including
11477 // the 64x64 corner case, `logical_tx == side == 64` with
11478 // `coeff_tx_side == 32`).
11479 let around = neighbours.around(at, side);
11480 let luma_grid = read_plane(
11481 dec,
11482 cdfs,
11483 luma_set,
11484 luma_scan,
11485 0,
11486 around[0],
11487 mode,
11488 mode,
11489 angle_delta_y,
11490 reach,
11491 y,
11492 px,
11493 py,
11494 side,
11495 coeff_tx_side,
11496 base_q_idx,
11497 None,
11498 filter_intra,
11499 None,
11500 smooth_neighbor,
11501 )?;
11502 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
11503 // Armed for exactly this block's two chroma reads (see
11504 // [`INTRABC_CHROMA_TX`]); the luma call above just set
11505 // [`LUMA_TX_TYPE`] to the type it coded.
11506 if intrabc_dv.is_some() {
11507 INTRABC_CHROMA_TX.with(|c| c.set(Some(LUMA_TX_TYPE.with(std::cell::Cell::get))));
11508 }
11509 if let Some((ub, _)) = &palette_uv_bufs {
11510 set_palette_pred(ub.clone());
11511 }
11512 let u_grid = read_plane(
11513 dec,
11514 cdfs,
11515 chroma_set,
11516 scans.1,
11517 1,
11518 around[1],
11519 mode,
11520 uv_predict_mode,
11521 angle_delta_uv,
11522 reach,
11523 u,
11524 cpx,
11525 cpy,
11526 chroma_side,
11527 chroma_tx,
11528 base_q_idx,
11529 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
11530 None,
11531 None,
11532 smooth_neighbor_uv,
11533 )?;
11534 if std::env::var_os("EC_AV1_TRACE").is_some() {
11535 eprintln!(
11536 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
11537 &u.data[cpy * u.width + cpx..][..chroma_side]
11538 );
11539 }
11540 if let Some((_, vb)) = &palette_uv_bufs {
11541 set_palette_pred(vb.clone());
11542 }
11543 let v_grid = read_plane(
11544 dec,
11545 cdfs,
11546 chroma_set,
11547 scans.1,
11548 2,
11549 around[2],
11550 mode,
11551 uv_predict_mode,
11552 angle_delta_uv,
11553 reach,
11554 v,
11555 cpx,
11556 cpy,
11557 chroma_side,
11558 chroma_tx,
11559 base_q_idx,
11560 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
11561 None,
11562 None,
11563 smooth_neighbor_uv,
11564 )?;
11565 INTRABC_CHROMA_TX.with(|c| c.set(None));
11566 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
11567 } else {
11568 // Several luma transform units, raster order (spec
11569 // `transform_block`'s loop): the block's resolved transform is
11570 // genuinely smaller than its own side, so each tile of it predicts
11571 // and codes independently, its own context read fresh off whatever
11572 // the earlier tiles in this same block already wrote -- the same
11573 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
11574 let n_axis = side / logical_tx;
11575 let cn = (chroma_side / chroma_tx).max(1);
11576 // libaom's transform-block loop is over 64x64 luma "mu" chunks
11577 // (`decode_token_recon_block`: `mu_blocks_wide/high` =
11578 // `mi_size_wide[BLOCK_64X64]`), and it codes EVERY PLANE of a chunk
11579 // before moving to the next one. Below 128 a block is a single chunk,
11580 // so this is byte-for-byte the all-luma-then-all-chroma order that has
11581 // always run; at 128 the four quadrants interleave Y,U,V per quadrant
11582 // and reading all four luma units first desyncs the tile at the second
11583 // one (lane-sb128b r3, measured against aomdec's `EC_TRACE_COEFF`).
11584 let nchunk = (side / 64).max(1);
11585 // `cn > 1` means the uv plane block is larger than the uv transform,
11586 // which moves libaom's chroma `txb_skip_ctx` offset from 7 to 10.
11587 let chroma_ctx_offset = if cn > 1 { Some(3) } else { None };
11588 let tpc = (n_axis / nchunk).max(1);
11589 let cpc = (cn / nchunk).max(1);
11590 let mut last_grids = [Vec::new(), Vec::new()];
11591 let mut units: Vec<((usize, usize), usize, Vec<i32>, Vec<i32>)> = Vec::new();
11592 for ch_row in 0..nchunk {
11593 for ch_col in 0..nchunk {
11594 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
11595 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
11596 let tu_mi = (
11597 mi_r + tu_row * (logical_tx / MI),
11598 mi_c + tu_col * (logical_tx / MI),
11599 );
11600 let tu_px = px + tu_col * logical_tx;
11601 let tu_py = py + tu_row * logical_tx;
11602 // Same libaom clip as `decode_rect_split`'s loop above; a
11603 // square block only hangs off the frame when the frame's mi
11604 // dimensions are odd at the block's own level.
11605 if tu_px >= y.true_width || tu_py >= y.true_height {
11606 continue;
11607 }
11608 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
11609 // A transform unit inside a block is NOT a block at that
11610 // position (lane-palette2 r12): `Reach::of` granted the
11611 // top-right 8x8 unit of a 16x16 D203 block bottom-left
11612 // pixels libaom refuses outright (`col_off > 0`), which is
11613 // the diagonal wedge seed 46 reconstructed wrong.
11614 let tu_reach = tu_reach(
11615 side,
11616 side,
11617 tu_col * logical_tx,
11618 tu_row * logical_tx,
11619 logical_tx,
11620 reach,
11621 px,
11622 py,
11623 y.width,
11624 y.height,
11625 );
11626 // This transform unit's own bsize (`logical_tx`) is smaller
11627 // than the block it sits in (`side`), so `txb_skip_ctx` is
11628 // the neighbour-magnitude table, not the lone-TU 0 (spec
11629 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
11630 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
11631 if let Some(buf) = &palette_y_buf {
11632 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
11633 let mut window = vec![0u16; logical_tx * logical_tx];
11634 for row in 0..logical_tx {
11635 let src = (tu_row * logical_tx + row) * side + tu_col * logical_tx;
11636 window[row * logical_tx..][..logical_tx]
11637 .copy_from_slice(&buf[src..][..logical_tx]);
11638 }
11639 set_palette_pred(window);
11640 }
11641 let tu_grid = read_plane(
11642 dec,
11643 cdfs,
11644 luma_set,
11645 luma_scan,
11646 0,
11647 tu_around,
11648 mode,
11649 mode,
11650 angle_delta_y,
11651 tu_reach,
11652 y,
11653 tu_px,
11654 tu_py,
11655 logical_tx,
11656 // The unit's own COEFFICIENT grid, half its side at
11657 // TX_64X64 (a 64-point transform codes nothing past 32);
11658 // identical to `logical_tx` at every smaller size
11659 // (lane-sb128b r1).
11660 coeff_tx_side,
11661 base_q_idx,
11662 None,
11663 filter_intra,
11664 Some(tu_skip_ctx),
11665 smooth_neighbor,
11666 )?;
11667 if std::env::var_os("EC_AV1_TRACE").is_some() {
11668 eprintln!(
11669 "TRACE tu_bitpos mi=({},{}) tell={}",
11670 tu_mi.0,
11671 tu_mi.1,
11672 dec.debug_bitpos()
11673 );
11674 }
11675 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
11676 }
11677 }
11678 // CfL is only allowed up to 32x32, i.e. only at `nchunk == 1`, where
11679 // this still runs after every luma unit of the block.
11680 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
11681 // The block's uv plane block is `chroma_side` across but its uv
11682 // transform is `chroma_tx` (`av1_get_max_uv_txsize` =
11683 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[uv_plane_bsize])`):
11684 // identical at every size up to 64x64, but a 128x128 block's 64x64 uv
11685 // plane block adjusts TX_64X64 down to TX_32X32, so each plane is
11686 // FOUR units (lane-sb128b r2) -- one per mu chunk.
11687 for cu_row in ch_row * cpc..(ch_row + 1) * cpc {
11688 for cu_col in ch_col * cpc..(ch_col + 1) * cpc {
11689 // The chroma context arrays are indexed in LUMA mi, so this
11690 // unit's anchor is its own luma quadrant: `chroma_tx` chroma
11691 // pixels span `2 * chroma_tx` luma ones.
11692 let luma_span = chroma_tx * 2;
11693 let cu_mi = (
11694 mi_r + cu_row * (luma_span / MI),
11695 mi_c + cu_col * (luma_span / MI),
11696 );
11697 let cu_around = neighbours.around_mi(cu_mi, luma_span);
11698 let cu_reach = if cn == 1 {
11699 reach
11700 } else {
11701 tu_reach(
11702 side, side,
11703 cu_col * luma_span, cu_row * luma_span, luma_span,
11704 reach, px, py, y.width, y.height,
11705 )
11706 };
11707 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
11708 if let Some((ub, _)) = &palette_uv_bufs {
11709 set_palette_pred(ub.clone());
11710 }
11711 let u_grid = read_plane(
11712 dec, cdfs, chroma_set, scans.1, 1, cu_around[1], mode,
11713 uv_predict_mode, angle_delta_uv, cu_reach, u, cu_x, cu_y,
11714 chroma_tx, chroma_tx, base_q_idx,
11715 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
11716 None, chroma_ctx_offset, smooth_neighbor_uv,
11717 )?;
11718 if let Some((_, vb)) = &palette_uv_bufs {
11719 set_palette_pred(vb.clone());
11720 }
11721 let v_grid = read_plane(
11722 dec, cdfs, chroma_set, scans.1, 2, cu_around[2], mode,
11723 uv_predict_mode, angle_delta_uv, cu_reach, v, cu_x, cu_y,
11724 chroma_tx, chroma_tx, base_q_idx,
11725 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
11726 None, chroma_ctx_offset, smooth_neighbor_uv,
11727 )?;
11728 if cn > 1 {
11729 CHROMA_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
11730 // Immediately, so the NEXT unit of this same block reads
11731 // this one's coefficient context (libaom's chroma
11732 // `txb_skip_ctx` for the second quadrant is 11, i.e. base
11733 // 1 from this left neighbour -- measured against aomdec).
11734 // The same writes are replayed after `record_split_luma`
11735 // below, which would otherwise clobber them whole-block.
11736 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 1, &u_grid);
11737 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 2, &v_grid);
11738 units.push((cu_mi, luma_span, u_grid.clone(), v_grid.clone()));
11739 }
11740 last_grids = [u_grid, v_grid];
11741 }
11742 }
11743 }
11744 }
11745 // Mode/side bookkeeping plus, at `cn == 1`, the whole-plane chroma
11746 // context write; at `cn > 1` the per-unit writes above are what the
11747 // next block reads, so they run after this (last writer wins).
11748 neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&last_grids[0], &last_grids[1]]);
11749 for (cu_mi, luma_span, u_grid, v_grid) in &units {
11750 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 1, u_grid);
11751 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 2, v_grid);
11752 }
11753 }
11754 // Unconditional, `size == 0` for a non-palette block: clears any stale
11755 // neighbour palette state the same way [`Neighbours::record`] always
11756 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
11757 // (the split-luma-TU branch above always refuses before reaching here
11758 // when `palette_y` is `Some`, so it is never live for that branch).
11759 let (py_size, py_colors) = palette_y
11760 .as_ref()
11761 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
11762 neighbours.record_palette_y(at, side, py_size, py_colors);
11763 let (puv_size, puv_colors) = palette_uv
11764 .as_ref()
11765 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
11766 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
11767 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
11768 neighbours.fill_lf_grid(
11769 (r * (SUB / MI), c * (SUB / MI)),
11770 side / MI,
11771 logical_tx as u8,
11772 0,
11773 );
11774 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv);
11775 Ok(())
11776}
11777
11778thread_local! {
11779 /// lane-sb128c r8: INTRA (key-frame) 128x64 blocks decoded at the 128
11780 /// root's HORZ arm, and 64x128 ones at its VERT arm.
11781 pub(crate) static INTRA_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
11782 pub(crate) static INTRA_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
11783 /// Those blocks by resolved intra `tx_depth` (0 = TX_64X64 units,
11784 /// 1 = TX_32X32, 2 = TX_16X16) -- proof the depth symbol is really read.
11785 pub(crate) static INTRA_SB128_DEPTH_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
11786 /// lane-inter128intra r1: the same shapes decoded on the INTER block path
11787 /// (an intra-coded PARTITION_HORZ/VERT half of a 128 superblock inside an
11788 /// inter frame) -- (128x64, 64x128).
11789 pub(crate) static INTRA128_IN_INTER_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
11790}
11791
11792/// [`INTRA128_IN_INTER_HITS`], for a gate's own before/after delta.
11793pub(crate) fn intra128_in_inter_hits() -> [usize; 2] {
11794 INTRA128_IN_INTER_HITS.with(std::cell::Cell::get)
11795}
11796
11797/// [`INTRA_SB128_HORZ_HITS`] / [`INTRA_SB128_VERT_HITS`] /
11798/// [`INTRA_SB128_DEPTH_HITS`], for a gate's own before/after delta.
11799pub(crate) fn intra_sb128_hits() -> (usize, usize, [usize; 3]) {
11800 (
11801 INTRA_SB128_HORZ_HITS.with(std::cell::Cell::get),
11802 INTRA_SB128_VERT_HITS.with(std::cell::Cell::get),
11803 INTRA_SB128_DEPTH_HITS.with(std::cell::Cell::get),
11804 )
11805}
11806
11807/// The 128 root's HORZ/VERT arm on an INTRA frame: ONE 128x64 (HORZ) or
11808/// 64x128 (VERT) intra block (lane-sb128c r8; the inter twin is
11809/// `decode_inter_block`'s own rect path).
11810///
11811/// libaom `decode_block` -> `predict_and_reconstruct_intra_block` per
11812/// transform unit, with the 128-specific geometry:
11813/// * `max_txsize_rect_lookup[BLOCK_128X64]` is TX_64X64, so every luma unit
11814/// is SQUARE and there are at least two of them -- depth 0: 64x64 x2,
11815/// depth 1: 32x32 x8, depth 2: 16x16 x32 (`bsize_to_tx_size_cat` counts
11816/// the `sub_tx_size_map` chain TX_64X64->32->16->8->4, i.e. cat 3, the
11817/// same CDF a 64x64 square block reads).
11818/// * `av1_get_max_uv_txsize` = `av1_get_adjusted_tx_size(
11819/// max_txsize_rect_lookup[BLOCK_64X32])` caps at TX_32X32, so the block's
11820/// 64x32 uv plane block is TWO 32x32 chroma units per plane -- one per
11821/// 64x64 luma "mu" chunk, and `decode_token_recon_block` codes Y, U, V of
11822/// a chunk before moving to the next (the interleave lane-sb128b r3
11823/// measured at the 128x128 NONE root).
11824/// * `get_txb_ctx`: the uv plane block is bigger than the uv transform, so
11825/// chroma `txb_skip_ctx` takes the offset-10 rows (7 + 3).
11826/// No CfL, no filter intra (both cap at 32x32) and no palette
11827/// (`av1_allow_palette` caps at 64x64) exist at this size -- the mode
11828/// reader's own size gates already say so, and the guard below is defensive.
11829#[allow(clippy::too_many_arguments)]
11830fn decode_block_128rect(
11831 dec: &mut SymbolDecoder,
11832 cdfs: &mut Cdfs,
11833 neighbours: &mut Neighbours,
11834 at: (usize, usize),
11835 bw: usize,
11836 bh: usize,
11837 y: &mut PlaneBuf,
11838 u: &mut PlaneBuf,
11839 v: &mut PlaneBuf,
11840 base_q_idx: u8,
11841 enable_filter_intra: bool,
11842 allow_screen_content_tools: bool,
11843 tx_select: bool,
11844 reduced_tx_set: bool,
11845) -> Result<()> {
11846 let (r, c) = at;
11847 let (px, py) = (c * SUB, r * SUB);
11848 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
11849 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
11850 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
11851 let palette_uv_cache = neighbours.palette_uv_cache(at);
11852 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
11853 read_intra_mode_rect(
11854 dec,
11855 cdfs,
11856 nb_above_mode,
11857 nb_left_mode,
11858 // `is_cfl_allowed` caps CFL at 32x32: `uv_mode` comes off the
11859 // 13-symbol no-CFL CDF here, never the 14-symbol one.
11860 false,
11861 true,
11862 bw,
11863 bh,
11864 enable_filter_intra,
11865 neighbours.skip_txfm_ctx(mi_r, mi_c),
11866 allow_screen_content_tools,
11867 Some((palette_ctx, &palette_cache)),
11868 &palette_uv_cache,
11869 mi_r,
11870 mi_c,
11871 )?;
11872 if alpha.is_some() || filter_intra.is_some() || palette_y.is_some() || palette_uv.is_some() {
11873 return Err(unsupported(
11874 "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of \
11875 their size gates caps at 64x64 or below, so none of these symbols exists there)",
11876 ));
11877 }
11878 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
11879 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
11880 if smooth_neighbor {
11881 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
11882 }
11883 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
11884 // spec 5.11.16 `read_tx_size`: read for every intra block, skipped or
11885 // not. `bsize_to_tx_size_cat(BLOCK_128X64)` is 3 (see this fn's doc).
11886 let in_inter = INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some();
11887 let depth = if tx_select {
11888 // lane-inter128intra r1: on an INTER frame `get_tx_size_context` reads
11889 // the real `TXFM_CONTEXT` bands, and compares them against
11890 // `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` -- TX_64X64 for
11891 // every 128-axis block, hence the `min(64)`.
11892 let ctx = if in_inter {
11893 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64))
11894 } else {
11895 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
11896 };
11897 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
11898 } else {
11899 0
11900 };
11901 if depth != 0 {
11902 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
11903 }
11904 INTRA_SB128_DEPTH_HITS.with(|c| {
11905 let mut h = c.get();
11906 h[depth.min(2)] += 1;
11907 c.set(h);
11908 });
11909 let logical_tx = 64 >> depth;
11910 // A 64-point transform codes nothing past its low 32 coefficients.
11911 let coeff_tx_side = logical_tx.min(32);
11912 let luma_set = txbset_for(logical_tx, reduced_tx_set);
11913 let luma_scan = default_scan(coeff_tx_side);
11914 let chroma_tx = 32;
11915 let chroma_scan = default_scan(chroma_tx);
11916 let (cpx, cpy) = (px / 2, py / 2);
11917 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
11918 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
11919 let (nch_x, nch_y) = (bw / 64, bh / 64);
11920 // One 32x32 chroma unit per mu chunk, per plane.
11921 debug_assert_eq!((chroma_w / chroma_tx, chroma_h / chroma_tx), (nch_x, nch_y));
11922 let tpc = 64 / logical_tx;
11923 let zero_tu = vec![0i32; logical_tx * logical_tx];
11924 let zero_cu = vec![0i32; chroma_tx * chroma_tx];
11925 let mut last_grids = [Vec::new(), Vec::new()];
11926 let mut units: Vec<((usize, usize), Vec<i32>, Vec<i32>)> = Vec::new();
11927 for ch_row in 0..nch_y {
11928 for ch_col in 0..nch_x {
11929 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
11930 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
11931 let tu_mi = (
11932 mi_r + tu_row * (logical_tx / MI),
11933 mi_c + tu_col * (logical_tx / MI),
11934 );
11935 let (tu_px, tu_py) = (px + tu_col * logical_tx, py + tu_row * logical_tx);
11936 // libaom clips the transform loop to
11937 // `max_blocks_wide/high`: a unit whose top-left sample is
11938 // outside the frame is never coded.
11939 if tu_px >= y.true_width || tu_py >= y.true_height {
11940 continue;
11941 }
11942 // Edge availability of a unit INSIDE a block, with the
11943 // 128 geometry -- `has_top_right` is false for a block
11944 // whose largest side is > 64, which [`Reach::of_rect`]
11945 // already answered for the block and [`tu_reach`] carries
11946 // down to the units on its own top row.
11947 let tu_r = tu_reach(
11948 bw,
11949 bh,
11950 tu_col * logical_tx,
11951 tu_row * logical_tx,
11952 logical_tx,
11953 reach,
11954 px,
11955 py,
11956 y.width,
11957 y.height,
11958 );
11959 if skip {
11960 y.reconstruct(
11961 tu_px, tu_py, logical_tx, mode, angle_delta_y, tu_r, &zero_tu, None,
11962 None, smooth_neighbor,
11963 );
11964 neighbours.record_mi_luma(tu_mi, logical_tx, &zero_tu);
11965 continue;
11966 }
11967 // The unit is smaller than its block, so `txb_skip_ctx`
11968 // is the neighbour-magnitude table, never the lone-TU 0.
11969 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
11970 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
11971 let tu_grid = read_plane(
11972 dec,
11973 cdfs,
11974 luma_set,
11975 &luma_scan,
11976 0,
11977 tu_around,
11978 mode,
11979 mode,
11980 angle_delta_y,
11981 tu_r,
11982 y,
11983 tu_px,
11984 tu_py,
11985 logical_tx,
11986 coeff_tx_side,
11987 base_q_idx,
11988 None,
11989 None,
11990 Some(tu_skip_ctx),
11991 smooth_neighbor,
11992 )?;
11993 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
11994 }
11995 }
11996 // The chroma context arrays are indexed in LUMA mi, so this
11997 // unit's anchor is its own 64x64 mu chunk.
11998 let luma_span = chroma_tx * 2;
11999 let cu_mi = (
12000 mi_r + ch_row * (luma_span / MI),
12001 mi_c + ch_col * (luma_span / MI),
12002 );
12003 let cu_r = tu_reach(
12004 bw,
12005 bh,
12006 ch_col * luma_span,
12007 ch_row * luma_span,
12008 luma_span,
12009 reach,
12010 px,
12011 py,
12012 y.width,
12013 y.height,
12014 );
12015 let (cu_x, cu_y) = (cpx + ch_col * chroma_tx, cpy + ch_row * chroma_tx);
12016 if skip {
12017 u.reconstruct(
12018 cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r, &zero_cu, None,
12019 None, smooth_neighbor_uv,
12020 );
12021 v.reconstruct(
12022 cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r, &zero_cu, None,
12023 None, smooth_neighbor_uv,
12024 );
12025 continue;
12026 }
12027 let cu_around = neighbours.around_mi(cu_mi, luma_span);
12028 let u_grid = read_plane(
12029 dec, cdfs, TxbSet::Chroma32, &chroma_scan, 1, cu_around[1], mode, uv_predict_mode,
12030 angle_delta_uv, cu_r, u, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, None, None,
12031 Some(3), smooth_neighbor_uv,
12032 )?;
12033 let v_grid = read_plane(
12034 dec, cdfs, TxbSet::Chroma32, &chroma_scan, 2, cu_around[2], mode, uv_predict_mode,
12035 angle_delta_uv, cu_r, v, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, None, None,
12036 Some(3), smooth_neighbor_uv,
12037 )?;
12038 CHROMA_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
12039 // Immediately, so the NEXT unit of this same block reads this
12040 // one's coefficient context; replayed after `record_split_luma_rect`
12041 // below, which would otherwise clobber them whole-block.
12042 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 1, &u_grid);
12043 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 2, &v_grid);
12044 units.push((cu_mi, u_grid.clone(), v_grid.clone()));
12045 last_grids = [u_grid, v_grid];
12046 }
12047 }
12048 if skip {
12049 neighbours.record_rect(
12050 at,
12051 bw,
12052 bh,
12053 mode,
12054 uv_predict_mode,
12055 &[
12056 vec![0i32; bw * bh],
12057 vec![0i32; chroma_w * chroma_h],
12058 vec![0i32; chroma_w * chroma_h],
12059 ],
12060 );
12061 } else {
12062 neighbours.record_split_luma_rect(
12063 at,
12064 bw,
12065 bh,
12066 mode,
12067 uv_predict_mode,
12068 [&last_grids[0], &last_grids[1]],
12069 );
12070 for (cu_mi, u_grid, v_grid) in &units {
12071 neighbours.record_mi_chroma(*cu_mi, 64, 64, 1, u_grid);
12072 neighbours.record_mi_chroma(*cu_mi, 64, 64, 2, v_grid);
12073 }
12074 }
12075 // No palette exists at this size; the unconditional stamp clears any
12076 // stale neighbour palette state, as every other block path does.
12077 neighbours.record_palette_y_rect(at, bw, bh, 0, [0u16; 8]);
12078 neighbours.record_palette_uv_rect(at, bw, bh, 0, [0u16; 8]);
12079 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
12080 neighbours.fill_lf_grid_rect(
12081 (mi_r, mi_c),
12082 bw / MI,
12083 bh / MI,
12084 logical_tx as u8,
12085 logical_tx as u8,
12086 0,
12087 );
12088 if in_inter {
12089 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)`
12090 // (libaom `decodeframe.c` `decode_block`) runs for EVERY block of an
12091 // inter frame, intra ones included: an intra block stamps its
12092 // TRANSFORM size over its own footprint in both TXFM_CONTEXT bands.
12093 // A key frame has no var-tx tree and its readers use the deblock grid,
12094 // so this is the inter path's alone.
12095 txfm_partition_update_rect(
12096 neighbours,
12097 (mi_r, mi_c),
12098 (logical_tx, logical_tx),
12099 (bw, bh),
12100 );
12101 INTRA128_IN_INTER_HITS.with(|c| {
12102 let mut h = c.get();
12103 h[usize::from(bw < bh)] += 1;
12104 c.set(h);
12105 });
12106 } else if bw > bh {
12107 INTRA_SB128_HORZ_HITS.with(|c| c.set(c.get() + 1));
12108 } else {
12109 INTRA_SB128_VERT_HITS.with(|c| c.set(c.get() + 1));
12110 }
12111 Ok(())
12112}
12113
12114
12115/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
12116/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
12117/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
12118/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
12119/// just-decoded mode, not the enclosing slot's stale one, is the true
12120/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
12121/// units, which is what its coefficient context (finer than [`SUB`]) is read
12122/// at. Returns the mode this leaf decoded, for the caller's own
12123/// `prev_leaf`/final mode-writeback bookkeeping.
12124#[allow(clippy::too_many_arguments)]
12125/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
12126/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
12127/// `above_mode[col]`, and its true above neighbour is the mi directly above
12128/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
12129/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
12130/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
12131/// (bottom-right) into both, as this path did, is right only when all four
12132/// leaves happen to share a mode. `done` may be short at the true frame edge
12133/// (the straddle caller filters positions off the frame), so each side falls
12134/// back to the last leaf actually decoded.
12135fn write_back_split_modes(
12136 neighbours: &mut Neighbours,
12137 done: &[((usize, usize), usize)],
12138 parent_mi: (usize, usize),
12139 slot: (usize, usize),
12140) {
12141 let (sr, sc) = slot;
12142 let Some(&(_, last)) = done.last() else {
12143 return;
12144 };
12145 let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m);
12146 neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last);
12147 neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last);
12148}
12149
12150fn decode_leaf8(
12151 dec: &mut SymbolDecoder,
12152 cdfs: &mut Cdfs,
12153 neighbours: &mut Neighbours,
12154 outer_at: (usize, usize),
12155 leaf_mi: (usize, usize),
12156 scans: (&[u16], &[u16]),
12157 prev_leaf: Option<((usize, usize), usize)>,
12158 y: &mut PlaneBuf,
12159 u: &mut PlaneBuf,
12160 v: &mut PlaneBuf,
12161 base_q_idx: u8,
12162 enable_filter_intra: bool,
12163 allow_screen_content_tools: bool,
12164 allow_intrabc: bool,
12165 tx_select: bool,
12166 reduced_tx_set: bool,
12167) -> Result<usize> {
12168 let (r, c) = outer_at;
12169 // lane-modectx r1: the group's own availability-correct fallback pair, not
12170 // the raw coarse bands (which leak across a tile edge -- see
12171 // `modes_above_left`).
12172 let (mut above_mode, mut left_mode) = neighbours.modes_above_left(r, c);
12173 if let Some(((pr, pc), pmode)) = prev_leaf {
12174 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
12175 above_mode = pmode;
12176 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
12177 left_mode = pmode;
12178 }
12179 }
12180 // The mi-exact neighbour wins over both the coarse 16x16 slot and
12181 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
12182 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
12183 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
12184 // lane-rectsplitx r2 swept this arm into
12185 // [`Neighbours::modes_above_left_mi`]: the mi-exact map ALSO has to answer
12186 // "no neighbour" at a tile edge, where the coarse cell holds the block
12187 // above/left of it inside the same 16x16.
12188 let (above_mode, left_mode) =
12189 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
12190 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
12191 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
12192 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
12193 // this leaf's `smooth_neighbor` is built from -- passing `false` here
12194 // filtered a directional chroma block's edge at the wrong strength
12195 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
12196 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
12197 // with the coarse [`SUB`] slot as the fallback when no block recorded
12198 // that exact mi cell.
12199 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
12200 if smooth_neighbor {
12201 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
12202 }
12203 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
12204 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
12205 // `decode_block` caller at 16x16 and up.
12206 // lane-pal8 r1: this leaf's own palette-Y mode ctx and colour cache
12207 // (`av1_get_palette_mode_ctx` / `av1_get_palette_cache`, decodemv.c:567,
12208 // `read_palette_mode_info`), at its REAL mi position -- passing
12209 // `None`/`&[]` read `palette_y_mode` off CDF row 0 and refused by name the
12210 // moment a real 8x8 palette block fired, which is where every 8-bit
12211 // `--tune-content=screen --min-partition-size=8` stream stopped.
12212 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(leaf_mi);
12213 let palette_uv_cache = neighbours.palette_uv_cache_mi(leaf_mi);
12214 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
12215 read_intra_mode(
12216 dec,
12217 cdfs,
12218 above_mode,
12219 left_mode,
12220 true,
12221 8,
12222 enable_filter_intra,
12223 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
12224 allow_screen_content_tools,
12225 allow_intrabc,
12226 Some((palette_ctx, &palette_cache)),
12227 &palette_uv_cache,
12228 leaf_mi.0,
12229 leaf_mi.1,
12230 )?;
12231 // lane-kf900 r7: an 8x8 leaf consumed `use_intrabc` (and its DV) through
12232 // `read_intra_mode` and then decoded the block as if it were ordinary
12233 // intra. libaom's `is_inter_block` counts an intrabc block
12234 // (`blockd.h:373`), so its luma `tx_type` comes off the INTER ext-tx set
12235 // (`av1_get_ext_tx_set_type(TX_8X8, is_inter=1, 0)` = `EXT_TX_SET_ALL16`,
12236 // a 16-symbol CDF) while we read the 7-symbol `TX_SET_INTRA_1` row: the
12237 // same value with a different interval, so the tile desynced at the very
12238 // next symbol (class `wrong-alphabet-same-value`). Everything below
12239 // mirrors `decode_block`'s own intrabc handling at 16x16 and up.
12240 let intrabc_dv = INTRABC_DV.with(|c| c.take());
12241 if intrabc_dv.is_some() {
12242 LEAF8_INTRABC_HITS.with(|c| c.set(c.get() + 1));
12243 }
12244 if intrabc_dv.is_some() && tx_select && !skip {
12245 return Err(unsupported(
12246 "an intrabc block under TxMode::Select (its transform size is coded by the inter var-tx partition tree, which this decoder never reads)",
12247 ));
12248 }
12249 // `av1_visit_palette`'s reconstruction (decodeframe.c:1135): the colour
12250 // index map, mapped through the base colours, IS the block's prediction --
12251 // carried to the next `reconstruct`/`read_plane` through the same
12252 // [`PALETTE_PRED`] slot [`decode_block`] uses at 16x16 and up.
12253 let palette_y_buf: Option<Vec<u16>> = palette_y
12254 .as_ref()
12255 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
12256 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
12257 (
12258 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
12259 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
12260 )
12261 });
12262 let (pal_y_size, pal_y_colors) =
12263 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12264 let (pal_uv_size, pal_uv_colors) =
12265 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12266 if palette_y.is_some() || palette_uv.is_some() {
12267 PALETTE_LEAF8_HITS.with(|c| c.set(c.get() + 1));
12268 }
12269 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
12270 DC_PRED
12271 } else {
12272 uv_mode
12273 };
12274 neighbours.above_uv_mode[c] = uv_predict_mode;
12275 neighbours.left_uv_mode[r] = uv_predict_mode;
12276 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
12277 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
12278 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
12279 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
12280 // transform units, same raster-order per-TU pattern `decode_block`'s
12281 // multi-TU branch runs).
12282 // ... and an intrabc leaf reads no intra `tx_depth` symbol at all: under
12283 // `TX_MODE_SELECT` a skipped inter block takes the largest transform
12284 // (`read_tx_size(.., is_inter=1, ..)`), and the unskipped case is refused
12285 // above.
12286 let resolved = if tx_select && intrabc_dv.is_none() {
12287 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, None)
12288 } else {
12289 8
12290 };
12291 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
12292 let reach = Reach::of(8, px, py, y.width, y.height);
12293 let (cpx, cpy) = (px / 2, py / 2);
12294 // spec 7.11.3.4 with `use_intrabc`, same as `decode_block`: predict from
12295 // the CURRENT frame's own pre-loop-filter reconstruction (every loop
12296 // filter is off whenever `allow_intrabc`, frame.rs:194/210/252/272) at
12297 // the full-pel block vector, with the BILINEAR kernel libaom forces.
12298 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
12299 let mut yb = vec![0u16; 8 * 8];
12300 mc::predict_with_filter(
12301 &y.data, y.width, y.true_width, y.true_height,
12302 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
12303 8, 8, mc::InterpFilterKind::Bilinear, &mut yb,
12304 );
12305 let mut ub = vec![0u16; 4 * 4];
12306 mc::predict_with_filter(
12307 &u.data, u.width, u.true_width, u.true_height,
12308 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
12309 4, 4, mc::InterpFilterKind::Bilinear, &mut ub,
12310 );
12311 let mut vb = vec![0u16; 4 * 4];
12312 mc::predict_with_filter(
12313 &v.data, v.width, v.true_width, v.true_height,
12314 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
12315 4, 4, mc::InterpFilterKind::Bilinear, &mut vb,
12316 );
12317 (yb, ub, vb)
12318 });
12319 // The per-plane prediction override rides the same [`PALETTE_PRED`] slot
12320 // `decode_block` uses: set fresh right before each plane's own
12321 // `reconstruct`/`read_plane` call (the slot is taken, not copied).
12322 if let Some((yb, _, _)) = &intrabc_bufs {
12323 set_palette_pred(yb.clone());
12324 }
12325 let (luma_grid, u_grid, v_grid);
12326 if skip {
12327 // lane-hgkf r2 (same shape as `decode_block`'s own skip branch): an
12328 // 8x8 leaf whose `tx_depth` resolved to TX_4X4 predicts FOUR 4x4
12329 // transform units, each off the units already written left/above of
12330 // it inside this same leaf -- an intra block's transform size is read
12331 // whether or not it is skipped, and spec 7.11.2 predicts per unit.
12332 // A palette block's prediction is the whole-block index map, never
12333 // per-transform-unit edges ([`decode_block`]'s own `split_tx_skip`
12334 // rule) -- so a palette leaf takes the single 8x8 reconstruct below
12335 // even when `tx_depth` resolved to TX_4X4.
12336 if resolved == 4 && palette_y_buf.is_none() {
12337 SKIP_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
12338 for tu_row in 0..2 {
12339 for tu_col in 0..2 {
12340 let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4);
12341 if tu_px >= y.true_width || tu_py >= y.true_height {
12342 continue;
12343 }
12344 let tu_reach = tu_reach(
12345 8,
12346 8,
12347 tu_col * 4,
12348 tu_row * 4,
12349 4,
12350 reach,
12351 px,
12352 py,
12353 y.width,
12354 y.height,
12355 );
12356 y.reconstruct(
12357 tu_px,
12358 tu_py,
12359 4,
12360 mode,
12361 angle_delta_y,
12362 tu_reach,
12363 &vec![0i32; 16],
12364 None,
12365 filter_intra,
12366 smooth_neighbor,
12367 );
12368 }
12369 }
12370 } else {
12371 if let Some(buf) = &palette_y_buf {
12372 set_palette_pred(buf.clone());
12373 }
12374 y.reconstruct(
12375 px,
12376 py,
12377 8,
12378 mode,
12379 angle_delta_y,
12380 reach,
12381 &vec![0i32; 64],
12382 None,
12383 filter_intra,
12384 smooth_neighbor,
12385 );
12386 }
12387 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
12388 if let Some((_, ub, _)) = &intrabc_bufs {
12389 set_palette_pred(ub.clone());
12390 } else if let Some((ub, _)) = &palette_uv_bufs {
12391 set_palette_pred(ub.clone());
12392 }
12393 u.reconstruct(
12394 cpx,
12395 cpy,
12396 4,
12397 uv_predict_mode,
12398 angle_delta_uv,
12399 reach,
12400 &vec![0i32; 16],
12401 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
12402 None,
12403 smooth_neighbor_uv,
12404 );
12405 if let Some((_, _, vb)) = &intrabc_bufs {
12406 set_palette_pred(vb.clone());
12407 } else if let Some((_, vb)) = &palette_uv_bufs {
12408 set_palette_pred(vb.clone());
12409 }
12410 v.reconstruct(
12411 cpx,
12412 cpy,
12413 4,
12414 uv_predict_mode,
12415 angle_delta_uv,
12416 reach,
12417 &vec![0i32; 16],
12418 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
12419 None,
12420 smooth_neighbor_uv,
12421 );
12422 luma_grid = vec![0i32; 64];
12423 u_grid = vec![0i32; 16];
12424 v_grid = vec![0i32; 16];
12425 } else if resolved != 4 {
12426 let around = neighbours.around_mi(leaf_mi, 8);
12427 if let Some(buf) = &palette_y_buf {
12428 set_palette_pred(buf.clone());
12429 }
12430 luma_grid = read_plane(
12431 dec,
12432 cdfs,
12433 if intrabc_dv.is_some() {
12434 txbset_for_inter(8, reduced_tx_set)
12435 } else if reduced_tx_set {
12436 TxbSet::Luma8
12437 } else {
12438 TxbSet::Luma8Set1
12439 },
12440 scans.0,
12441 0,
12442 around[0],
12443 mode,
12444 mode,
12445 angle_delta_y,
12446 reach,
12447 y,
12448 px,
12449 py,
12450 8,
12451 TX8,
12452 base_q_idx,
12453 None,
12454 filter_intra,
12455 None,
12456 smooth_neighbor,
12457 )?;
12458 // `av1_get_tx_type` branches `PLANE_TYPE_UV` on `is_inter_block`, so
12459 // an intrabc block's chroma tx_type is the colocated LUMA transform's
12460 // coded type (lane-kf900 r6's own fix, `decode_block`'s line).
12461 if intrabc_dv.is_some() {
12462 INTRABC_CHROMA_TX.with(|c| c.set(Some(LUMA_TX_TYPE.with(std::cell::Cell::get))));
12463 }
12464 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
12465 if let Some((_, ub, _)) = &intrabc_bufs {
12466 set_palette_pred(ub.clone());
12467 } else if let Some((ub, _)) = &palette_uv_bufs {
12468 set_palette_pred(ub.clone());
12469 }
12470 u_grid = read_plane(
12471 dec,
12472 cdfs,
12473 TxbSet::Chroma4,
12474 scans.1,
12475 1,
12476 around[1],
12477 mode,
12478 uv_predict_mode,
12479 angle_delta_uv,
12480 reach,
12481 u,
12482 cpx,
12483 cpy,
12484 4,
12485 TX4,
12486 base_q_idx,
12487 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
12488 None,
12489 None,
12490 smooth_neighbor_uv,
12491 )?;
12492 if let Some((_, _, vb)) = &intrabc_bufs {
12493 set_palette_pred(vb.clone());
12494 } else if let Some((_, vb)) = &palette_uv_bufs {
12495 set_palette_pred(vb.clone());
12496 }
12497 v_grid = read_plane(
12498 dec,
12499 cdfs,
12500 TxbSet::Chroma4,
12501 scans.1,
12502 2,
12503 around[2],
12504 mode,
12505 uv_predict_mode,
12506 angle_delta_uv,
12507 reach,
12508 v,
12509 cpx,
12510 cpy,
12511 4,
12512 TX4,
12513 base_q_idx,
12514 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
12515 None,
12516 None,
12517 smooth_neighbor_uv,
12518 )?;
12519 // Disarm: `INTRABC_CHROMA_TX` is `Some` across exactly this block's
12520 // two chroma reads (`decode_block`'s own tail does the same) -- left
12521 // set, every later chroma block would inherit this luma tx_type,
12522 // which picks the scan and the inverse transform.
12523 INTRABC_CHROMA_TX.with(|c| c.set(None));
12524 } else {
12525 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
12526 // grid of 4x4 transform units, each predicted from the leaf's own
12527 // 8x8 `mode` and reading its own fresh context off the earlier
12528 // units in this same leaf (the same per-TU pattern `decode_block`'s
12529 // multi-TU branch runs at bigger blocks).
12530 luma_grid = vec![0i32; 64];
12531 for tu_row in 0..2 {
12532 for tu_col in 0..2 {
12533 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
12534 let tu_px = px + tu_col * 4;
12535 let tu_py = py + tu_row * 4;
12536 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
12537 if crate::encode::Reach::in_vert_ab() {
12538 VERT_AB_TX4_HITS.with(|c| c.set(c.get() + 1));
12539 }
12540 let tu_reach = tu_reach(
12541 8,
12542 8,
12543 tu_col * 4,
12544 tu_row * 4,
12545 4,
12546 reach,
12547 px,
12548 py,
12549 y.width,
12550 y.height,
12551 );
12552 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
12553 // Each 4x4 unit predicts from its own window of the block's
12554 // 8x8 colour-index map ([`decode_block`]'s per-TU slice at
12555 // 16x16 and up) -- the whole-block buffer would be taken by
12556 // the FIRST unit and indexed at the wrong stride.
12557 if let Some(buf) = &palette_y_buf {
12558 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
12559 let mut window = vec![0u16; 16];
12560 for row in 0..4 {
12561 let src = (tu_row * 4 + row) * 8 + tu_col * 4;
12562 window[row * 4..][..4].copy_from_slice(&buf[src..][..4]);
12563 }
12564 set_palette_pred(window);
12565 }
12566 let tu_grid = read_plane(
12567 dec,
12568 cdfs,
12569 if reduced_tx_set {
12570 TxbSet::Luma4
12571 } else {
12572 TxbSet::Luma4Set1
12573 },
12574 scans.1,
12575 0,
12576 tu_around,
12577 mode,
12578 mode,
12579 angle_delta_y,
12580 tu_reach,
12581 y,
12582 tu_px,
12583 tu_py,
12584 4,
12585 4,
12586 base_q_idx,
12587 None,
12588 filter_intra,
12589 Some(tu_skip_ctx),
12590 smooth_neighbor,
12591 )?;
12592 if std::env::var_os("EC_AV1_TRACE").is_some() {
12593 eprintln!(
12594 "TRACE tu_bitpos mi=({},{}) tell={}",
12595 tu_mi.0,
12596 tu_mi.1,
12597 dec.debug_bitpos()
12598 );
12599 }
12600 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
12601 }
12602 }
12603 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
12604 let chroma_around = neighbours.around_mi(leaf_mi, 8);
12605 if let Some((ub, _)) = &palette_uv_bufs {
12606 set_palette_pred(ub.clone());
12607 }
12608 u_grid = read_plane(
12609 dec,
12610 cdfs,
12611 TxbSet::Chroma4,
12612 scans.1,
12613 1,
12614 chroma_around[1],
12615 mode,
12616 uv_predict_mode,
12617 angle_delta_uv,
12618 reach,
12619 u,
12620 cpx,
12621 cpy,
12622 4,
12623 TX4,
12624 base_q_idx,
12625 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
12626 None,
12627 None,
12628 smooth_neighbor_uv,
12629 )?;
12630 if let Some((_, vb)) = &palette_uv_bufs {
12631 set_palette_pred(vb.clone());
12632 }
12633 v_grid = read_plane(
12634 dec,
12635 cdfs,
12636 TxbSet::Chroma4,
12637 scans.1,
12638 2,
12639 chroma_around[2],
12640 mode,
12641 uv_predict_mode,
12642 angle_delta_uv,
12643 reach,
12644 v,
12645 cpx,
12646 cpy,
12647 4,
12648 TX4,
12649 base_q_idx,
12650 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
12651 None,
12652 None,
12653 smooth_neighbor_uv,
12654 )?;
12655 // `record_split_luma` expects a `record`-style `(r, c)` position in
12656 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
12657 // already in mi units, so calling it here double-scaled the
12658 // position. Plane 0 is already correct per-TU from the
12659 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
12660 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
12661 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
12662 // leaf's own 8x8 side over `MI`).
12663 let side_mi = 2;
12664 for cell in 0..side_mi {
12665 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
12666 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
12667 }
12668 let round_up_even = |n: usize| n.div_ceil(2) * 2;
12669 let bound_h = round_up_even(neighbours.mi_rows);
12670 let bound_w = round_up_even(neighbours.mi_cols);
12671 let u_state = neighbour_state(&u_grid);
12672 let v_state = neighbour_state(&v_grid);
12673 for cell in 0..side_mi {
12674 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
12675 neighbours.left[leaf_mi.0 + cell][1] = u_state;
12676 neighbours.left[leaf_mi.0 + cell][2] = v_state;
12677 }
12678 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
12679 neighbours.above[leaf_mi.1 + cell][1] = u_state;
12680 neighbours.above[leaf_mi.1 + cell][2] = v_state;
12681 }
12682 }
12683 // This leaf's own palette state into the mi-granular above/left bands
12684 // (sizes 0 when it used none, which is what clears a previous block's
12685 // palette out of the next block's ctx and colour cache).
12686 {
12687 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
12688 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
12689 }
12690 neighbours.fill_skip_grid(leaf_mi, 2, skip);
12691 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0);
12692 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
12693 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv);
12694 return Ok(mode);
12695 }
12696 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
12697 // This leaf's own palette state into the mi-granular above/left bands
12698 // (sizes 0 when it used none, which is what clears a previous block's
12699 // palette out of the next block's ctx and colour cache).
12700 {
12701 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
12702 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
12703 }
12704 INTER8_SKIP_BAND_HITS.with(|c| c.set(c.get() + 1));
12705 neighbours.fill_skip_grid(leaf_mi, 2, skip);
12706 // lane-kf900 r1: the leaf's own RESOLVED transform size, never the literal
12707 // block side. libaom calls `set_txfm_ctxs(mbmi->tx_size, ..., skip_txfm &&
12708 // is_inter_block(mbmi), xd)` (decodemv.c) -- for an INTRA block that skip
12709 // term is always 0, so a skipped 8x8 leaf whose `tx_depth` resolved to
12710 // TX_4X4 still publishes 4 to the next block's `get_tx_size_context`
12711 // (pred_common.h:342). Writing 8 here made the 8x16 strip below the leaf
12712 // read `tx_size_cat1` row 2 where libaom reads row 1 -- same alphabet,
12713 // wrong CDF row, so the msac range diverged mid-frame with no refusal
12714 // (class `wrong-alphabet-same-value`; the ReelB key frame at
12715 // -ss 900, first bad luma sample row 186 col 1803).
12716 neighbours.fill_lf_grid(leaf_mi, 2, resolved as u8, 0);
12717 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
12718 // The DV predictor of a LATER intrabc block is the ordinary `INTRA_FRAME`
12719 // MV stack over this grid (`av1_find_mv_refs`), so an 8x8 leaf has to
12720 // publish its own cells exactly like `decode_block` does.
12721 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv);
12722 Ok(mode)
12723}
12724
12725/// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf
12726/// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8`
12727/// bottom, where no partition symbol is read at all -- `decode_block` runs
12728/// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec
12729/// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always
12730/// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference`
12731/// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf
12732/// of the 2x2 4x4 group carries chroma syntax at all.
12733#[allow(clippy::too_many_arguments)]
12734fn read_intra_mode_sub8(
12735 dec: &mut SymbolDecoder,
12736 cdfs: &mut Cdfs,
12737 above_mode: usize,
12738 left_mode: usize,
12739 has_chroma: bool,
12740 enable_filter_intra: bool,
12741 // [`filter_intra_size_class_rect`] for the LEAF's own shape: 0 for a
12742 // `BLOCK_4X4` split leaf, 8/9 for a 4x8/8x4 rect leaf. Reading the flag
12743 // from the wrong row is the same VALUE with a different interval, so it
12744 // desyncs a block or two later, not here (class `wrong-alphabet-same-value`).
12745 fi_class: usize,
12746 skip_ctx: usize,
12747 allow_intrabc: bool,
12748 mi_r: usize,
12749 mi_c: usize,
12750) -> Result<(bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option<usize>)> {
12751 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
12752 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
12753 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sub8 rng={}", dec.debug_state().0);
12754 }
12755 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
12756 if trace {
12757 eprintln!("TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}", skip as i32, dec.debug_state().0);
12758 }
12759 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
12760 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip);
12761 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip);
12762 if allow_intrabc {
12763 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
12764 if use_intrabc {
12765 return Err(unsupported(
12766 "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)",
12767 ));
12768 }
12769 }
12770 let above_ctx = INTRA_MODE_CTX[above_mode];
12771 let left_ctx = INTRA_MODE_CTX[left_mode];
12772 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
12773 if trace {
12774 eprintln!("TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
12775 }
12776 // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/
12777 // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`,
12778 // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta
12779 // symbol. Reading one consumed a symbol the encoder never wrote and
12780 // desynced the tile at the very next element.
12781 let angle_delta_y = 0;
12782 let chroma = if has_chroma {
12783 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
12784 if trace {
12785 eprintln!("TRACE sub8 uv_mode value={uv_mode} rng={}", dec.debug_state().0);
12786 }
12787 if (9..=12).contains(&uv_mode) {
12788 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
12789 }
12790 let alpha = if uv_mode == UV_CFL_PRED {
12791 Some(read_cfl_alphas(dec, cdfs))
12792 } else {
12793 None
12794 };
12795 if (V_PRED..=D67_PRED).contains(&uv_mode) {
12796 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
12797 }
12798 // See the luma comment above: no angle delta below 8x8.
12799 let angle_delta_uv = 0;
12800 Some((uv_mode, angle_delta_uv, alpha))
12801 } else {
12802 None
12803 };
12804 let mut filter_intra = None;
12805 if mode == DC_PRED && enable_filter_intra {
12806 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0;
12807 if trace {
12808 eprintln!("TRACE sub8 use_filter_intra value={}", use_filter_intra as i32);
12809 }
12810 if use_filter_intra {
12811 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
12812 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
12813 filter_intra = Some(fi_mode);
12814 }
12815 }
12816 Ok((skip, mode, angle_delta_y, chroma, filter_intra))
12817}
12818
12819/// Decodes a `PARTITION_SPLIT` of one 8x8 block into four `BLOCK_4X4` leaves
12820/// (spec `decode_partition`'s recursion bottom), sharing [`decode_leaf8`]'s
12821/// own signature so its caller's `prev_leaf`/`above_mode`/`left_mode`
12822/// bookkeeping needs no change. Each leaf reads its own luma mode info,
12823/// neighboured off the *previously decoded leaf in this same group* on
12824/// whichever axis is adjacent (mirroring [`decode_leaf8`]'s own `prev_leaf`
12825/// pattern, one level deeper); chroma is read and reconstructed exactly
12826/// once, on the last (bottom-right) leaf, at the whole 8x8 group's own 4x4
12827/// chroma unit -- [`read_intra_mode_sub8`]'s doc has the `is_chroma_reference`
12828/// derivation.
12829#[allow(clippy::too_many_arguments)]
12830fn decode_leaf_split4(
12831 dec: &mut SymbolDecoder,
12832 cdfs: &mut Cdfs,
12833 neighbours: &mut Neighbours,
12834 outer_at: (usize, usize),
12835 leaf_mi: (usize, usize),
12836 scan4: &[u16],
12837 prev_leaf: Option<((usize, usize), usize)>,
12838 y: &mut PlaneBuf,
12839 u: &mut PlaneBuf,
12840 v: &mut PlaneBuf,
12841 base_q_idx: u8,
12842 enable_filter_intra: bool,
12843 allow_intrabc: bool,
12844 reduced_tx_set: bool,
12845 // Returns `(below_mode, right_mode)`: the mode a neighbour BELOW this 8x8
12846 // group sees (its bottom-left 4x4, libaom reads mi(row-1, col)) and the
12847 // one a neighbour to its RIGHT sees (its top-right 4x4, mi(row, col-1)).
12848) -> Result<(usize, usize)> {
12849 SUB8_SPLIT_HITS.with(|c| c.set(c.get() + 1));
12850 let (r, c) = outer_at;
12851 let mut above_mode = neighbours.above_mode[c];
12852 let mut left_mode = neighbours.left_mode[r];
12853 if let Some(((pr, pc), pmode)) = prev_leaf {
12854 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
12855 above_mode = pmode;
12856 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
12857 left_mode = pmode;
12858 }
12859 }
12860 // See `decode_leaf8`'s own `smooth_neighbor_uv`: the chroma edge-filter
12861 // type is the chroma neighbours' `uv_mode`, mi-exact where recorded.
12862 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
12863 let mut leaf_modes = [0usize; 4];
12864 let mut leaf_skips = [false; 4];
12865 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
12866 for i in 0..4usize {
12867 let (dr, dc) = (i / 2, i % 2);
12868 let lmi = (leaf_mi.0 + dr, leaf_mi.1 + dc);
12869 // Neighbour modes at real mi granularity: inside the group the
12870 // sibling leaf, outside it the split-leaf map when the adjacent mi
12871 // was itself a 4x4 leaf, else the coarse 16x16 slot (see
12872 // `sub8_mode_col`'s doc).
12873 let leaf_above = if dr == 0 {
12874 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
12875 } else {
12876 leaf_modes[i - 2]
12877 };
12878 let leaf_left = if dc == 0 {
12879 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
12880 } else {
12881 leaf_modes[i - 1]
12882 };
12883 let has_chroma = i == 3;
12884 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
12885 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
12886 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
12887 filter_intra_size_class(4).expect("BLOCK_4X4 has its own filter_intra row"),
12888 skip_ctx, allow_intrabc, lmi.0, lmi.1,
12889 )?;
12890 leaf_modes[i] = mode;
12891 leaf_skips[i] = skip;
12892 neighbours.record_mode_mi(lmi.0, lmi.1, 1, 1, mode);
12893 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
12894 if smooth_neighbor {
12895 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
12896 }
12897 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
12898 let reach = Reach::of(4, px, py, y.width, y.height);
12899 if skip {
12900 y.reconstruct(px, py, 4, mode, angle_delta_y, reach, &vec![0i32; 16], None, filter_intra, smooth_neighbor);
12901 neighbours.record_mi_luma(lmi, 4, &vec![0i32; 16]);
12902 } else {
12903 let tu_around = neighbours.around_mi(lmi, 4)[0];
12904 // A `BLOCK_4X4` leaf's luma TU *is* the whole block, so libaom's
12905 // `get_txb_ctx` takes its `plane_bsize == txsize_to_bsize[tx_size]`
12906 // branch: `txb_skip_ctx = 0`, never the neighbour-magnitude table
12907 // (`txb_common.h:400`). Reading the table here decoded `all_zero`
12908 // off the wrong CDF on the very first leaf and desynced the tile.
12909 let tu_grid = read_plane(
12910 dec,
12911 cdfs,
12912 if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 },
12913 scan4,
12914 0,
12915 tu_around,
12916 mode,
12917 mode,
12918 angle_delta_y,
12919 reach,
12920 y,
12921 px,
12922 py,
12923 4,
12924 4,
12925 base_q_idx,
12926 None,
12927 filter_intra,
12928 None,
12929 smooth_neighbor,
12930 )?;
12931 neighbours.record_mi_luma(lmi, 4, &tu_grid);
12932 }
12933 neighbours.fill_skip_grid(lmi, 1, skip);
12934 neighbours.fill_lf_grid(lmi, 1, 4, 0);
12935 if has_chroma {
12936 last_uv = chroma;
12937 }
12938 }
12939 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
12940 let (cpx, cpy) = (gpx / 2, gpy / 2);
12941 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height);
12942 let (uv_mode, angle_delta_uv, alpha) =
12943 last_uv.expect("i==3 always sets has_chroma, so chroma is always Some");
12944 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
12945 neighbours.above_uv_mode[c] = uv_predict_mode;
12946 neighbours.left_uv_mode[r] = uv_predict_mode;
12947 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
12948 let (u_grid, v_grid): (Vec<i32>, Vec<i32>) = if leaf_skips[3] {
12949 // A skipped chroma block still gets its CfL contribution: libaom's
12950 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
12951 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
12952 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
12953 // added -- `skip_txfm` only drops the residual, never the alpha.
12954 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
12955 // merge keeps one fix and feeds both lanes' counters so neither of
12956 // their gates goes vacuous.
12957 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
12958 if alpha.is_some() {
12959 CHROMA_SKIP_CFL_HITS.with(|h| h.set(h.get() + 1));
12960 SKIP_CFL_HITS.with(|c| c.set(c.get() + 1));
12961 }
12962 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);
12963 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);
12964 (vec![0i32; 16], vec![0i32; 16])
12965 } else {
12966 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
12967 let chroma_around = neighbours.around_mi(leaf_mi, 8);
12968 let ug = read_plane(
12969 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
12970 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
12971 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv,
12972 )?;
12973 let vg = read_plane(
12974 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
12975 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
12976 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv,
12977 )?;
12978 (ug, vg)
12979 };
12980 // Chroma neighbour bookkeeping for the whole 8x8 group -- mirrors
12981 // [`decode_leaf8`]'s own tx4-chroma section (`record_split_luma`'s
12982 // rescaling is wrong for an already-mi-unit position, so this inlines
12983 // its tail directly at `leaf_mi`, side_mi=2), EXCEPT for the partition
12984 // context value itself. Unlike `decode_leaf8`'s TX4 branch (still one
12985 // `BLOCK_8X8`, `PARTITION_NONE`, transform depth only), this group is
12986 // genuinely four `BLOCK_4X4` blocks (`PARTITION_SPLIT` at the 8x8
12987 // level, libaom `decode_partition`'s `bsize2`/`subsize` recursion
12988 // bottom). libaom's `update_ext_partition_context` writes
12989 // `partition_context_lookup[subsize]` at the 8x8 slot -- `{30,30}` for
12990 // `BLOCK_8X8` (bit0=0, what `decode_leaf8` already reproduces via
12991 // side_mi=8) but `{31,31}` for `BLOCK_4X4` (bit0=1) here, and
12992 // `partition_ctx_mi`'s `left_side_mi[mi_r]*2 <= side` needs
12993 // `left_side_mi <= 4` to read that bit as 1. Leaving this at 8 (this
12994 // round's bug) makes the very next sibling 8x8's `partition_w8` read
12995 // with the wrong context and desync immediately.
12996 let side_mi = 2;
12997 for cell in 0..side_mi {
12998 neighbours.left_side_mi[leaf_mi.0 + cell] = 4;
12999 neighbours.above_side_mi[leaf_mi.1 + cell] = 4;
13000 }
13001 let round_up_even = |n: usize| n.div_ceil(2) * 2;
13002 let bound_h = round_up_even(neighbours.mi_rows);
13003 let bound_w = round_up_even(neighbours.mi_cols);
13004 let u_state = neighbour_state(&u_grid);
13005 let v_state = neighbour_state(&v_grid);
13006 for cell in 0..side_mi {
13007 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
13008 neighbours.left[leaf_mi.0 + cell][1] = u_state;
13009 neighbours.left[leaf_mi.0 + cell][2] = v_state;
13010 }
13011 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
13012 neighbours.above[leaf_mi.1 + cell][1] = u_state;
13013 neighbours.above[leaf_mi.1 + cell][2] = v_state;
13014 }
13015 }
13016 Ok((leaf_modes[2], leaf_modes[1]))
13017}
13018
13019/// Decodes a `PARTITION_VERT`/`PARTITION_HORZ` of one 8x8 block into two
13020/// `BLOCK_4X8`/`BLOCK_8X4` leaves (lane-tx4x8), the last partition shape
13021/// below 8x8 this decoder refused. Mirrors [`decode_leaf_split4`] element for
13022/// element -- same mode reads ([`read_intra_mode_sub8`]: no angle delta, no
13023/// tx-depth symbol below 8x8), same "chroma once, on the last sub-block, at
13024/// the whole 8x8 group's 4x4 unit" rule (`is_chroma_reference` is false for
13025/// every sub-block one mi wide or high but the last) -- differing only where
13026/// the shape does:
13027///
13028/// * the transform is a true `TX_4X8`/`TX_8X4`
13029/// ([`dequant_and_inverse_typed_wh`], whose `abs(rect_type) == 1` scale and
13030/// `av1_inv_txfm_shift_ls` row already cover this size pair);
13031/// * the CDF set is [`TxbSet::LumaRect4x8`] (`get_txsize_entropy_ctx` squares
13032/// up to `TX_8X8`) with a 32-position `eob_pt` and the `TX_4X4` `tx_type`
13033/// row -- see that variant's doc comment;
13034/// * the scan is [`SCAN_4X8`]/[`SCAN_8X4`], or their `mrow`/`mcol` siblings
13035/// ([`class_scan_table_wh`]) when the coded `tx_type` is `V_DCT`/`H_DCT`;
13036/// * `Reach` comes from libaom's own `has_tr_4x8`/`has_bl_8x4` rows
13037/// ([`Reach::of_rect`]);
13038/// * `update_partition_context` writes `partition_context_lookup[BLOCK_4X8]`
13039/// = `{31, 30}` (width 4 above, height 8 left), not the `{31, 31}` a
13040/// `BLOCK_4X4` split writes.
13041///
13042/// Filter intra on one of these leaves is decoded (lane-fi8 r1): the flag is
13043/// read from `BLOCK_4X8`/`BLOCK_8X4`'s own `cdf::FILTER_INTRA` row (classes
13044/// 8/9, NOT `BLOCK_4X4`'s), the predictor is [`crate::intra::predict_filter_intra`]
13045/// over the leaf's true `bw`x`bh` -- per 4x4 transform unit, with that unit's
13046/// own edge, when `tx_depth` splits it -- and the coded `tx_type` row is
13047/// [`fi_tx_row`]'s `fimode_to_intradir`, not the block's raw `DC_PRED`.
13048#[allow(clippy::too_many_arguments)]
13049fn decode_leaf_rect8(
13050 dec: &mut SymbolDecoder,
13051 cdfs: &mut Cdfs,
13052 neighbours: &mut Neighbours,
13053 outer_at: (usize, usize),
13054 leaf_mi: (usize, usize),
13055 vert: bool,
13056 scan4: &[u16],
13057 y: &mut PlaneBuf,
13058 u: &mut PlaneBuf,
13059 v: &mut PlaneBuf,
13060 base_q_idx: u8,
13061 enable_filter_intra: bool,
13062 allow_intrabc: bool,
13063 tx_select: bool,
13064 reduced_tx_set: bool,
13065) -> Result<(usize, usize)> {
13066 let (r, c) = outer_at;
13067 // lane-modectx r1: availability-correct fallback pair (see
13068 // `modes_above_left`), not the raw coarse bands.
13069 let (above_mode, left_mode) = neighbours.modes_above_left(r, c);
13070 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
13071 let (bw, bh) = if vert { (4, 8) } else { (8, 4) };
13072 let (w_mi, h_mi) = (bw / MI, bh / MI);
13073 let scan: &[u16] = if vert { &SCAN_4X8 } else { &SCAN_8X4 };
13074 let mut leaf_modes = [0usize; 2];
13075 let mut leaf_skips = [false; 2];
13076 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
13077 for i in 0..2usize {
13078 let lmi = if vert {
13079 (leaf_mi.0, leaf_mi.1 + i)
13080 } else {
13081 (leaf_mi.0 + i, leaf_mi.1)
13082 };
13083 // Inside the pair the sibling is the neighbour on the split axis;
13084 // outside it the mi-granular map, else the coarse 16x16 slot.
13085 let leaf_above = if !vert && i == 1 {
13086 leaf_modes[0]
13087 } else {
13088 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
13089 };
13090 let leaf_left = if vert && i == 1 {
13091 leaf_modes[0]
13092 } else {
13093 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
13094 };
13095 let has_chroma = i == 1;
13096 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
13097 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
13098 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
13099 filter_intra_size_class_rect(bw, bh)
13100 .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize"),
13101 skip_ctx, allow_intrabc, lmi.0, lmi.1,
13102 )?;
13103 if filter_intra.is_some() {
13104 // lane-fi8 r1: `predict_filter_intra` walks its 4x2 patches over
13105 // a true `bw`x`bh` block, so a 4x8/8x4 leaf predicts through the
13106 // same `reconstruct_rect`/`reconstruct` calls below -- and under
13107 // a split transform, per 4x4 unit with that unit's own edge,
13108 // which is exactly what the depth-1 loop already does.
13109 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
13110 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.set(c.get() + 1));
13111 }
13112 // `TxMode::Select`'s `tx_depth` (spec 5.11.16) exists at a 4x8/8x4
13113 // leaf too, and is read for every intra block, skipped or not. Its
13114 // category is libaom's `bsize_to_tx_size_cat(BLOCK_4X8) == 0` --
13115 // `sub_tx_size_map[TX_4X8] == TX_4X4` is a single step, so it is the
13116 // same 2-symbol `tx_size_cat0` an 8x8 uses, not the 3-symbol
13117 // `tx_size_cat2` the 32x16 strips read -- with the rect context
13118 // (`get_tx_size_context`'s `max_tx_wide`/`max_tx_high` = bw/bh).
13119 // Missing this read consumed one symbol fewer than the encoder wrote
13120 // and desynced the tile at the very first rect leaf (class
13121 // `symbol-consumption-gap`).
13122 let depth = if tx_select {
13123 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band
13124 // read every other rect reader now does -- a no-op on a key frame.
13125 let ctx = if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {
13126 tx_size_context_txfm_rect(neighbours, lmi, bw, bh)
13127 } else {
13128 tx_size_context_rect(neighbours, lmi, bw, bh)
13129 };
13130 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
13131 } else {
13132 0
13133 };
13134 if depth != 0 {
13135 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
13136 RECT8_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
13137 }
13138 leaf_modes[i] = mode;
13139 leaf_skips[i] = skip;
13140 neighbours.record_mode_mi(lmi.0, lmi.1, w_mi, h_mi, mode);
13141 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
13142 if smooth_neighbor {
13143 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
13144 }
13145 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
13146 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
13147 // `sub_tx_size_map[TX_4X8] == TX_4X4`: depth 1 splits the leaf into
13148 // two 4x4 transform units along its long axis, each predicted from
13149 // the previous unit's reconstruction and reading its own `txb_skip`
13150 // context -- `decode_leaf8`'s own depth-1 loop, two units instead of
13151 // four. The per-TU path writes its own neighbour state, so the
13152 // block-level write below is skipped for it.
13153 let split = depth != 0;
13154 if split {
13155 let mut done = 0usize;
13156 for tu in 0..2usize {
13157 let tu_mi = if vert {
13158 (lmi.0 + tu, lmi.1)
13159 } else {
13160 (lmi.0, lmi.1 + tu)
13161 };
13162 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);
13163 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
13164 // Same per-TU rule as every other split-transform site
13165 // (lane-palette2 r12): a transform unit inside a block is not
13166 // a block at that position, so its reach comes from the
13167 // block's own row, offset by the unit's position.
13168 let tu_reach = tu_reach(
13169 bw,
13170 bh,
13171 tu_px - px,
13172 tu_py - py,
13173 4,
13174 reach,
13175 px,
13176 py,
13177 y.width,
13178 y.height,
13179 );
13180 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
13181 if skip {
13182 // A skipped leaf still predicts per transform unit: the
13183 // second 4x4 takes its above/left edge from the first
13184 // one's reconstruction, which is NOT what a single 4x8
13185 // prediction of the same mode produces.
13186 let zeros = vec![0i32; 16];
13187 y.reconstruct(
13188 tu_px, tu_py, 4, mode, angle_delta_y, tu_reach, &zeros, None,
13189 filter_intra, smooth_neighbor,
13190 );
13191 neighbours.record_mi_luma(tu_mi, 4, &zeros);
13192 continue;
13193 }
13194 let tu_grid = read_plane(
13195 dec,
13196 cdfs,
13197 if reduced_tx_set {
13198 TxbSet::Luma4
13199 } else {
13200 TxbSet::Luma4Set1
13201 },
13202 scan4,
13203 0,
13204 tu_around,
13205 mode,
13206 mode,
13207 angle_delta_y,
13208 tu_reach,
13209 y,
13210 tu_px,
13211 tu_py,
13212 4,
13213 TX4,
13214 base_q_idx,
13215 None,
13216 filter_intra,
13217 Some(tu_skip_ctx),
13218 smooth_neighbor,
13219 )?;
13220 if tu_grid.iter().any(|&l| l != 0) {
13221 done += 1;
13222 }
13223 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
13224 }
13225 if done > 0 {
13226 if vert {
13227 TX4X8_CODED_HITS.with(|h| h.set(h.get() + 1));
13228 } else {
13229 TX8X4_CODED_HITS.with(|h| h.set(h.get() + 1));
13230 }
13231 }
13232 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
13233 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, 4, 4, 0);
13234 if has_chroma {
13235 last_uv = chroma;
13236 }
13237 continue;
13238 }
13239 let grid = if skip {
13240 let zeros = vec![0i32; bw * bh];
13241 y.reconstruct_rect(
13242 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
13243 smooth_neighbor,
13244 );
13245 zeros
13246 } else {
13247 // `plane_bsize == txsize_to_bsize[tx_size]` here too (the leaf's
13248 // luma TU *is* the leaf), so `get_txb_ctx` fixes `txb_skip_ctx`
13249 // at 0 -- see `decode_leaf_split4`'s own note.
13250 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
13251 let set = if reduced_tx_set {
13252 TxbSet::LumaRect4x8
13253 } else {
13254 TxbSet::LumaRect4x8Set1
13255 };
13256 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
13257 let (levels, tx_type) = read_coeffs_rect(
13258 dec,
13259 &mut coding,
13260 scan,
13261 bw,
13262 bh,
13263 0,
13264 dc_sign_ctx(around.2),
13265 TxType::DctDct,
13266 )?;
13267 if levels.iter().any(|&l| l != 0) {
13268 if vert {
13269 TX4X8_CODED_HITS.with(|h| h.set(h.get() + 1));
13270 } else {
13271 TX8X4_CODED_HITS.with(|h| h.set(h.get() + 1));
13272 }
13273 }
13274 let residual = dequant_and_inverse_typed_wh(
13275 &levels,
13276 bw,
13277 bh,
13278 crate::decode::bit_depth(),
13279 CURRENT_Q_IDX.with(|q| q.get()),
13280 plane_q_delta(0).0,
13281 plane_q_delta(0).1,
13282 tx_type,
13283 );
13284 y.reconstruct_rect(
13285 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
13286 smooth_neighbor,
13287 );
13288 levels
13289 };
13290 // Plane 0's per-TU coefficient context over this leaf's own mi span
13291 // (`record_mi_luma`'s rect twin -- the chroma planes are written once
13292 // for the whole 8x8 group below).
13293 let state = neighbour_state(&grid);
13294 for cell in 0..h_mi {
13295 if lmi.0 + cell < neighbours.mi_rows {
13296 neighbours.left[lmi.0 + cell][0] = state;
13297 }
13298 }
13299 for cell in 0..w_mi {
13300 if lmi.1 + cell < neighbours.mi_cols {
13301 neighbours.above[lmi.1 + cell][0] = state;
13302 }
13303 }
13304 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
13305 let (tx_w, tx_h) = if split { (4, 4) } else { (bw as u8, bh as u8) };
13306 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, tx_w, tx_h, 0);
13307 if has_chroma {
13308 last_uv = chroma;
13309 }
13310 }
13311 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
13312 let (cpx, cpy) = (gpx / 2, gpy / 2);
13313 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height);
13314 let (uv_mode, angle_delta_uv, alpha) =
13315 last_uv.expect("i==1 always sets has_chroma, so chroma is always Some");
13316 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
13317 neighbours.above_uv_mode[c] = uv_predict_mode;
13318 neighbours.left_uv_mode[r] = uv_predict_mode;
13319 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
13320 let (u_grid, v_grid): (Vec<i32>, Vec<i32>) = if leaf_skips[1] {
13321 // A skipped chroma block still gets its CfL contribution: libaom's
13322 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
13323 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
13324 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
13325 // added -- `skip_txfm` only drops the residual, never the alpha.
13326 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
13327 // merge keeps one fix and feeds both lanes' counters so neither of
13328 // their gates goes vacuous.
13329 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
13330 if alpha.is_some() {
13331 CHROMA_SKIP_CFL_HITS.with(|h| h.set(h.get() + 1));
13332 SKIP_CFL_HITS.with(|c| c.set(c.get() + 1));
13333 }
13334 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);
13335 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);
13336 (vec![0i32; 16], vec![0i32; 16])
13337 } else {
13338 let ac = alpha.map(|_| cfl_ac_q3(y, gpx, gpy, 8));
13339 let chroma_around = neighbours.around_mi(leaf_mi, 8);
13340 let ug = read_plane(
13341 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
13342 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
13343 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv,
13344 )?;
13345 let vg = read_plane(
13346 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
13347 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
13348 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv,
13349 )?;
13350 (ug, vg)
13351 };
13352 // `update_partition_context` at the 8x8 level writes
13353 // `partition_context_lookup[subsize]` over the whole 8x8 span: BLOCK_4X8
13354 // is `{31, 30}` (bit0 set on the above half only), BLOCK_8X4 `{30, 31}`
13355 // -- the mirror of `decode_leaf_split4`'s `{31, 31}`, which
13356 // `partition_ctx_mi` reads back off these side values.
13357 for cell in 0..2 {
13358 neighbours.above_side_mi[leaf_mi.1 + cell] = bw;
13359 neighbours.left_side_mi[leaf_mi.0 + cell] = bh;
13360 }
13361 let round_up_even = |n: usize| n.div_ceil(2) * 2;
13362 let bound_h = round_up_even(neighbours.mi_rows);
13363 let bound_w = round_up_even(neighbours.mi_cols);
13364 let u_state = neighbour_state(&u_grid);
13365 let v_state = neighbour_state(&v_grid);
13366 for cell in 0..2usize {
13367 if cell < 2usize.min(bound_h.saturating_sub(leaf_mi.0)) {
13368 neighbours.left[leaf_mi.0 + cell][1] = u_state;
13369 neighbours.left[leaf_mi.0 + cell][2] = v_state;
13370 }
13371 if cell < 2usize.min(bound_w.saturating_sub(leaf_mi.1)) {
13372 neighbours.above[leaf_mi.1 + cell][1] = u_state;
13373 neighbours.above[leaf_mi.1 + cell][2] = v_state;
13374 }
13375 }
13376 // `(below_mode, right_mode)`: the sub-block a neighbour below sees is the
13377 // bottom one (the second under HORZ, the left one under VERT), the one a
13378 // neighbour to the right sees is the top-right (the second under VERT).
13379 Ok(if vert {
13380 (leaf_modes[0], leaf_modes[1])
13381 } else {
13382 (leaf_modes[1], leaf_modes[0])
13383 })
13384}
13385
13386/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
13387/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
13388/// (mod 8) reuse the same table.
13389const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
13390 [(-1, 1), (-2, 2)],
13391 [(0, 1), (-1, 2)],
13392 [(0, 1), (0, 2)],
13393 [(0, 1), (1, 2)],
13394 [(1, 1), (2, 2)],
13395 [(1, 0), (2, 1)],
13396 [(1, 0), (2, 0)],
13397 [(1, 0), (2, -1)],
13398];
13399/// A neighbour tap outside the frame's true extent -- `constrain` reads this
13400/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
13401const CDEF_VERY_LARGE: i32 = 0x4000;
13402const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
13403const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
13404
13405fn cdef_msb(x: i32) -> i32 {
13406 31 - x.leading_zeros() as i32
13407}
13408
13409/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
13410/// centre sample a filter tap is allowed to contribute.
13411fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
13412 if threshold == 0 {
13413 return 0;
13414 }
13415 let shift = (damping - cdef_msb(threshold)).max(0);
13416 diff.signum() * (threshold - (diff.abs() >> shift)).clamp(0, diff.abs())
13417}
13418
13419/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
13420/// direction of an 8x8 luma window and the variance gap between it and its
13421/// orthogonal, `sample(row, col)` reading that window's own pixels.
13422fn cdef_find_dir(coeff_shift: i32, sample: impl Fn(usize, usize) -> i32) -> (usize, i32) {
13423 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
13424 let mut partial = [[0i64; 15]; 8];
13425 for i in 0..8i64 {
13426 for j in 0..8i64 {
13427 // libaom `cdef_find_dir_c`: normalise to an 8-bit sample before
13428 // accumulating, same as `constrain`'s threshold shift below.
13429 let x = i64::from(sample(i as usize, j as usize) >> coeff_shift) - 128;
13430 partial[0][(i + j) as usize] += x;
13431 partial[1][(i + j / 2) as usize] += x;
13432 partial[2][i as usize] += x;
13433 partial[3][(3 + i - j / 2) as usize] += x;
13434 partial[4][(7 + i - j) as usize] += x;
13435 partial[5][(3 - i / 2 + j) as usize] += x;
13436 partial[6][j as usize] += x;
13437 partial[7][(i / 2 + j) as usize] += x;
13438 }
13439 }
13440 let mut cost = [0i64; 8];
13441 for i in 0..8usize {
13442 cost[2] += partial[2][i] * partial[2][i];
13443 cost[6] += partial[6][i] * partial[6][i];
13444 }
13445 cost[2] *= DIV_TABLE[8];
13446 cost[6] *= DIV_TABLE[8];
13447 for i in 0..7usize {
13448 cost[0] += (partial[0][i] * partial[0][i] + partial[0][14 - i] * partial[0][14 - i])
13449 * DIV_TABLE[i + 1];
13450 cost[4] += (partial[4][i] * partial[4][i] + partial[4][14 - i] * partial[4][14 - i])
13451 * DIV_TABLE[i + 1];
13452 }
13453 cost[0] += partial[0][7] * partial[0][7] * DIV_TABLE[8];
13454 cost[4] += partial[4][7] * partial[4][7] * DIV_TABLE[8];
13455 for i in (1..8).step_by(2) {
13456 for j in 0..5usize {
13457 cost[i] += partial[i][3 + j] * partial[i][3 + j];
13458 }
13459 cost[i] *= DIV_TABLE[8];
13460 for j in 0..3usize {
13461 cost[i] += (partial[i][j] * partial[i][j] + partial[i][10 - j] * partial[i][10 - j])
13462 * DIV_TABLE[2 * j + 2];
13463 }
13464 }
13465 let mut best_cost = 0i64;
13466 let mut best_dir = 0usize;
13467 for (i, &c) in cost.iter().enumerate() {
13468 if c > best_cost {
13469 best_cost = c;
13470 best_dir = i;
13471 }
13472 }
13473 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
13474 (best_dir, var as i32)
13475}
13476
13477/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
13478/// (high variance gap) gets more deringing than a flat or non-directional
13479/// one, only ever applied to the luma primary strength.
13480fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
13481 if var == 0 {
13482 return 0;
13483 }
13484 let i = if var >> 6 != 0 {
13485 cdef_msb(var >> 6).min(12)
13486 } else {
13487 0
13488 };
13489 (strength * (4 + i) + 8) >> 4
13490}
13491
13492/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
13493/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
13494/// previously-filtered neighbour must never feed this block's own sum).
13495#[allow(clippy::too_many_arguments)]
13496fn cdef_filter_block(
13497 sample: impl Fn(i32, i32) -> i32,
13498 dst: &mut PlaneBuf,
13499 ox: usize,
13500 oy: usize,
13501 bw: usize,
13502 bh: usize,
13503 pri_strength: i32,
13504 sec_strength: i32,
13505 dir: usize,
13506 pri_damping: i32,
13507 sec_damping: i32,
13508 enable_primary: bool,
13509 enable_secondary: bool,
13510 coeff_shift: i32,
13511) {
13512 let clipping_required = enable_primary && enable_secondary;
13513 // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >>
13514 // coeff_shift) & 1]` -- `pri_strength` (and its `adjust_strength`
13515 // derivative) carries the bit-depth shift, so the tap-set parity bit
13516 // must be read back above that shift, not off the raw low bit.
13517 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
13518 for i in 0..bh {
13519 for j in 0..bw {
13520 let x = sample(i as i32, j as i32);
13521 let mut sum = 0i32;
13522 let mut max = x;
13523 let mut min = x;
13524 for k in 0..2usize {
13525 if enable_primary {
13526 let (tr, tc) = CDEF_DIRECTIONS[dir][k];
13527 let p0 = sample(i as i32 + tr, j as i32 + tc);
13528 let p1 = sample(i as i32 - tr, j as i32 - tc);
13529 sum += pri_taps[k] * cdef_constrain(p0 - x, pri_strength, pri_damping);
13530 sum += pri_taps[k] * cdef_constrain(p1 - x, pri_strength, pri_damping);
13531 if clipping_required {
13532 if p0 != CDEF_VERY_LARGE {
13533 max = max.max(p0);
13534 }
13535 if p1 != CDEF_VERY_LARGE {
13536 max = max.max(p1);
13537 }
13538 min = min.min(p0).min(p1);
13539 }
13540 }
13541 if enable_secondary {
13542 let (tr0, tc0) = CDEF_DIRECTIONS[(dir + 2) & 7][k];
13543 let (tr1, tc1) = CDEF_DIRECTIONS[(dir + 6) & 7][k];
13544 let s0 = sample(i as i32 + tr0, j as i32 + tc0);
13545 let s1 = sample(i as i32 - tr0, j as i32 - tc0);
13546 let s2 = sample(i as i32 + tr1, j as i32 + tc1);
13547 let s3 = sample(i as i32 - tr1, j as i32 - tc1);
13548 if clipping_required {
13549 for s in [s0, s1, s2, s3] {
13550 if s != CDEF_VERY_LARGE {
13551 max = max.max(s);
13552 }
13553 }
13554 min = min.min(s0).min(s1).min(s2).min(s3);
13555 }
13556 sum += CDEF_SEC_TAPS[k]
13557 * (cdef_constrain(s0 - x, sec_strength, sec_damping)
13558 + cdef_constrain(s1 - x, sec_strength, sec_damping)
13559 + cdef_constrain(s2 - x, sec_strength, sec_damping)
13560 + cdef_constrain(s3 - x, sec_strength, sec_damping));
13561 }
13562 }
13563 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
13564 if clipping_required {
13565 y = y.clamp(min, max);
13566 }
13567 dst.data[(oy + i) * dst.width + (ox + j)] = y.clamp(0, sample_max()) as u16;
13568 }
13569 }
13570}
13571
13572/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
13573/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
13574/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
13575/// every block's level comes from [`LoopFilterParams::level`] plus the
13576/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
13577/// `get_filter_level`, precomputed per-block here rather than cached in a
13578/// table the way libaom's `av1_loop_filter_frame_init` does).
13579///
13580/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
13581/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
13582fn apply_deblock(
13583 y: &mut PlaneBuf,
13584 u: &mut PlaneBuf,
13585 v: &mut PlaneBuf,
13586 lf: &LoopFilterParams,
13587 n: &Neighbours,
13588 frame_width: usize,
13589 frame_height: usize,
13590) {
13591 // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel
13592 // mismatch between the raw reconstruction and post-filter output.
13593 if std::env::var_os("EC_AV1_DEBUG_SKIP_DEBLOCK").is_some() {
13594 return;
13595 }
13596 if lf.level[0] != 0 || lf.level[1] != 0 {
13597 deblock_plane(y, 0, lf, n, frame_width, frame_height);
13598 }
13599 if lf.level[2] != 0 {
13600 deblock_plane(u, 1, lf, n, frame_width, frame_height);
13601 }
13602 if lf.level[3] != 0 {
13603 deblock_plane(v, 2, lf, n, frame_width, frame_height);
13604 }
13605}
13606
13607/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
13608/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
13609/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
13610/// mi unit under this decoder's assumed 4:2:0 subsampling).
13611fn plane_to_mi(chroma: bool, coord: usize) -> usize {
13612 if chroma { coord / 2 } else { coord / 4 }
13613}
13614
13615/// This plane's own transform width in pixels at the covering block, spec
13616/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
13617/// width directly; chroma halves it (this decoder's UV transform is always
13618/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
13619/// under 4:2:0 and a block that never splits its own transform).
13620fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
13621 let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid };
13622 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
13623}
13624
13625/// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
13626/// edges step and gate by transform height, which differs from width only
13627/// on rect partition strips.
13628fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
13629 let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid };
13630 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
13631}
13632
13633/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
13634/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
13635/// present only when its neighbour exists inside the true frame -- whether
13636/// the block immediately above (at this block's own leftmost mi column) or
13637/// to the left (at its own topmost mi row) coded a transform at least as wide
13638/// as `own_side`.
13639fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
13640 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side;
13641 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side;
13642 usize::from(above) + usize::from(left)
13643}
13644
13645/// `get_tx_size_context` as libaom actually writes it (`pred_common.h:342`),
13646/// for a block inside an INTER frame: the two `TXFM_CONTEXT` arrays
13647/// ([`Neighbours::above_txfm`]/[`Neighbours::left_txfm`], which only the
13648/// inter path maintains), except that an *inter* neighbour contributes its
13649/// own BLOCK size rather than its transform size -- the two differ the moment
13650/// a neighbour's var-tx tree splits. [`tx_size_context`]'s deblock-grid
13651/// approximation coincides with this only while every neighbour codes one
13652/// whole-block transform, which is exactly what `TxMode::Select` ends.
13653/// [`tx_size_context_txfm`] with the block's own width and height (lane-intrasplit
13654/// r1): `get_tx_size_context` compares the neighbour ABOVE against
13655/// `tx_size_wide[max_txsize_rect_lookup[bsize]]` and the neighbour to the LEFT
13656/// against `tx_size_high[...]` (libaom `pred_common.h:342`), which for a 2:1
13657/// strip are two different numbers. The intra strip inside an inter frame read
13658/// this through [`tx_size_context_rect`] -- the key frame's deblock-grid
13659/// approximation -- so once `TxMode::Select` made the depth symbol exist, it was
13660/// read off the wrong CDF row whenever a neighbour's var-tx tree had split.
13661fn tx_size_context_txfm_rect(
13662 n: &Neighbours,
13663 (mi_r, mi_c): (usize, usize),
13664 own_w: usize,
13665 own_h: usize,
13666) -> usize {
13667 let has_above = mi_r > n.tile_row0_mi;
13668 let has_left = mi_c > n.tile_col0_mi;
13669 let mut above = usize::from(n.above_txfm[mi_c]) >= own_w;
13670 let mut left = usize::from(n.left_txfm[mi_r]) >= own_h;
13671 if has_above && n.above_inter[mi_c] {
13672 above = n.above_side_mi[mi_c] >= own_w;
13673 }
13674 if has_left && n.left_inter[mi_r] {
13675 left = n.left_side_mi[mi_r] >= own_h;
13676 }
13677 if std::env::var_os("EC_TXCTX").is_some() {
13678 eprintln!(
13679 "EC_TXCTX mi={mi_r},{mi_c} own={own_w}x{own_h} ha={has_above} hl={has_left} \
13680 above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \
13681 above={above} left={left}",
13682 n.above_txfm[mi_c],
13683 n.left_txfm[mi_r],
13684 n.above_inter[mi_c],
13685 n.left_inter[mi_r],
13686 n.above_side_mi[mi_c],
13687 n.left_side_mi[mi_r],
13688 );
13689 }
13690 let ctx = match (has_above, has_left) {
13691 (true, true) => usize::from(above) + usize::from(left),
13692 (true, false) => usize::from(above),
13693 (false, true) => usize::from(left),
13694 (false, false) => 0,
13695 };
13696 // lane-midcut r3: count only the blocks the KEY FRAME deblock-grid
13697 // approximation ([`tx_size_context_rect`]) would have read off a DIFFERENT
13698 // CDF row, i.e. exactly the blocks this band read fixes -- a plain "rect
13699 // intra in an inter frame" tally is green on the buggy code too (class
13700 // gate-blind-to-feature).
13701 if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_some() {
13702 let (cw, ch) = (own_w.min(64), own_h.min(64));
13703 let stale = usize::from(has_above && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= cw)
13704 + usize::from(has_left && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= ch);
13705 if ctx != stale {
13706 INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS.with(|c| c.set(c.get() + 1));
13707 }
13708 }
13709 ctx
13710}
13711
13712/// lane-intrasplit r3: `above_inter`/`left_inter` are mi-granular bands (they
13713/// are written and read everywhere else with a raw mi index); the SUB-cell
13714/// division this pair used read a cell four blocks away, so the inter-neighbour
13715/// override above fired on the wrong neighbour -- the first divergence of the
13716/// 10-bit gate's stream was exactly this (`tx_depth` ctx 0 where libaom has 1,
13717/// at the intra block right of an inter one).
13718fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
13719 let has_above = mi_r > n.tile_row0_mi;
13720 let has_left = mi_c > n.tile_col0_mi;
13721 let mut above = usize::from(n.above_txfm[mi_c]) >= side;
13722 let mut left = usize::from(n.left_txfm[mi_r]) >= side;
13723 // lane-angledelta r1 (class [[context-read-from-one-cell]]): both
13724 // `above_inter`/`left_inter` bands are written per MI unit
13725 // (`record_inter_rect_mi`), so they are read per MI too -- the `/ (SUB /
13726 // MI)` here read the 16-px cell's FIRST mi instead, i.e. a different
13727 // block whenever the neighbour column/row is not the cell's first. A
13728 // 16x16 intra block whose left neighbour is an inter block at mi row 4
13729 // then missed libaom's "an inter neighbour contributes its BLOCK size"
13730 // override and read `tx_size_cat1` row 1 where aomdec reads row 2.
13731 if has_above && n.above_inter[mi_c] {
13732 above = n.above_side_mi[mi_c] >= side;
13733 }
13734 if has_left && n.left_inter[mi_r] {
13735 left = n.left_side_mi[mi_r] >= side;
13736 }
13737 if std::env::var_os("EC_TXCTX").is_some() {
13738 eprintln!(
13739 "EC_TXCTX mi={mi_r},{mi_c} own={side} ha={has_above} hl={has_left} \
13740 above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \
13741 above={above} left={left}",
13742 n.above_txfm[mi_c],
13743 n.left_txfm[mi_r],
13744 n.above_inter[mi_c],
13745 n.left_inter[mi_r],
13746 n.above_side_mi[mi_c],
13747 n.left_side_mi[mi_r],
13748 );
13749 }
13750 match (has_above, has_left) {
13751 (true, true) => usize::from(above) + usize::from(left),
13752 (true, false) => usize::from(above),
13753 (false, true) => usize::from(left),
13754 (false, false) => 0,
13755 }
13756}
13757
13758/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
13759/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
13760/// the transform's own side in pixels (`side >> depth`) -- this decoder's
13761/// four square categories (8/16/32/64) each halve at most twice, matching
13762/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
13763fn read_tx_size(
13764 dec: &mut SymbolDecoder,
13765 cdfs: &mut Cdfs,
13766 n: &Neighbours,
13767 at_mi: (usize, usize),
13768 side: usize,
13769 // lane-txselect: `get_tx_size_context`'s real context, for the callers
13770 // that have one -- see [`tx_size_context_txfm`]. `None` keeps the
13771 // key-frame path's own deblock-grid approximation.
13772 ctx_override: Option<usize>,
13773) -> usize {
13774 // `max_txsize_rect_lookup[bsize]` (libaom `read_selected_tx_size` /
13775 // `get_tx_size_context`): a block wider than 64 still tops out at
13776 // TX_64X64, so BLOCK_128X128 reads BLOCK_64X64's own category (its depth
13777 // chain 64->32->16->8->4 is the same four steps) and resolves against 64,
13778 // never against its own 128 side (lane-sb128b r1).
13779 let max_tx = side.min(64);
13780 let ctx = ctx_override.unwrap_or_else(|| tx_size_context(n, at_mi, max_tx));
13781 let depth = match max_tx {
13782 8 => {
13783 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
13784 }
13785 16 => {
13786 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
13787 }
13788 32 => {
13789 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
13790 }
13791 64 => {
13792 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
13793 }
13794 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64/128"),
13795 };
13796 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
13797 let (rng, _) = dec.debug_state();
13798 let (mi_r, mi_c) = at_mi;
13799 eprintln!(
13800 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={depth} ctx={ctx} rng={rng}"
13801 );
13802 }
13803 if depth != 0 {
13804 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
13805 }
13806 max_tx >> depth
13807}
13808
13809/// `txfm_partition_context` (libaom `av1_common_int.h`): an inter block's
13810/// `txfm_split` context -- a category from the block's own largest square
13811/// transform and whether this unit already sits below it, times three, plus
13812/// the two neighbour terms (whether the transform last written above/left of
13813/// this unit is narrower/shorter than the unit itself).
13814fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize {
13815 txfm_partition_ctx_rect(above_px, left_px, blk_max_px, tx_px, tx_px)
13816}
13817
13818/// [`txfm_partition_ctx`] for a *rectangular* transform (lane-inter4 r2):
13819/// libaom's `txfm_partition_context` compares the above context against
13820/// `tx_size_wide` and the left one against `tx_size_high`, and takes its
13821/// category from `txsize_sqr_up_map[tx_size]` -- all three collapse to one
13822/// side for a square transform, which is why the square form above is a
13823/// special case of this one.
13824fn txfm_partition_ctx_rect(
13825 above_px: u8,
13826 left_px: u8,
13827 blk_max_px: usize,
13828 tx_w: usize,
13829 tx_h: usize,
13830) -> usize {
13831 let above = usize::from(usize::from(above_px) < tx_w);
13832 let left = usize::from(usize::from(left_px) < tx_h);
13833 let tx_px = tx_w.max(tx_h);
13834 // `get_sqr_tx_size(max(block_size_wide, block_size_high))`, capped at the
13835 // largest transform (`TX_64X64`); `TX_4X4`..`TX_64X64` index as
13836 // `log2(px) - 2`.
13837 let max_tx = blk_max_px.min(64);
13838 let max_idx = max_tx.trailing_zeros() as usize - 2;
13839 let category = usize::from(tx_px != max_tx && max_tx > 8) + (4 - max_idx) * 2;
13840 category * 3 + above + left
13841}
13842
13843/// `txfm_partition_update` (libaom `av1_common_int.h`): once a var-tx unit
13844/// resolves, every mi cell its *parent* unit (`txb_px`) spans records the
13845/// resolved transform's own size.
13846fn txfm_partition_update(
13847 n: &mut Neighbours,
13848 at_mi: (usize, usize),
13849 tx_px: usize,
13850 txb_px: usize,
13851) {
13852 txfm_partition_update_rect(n, at_mi, (tx_px, tx_px), (txb_px, txb_px));
13853}
13854
13855/// [`txfm_partition_update`] for a rectangular transform (lane-inter4 r2):
13856/// the left column records `tx_size_high` over the parent's own height and
13857/// the above row records `tx_size_wide` over its width.
13858/// libaom `set_txfm_ctxs` + `txfm_partition_update` (`decodeframe.c`, end of
13859/// `decode_token_recon_block`): EVERY block of an inter frame publishes its
13860/// TRANSFORM size into both `TXFM_CONTEXT` bands, intra blocks included. The
13861/// key frame writes neither (its readers use the deblock grid), so the
13862/// key-frame bodies reused by [`decode_intra_rect_in_inter`] have to do it
13863/// themselves when they run inside an inter frame. The 2:1 and 16x4 arms do it
13864/// at the call site (the transform size comes back to them); the 1:4 arms
13865/// ([`decode_block_rect4`] / [`decode_block_rect64`]) keep their size inside,
13866/// so they call this where their own depth resolves. A no-op on a key frame
13867/// ([`INTRA_IN_INTER_MODE`] unset), where those bands are not read at all.
13868///
13869/// lane-t900 r1 root cause: the HORZ_4 32x8 intra strip at mi(0,312) of an
13870/// inter frame left `left_txfm[0]` at a stale 32 where libaom's own
13871/// `set_txfm_ctxs` writes 8, so the intra 8x16 block at mi(0,320) read
13872/// `tx_size_cat1` row 1 instead of row 0 -- same depth VALUE, different CDF,
13873/// range 39156 where the reference has 54736 (class tx-grid-published-block-side
13874/// / early-return-skips-tail).
13875fn publish_txfm_bands_if_in_inter(
13876 n: &mut Neighbours,
13877 at_mi: (usize, usize),
13878 (tx_w, tx_h): (usize, usize),
13879 (bw, bh): (usize, usize),
13880) {
13881 if INTRA_IN_INTER_MODE.with(std::cell::Cell::get).is_none() {
13882 return;
13883 }
13884 let (mi_r, mi_c) = at_mi;
13885 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
13886 for i in 0..bw / MI {
13887 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
13888 *cell = tx_w as u8;
13889 }
13890 }
13891 for i in 0..bh / MI {
13892 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
13893 *cell = tx_h as u8;
13894 }
13895 }
13896}
13897
13898fn txfm_partition_update_rect(
13899 n: &mut Neighbours,
13900 (mi_r, mi_c): (usize, usize),
13901 (tx_w, tx_h): (usize, usize),
13902 (txb_w, txb_h): (usize, usize),
13903) {
13904 if std::env::var_os("EC_TXUPD").is_some() {
13905 eprintln!("EC_TXUPD rect mi=({},{}) tx=({tx_w},{tx_h}) txb=({txb_w},{txb_h})", mi_r, mi_c);
13906 }
13907 for i in 0..txb_h / MI {
13908 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
13909 *cell = tx_h as u8;
13910 }
13911 }
13912 for i in 0..txb_w / MI {
13913 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
13914 *cell = tx_w as u8;
13915 }
13916 }
13917}
13918
13919/// `set_txfm_ctxs` (libaom `av1_common_int.h`): the non-var-tx write of the
13920/// same contexts -- a skipped *inter* block records its own block size rather
13921/// than its transform size.
13922fn set_txfm_ctxs(
13923 n: &mut Neighbours,
13924 (mi_r, mi_c): (usize, usize),
13925 tx_px: usize,
13926 w_mi: usize,
13927 h_mi: usize,
13928 skip_inter: bool,
13929) {
13930 if std::env::var_os("EC_TXUPD").is_some() {
13931 eprintln!("EC_TXUPD ctxs mi=({mi_r},{mi_c}) tx={tx_px} wh=({w_mi},{h_mi}) skip_inter={skip_inter}");
13932 }
13933 let bw = if skip_inter { w_mi * MI } else { tx_px };
13934 let bh = if skip_inter { h_mi * MI } else { tx_px };
13935 for i in 0..w_mi {
13936 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
13937 *cell = bw as u8;
13938 }
13939 }
13940 for i in 0..h_mi {
13941 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
13942 *cell = bh as u8;
13943 }
13944 }
13945}
13946
13947/// The value libaom initialises both transform contexts to -- NOT zero:
13948/// `av1_zero_above_context` memsets the txfm row to
13949/// `tx_size_wide[TX_SIZES_LARGEST]` and `av1_zero_left_context` does the same
13950/// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64
13951/// pixels, so an unwritten neighbour reads as the *widest* possible
13952/// transform, not the narrowest.
13953const TXFM_CTX_INIT: u8 = 64;
13954
13955/// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most
13956/// twice below its own largest transform.
13957const MAX_VARTX_DEPTH: usize = 2;
13958
13959/// libaom `sub_tx_size_map[TX_SIZES_ALL]` (`common_data.c`): the transform
13960/// one `txfm_split` step below `tx_size`. RECTANGULAR for the 1:4 shapes
13961/// (`[TX_64X16] == TX_32X16`, `[TX_16X64] == TX_16X32`) and for the 4:1
13962/// small ones, square everywhere else.
13963fn sub_tx_size_map(tx_w: usize, tx_h: usize) -> (usize, usize) {
13964 match (tx_w, tx_h) {
13965 (4, 4) => (4, 4),
13966 (8, 8) => (4, 4),
13967 (16, 16) => (8, 8),
13968 (32, 32) => (16, 16),
13969 (64, 64) => (32, 32),
13970 (4, 8) | (8, 4) => (4, 4),
13971 (8, 16) | (16, 8) => (8, 8),
13972 (16, 32) | (32, 16) => (16, 16),
13973 (32, 64) | (64, 32) => (32, 32),
13974 (4, 16) => (4, 8),
13975 (16, 4) => (8, 4),
13976 (8, 32) => (8, 16),
13977 (32, 8) => (16, 8),
13978 (16, 64) => (16, 32),
13979 (64, 16) => (32, 16),
13980 _ => unreachable!("not a TX_SIZES_ALL shape: {tx_w}x{tx_h}"),
13981 }
13982}
13983
13984#[test]
13985fn sub_tx_size_map_matches_libaom() {
13986 // libaom `common_data.c` `sub_tx_size_map`, in TX_SIZES_ALL order.
13987 const TABLE: [((usize, usize), (usize, usize)); 19] = [
13988 ((4, 4), (4, 4)), ((8, 8), (4, 4)), ((16, 16), (8, 8)), ((32, 32), (16, 16)),
13989 ((64, 64), (32, 32)), ((4, 8), (4, 4)), ((8, 4), (4, 4)), ((8, 16), (8, 8)),
13990 ((16, 8), (8, 8)), ((16, 32), (16, 16)), ((32, 16), (16, 16)), ((32, 64), (32, 32)),
13991 ((64, 32), (32, 32)), ((4, 16), (4, 8)), ((16, 4), (8, 4)), ((8, 32), (8, 16)),
13992 ((32, 8), (16, 8)), ((16, 64), (16, 32)), ((64, 16), (32, 16)),
13993 ];
13994 for (tx, want) in TABLE {
13995 assert_eq!(sub_tx_size_map(tx.0, tx.1), want, "sub_tx_size_map({tx:?})");
13996 }
13997}
13998
13999/// `read_var_tx_size` (spec 5.11.17, libaom `decodeframe.c`
14000/// `read_tx_size_vartx`): the recursive `txfm_split` tree of one
14001/// max-transform-sized unit of an inter block, collecting the resolved leaf
14002/// transform units into `out` as `(row offset, col offset, side)` in mi units
14003/// -- exactly the order `decode_reconstruct_tx` later reads their
14004/// coefficients in. `blk_row`/`blk_col` are mi offsets inside the block;
14005/// `max_w_mi`/`max_h_mi` clip it to the true frame edge (`max_block_wide`/
14006/// `max_block_high`).
14007#[allow(clippy::too_many_arguments)]
14008fn read_var_tx_size(
14009 dec: &mut SymbolDecoder,
14010 cdfs: &mut Cdfs,
14011 n: &mut Neighbours,
14012 at_mi: (usize, usize),
14013 blk_max_px: usize,
14014 (max_w_mi, max_h_mi): (usize, usize),
14015 (tx_w, tx_h): (usize, usize),
14016 depth: usize,
14017 blk_row: usize,
14018 blk_col: usize,
14019 out: &mut Vec<(usize, usize, usize, usize)>,
14020) {
14021 if blk_row >= max_h_mi || blk_col >= max_w_mi {
14022 return;
14023 }
14024 let unit = (at_mi.0 + blk_row, at_mi.1 + blk_col);
14025 if depth == MAX_VARTX_DEPTH {
14026 out.push((blk_row, blk_col, tx_w, tx_h));
14027 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
14028 return;
14029 }
14030 let ctx = txfm_partition_ctx_rect(
14031 n.above_txfm[unit.1],
14032 n.left_txfm[unit.0],
14033 blk_max_px,
14034 tx_w,
14035 tx_h,
14036 );
14037 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
14038 TXFM_SPLIT_READS.with(|c| c.set(c.get() + 1));
14039 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
14040 let (rng, _) = dec.debug_state();
14041 eprintln!(
14042 "EC_ISTEP mi_row={} mi_col={} name=txfm_split val={} ctx={ctx} rng={rng}",
14043 unit.0,
14044 unit.1,
14045 u8::from(split)
14046 );
14047 }
14048 if !split {
14049 out.push((blk_row, blk_col, tx_w, tx_h));
14050 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
14051 return;
14052 }
14053 TXFM_SPLIT_HITS.with(|c| c.set(c.get() + 1));
14054 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
14055 if (sub_w, sub_h) == (4, 4) {
14056 // libaom's `sub_txs == TX_4X4` early return: every mi cell of the
14057 // unit is marked 4x4 (raster order) without recursing.
14058 for row in 0..tx_h / MI {
14059 for col in 0..tx_w / MI {
14060 if blk_row + row < max_h_mi && blk_col + col < max_w_mi {
14061 out.push((blk_row + row, blk_col + col, 4, 4));
14062 }
14063 }
14064 }
14065 txfm_partition_update_rect(n, unit, (4, 4), (tx_w, tx_h));
14066 return;
14067 }
14068 for row in (0..tx_h / MI).step_by(sub_h / MI) {
14069 for col in (0..tx_w / MI).step_by(sub_w / MI) {
14070 read_var_tx_size(
14071 dec,
14072 cdfs,
14073 n,
14074 at_mi,
14075 blk_max_px,
14076 (max_w_mi, max_h_mi),
14077 (sub_w, sub_h),
14078 depth + 1,
14079 blk_row + row,
14080 blk_col + col,
14081 out,
14082 );
14083 }
14084 }
14085}
14086
14087/// `read_block_tx_size` (libaom `decodeframe.c` `parse_decode_block`'s tx
14088/// branch): every block of a `TxMode::Select` inter frame codes its transform
14089/// size right after its own mode info -- an inter non-skip block through the
14090/// recursive var-tx tree ([`read_var_tx_size`], whose leaf list this returns),
14091/// every other block through the intra `tx_depth` symbol (a skipped inter
14092/// block codes no symbol at all) plus a `set_txfm_ctxs` write. Returns the
14093/// block's own resolved transform side and the leaf list, the latter only
14094/// when the tree resolved to more than one transform unit.
14095#[allow(clippy::too_many_arguments)]
14096fn read_block_tx_size(
14097 dec: &mut SymbolDecoder,
14098 cdfs: &mut Cdfs,
14099 n: &mut Neighbours,
14100 at_mi: (usize, usize),
14101 side: usize,
14102 (mi_cols, mi_rows): (usize, usize),
14103 is_inter: bool,
14104 skip: bool,
14105) -> Result<(usize, Option<Vec<(usize, usize, usize, usize)>>)> {
14106 if !TX_SELECT_INTER.with(std::cell::Cell::get) {
14107 // lane-sb128c r1: `max_txsize_rect_lookup[BLOCK_128X128]` is TX_64X64,
14108 // so a 128x128 inter block is FOUR luma units even with `tx_mode ==
14109 // TX_MODE_LARGEST` -- the same leaf shape the var-tx tree hands back.
14110 // lane-sb128c r3: intra too -- an INTRA 128x128 block under
14111 // `TX_MODE_LARGEST` also resolves to TX_64X64, i.e. four luma units.
14112 if side > 64 {
14113 let step = 64 / MI;
14114 let mut leaves = Vec::new();
14115 for row in (0..side / MI).step_by(step) {
14116 for col in (0..side / MI).step_by(step) {
14117 leaves.push((row, col, 64, 64));
14118 }
14119 }
14120 return Ok((64, Some(leaves)));
14121 }
14122 return Ok((side, None));
14123 }
14124 let side_mi = side / MI;
14125 if is_inter && !skip {
14126 let max_tx = side.min(64);
14127 let max_w_mi = side_mi.min(mi_cols.saturating_sub(at_mi.1));
14128 let max_h_mi = side_mi.min(mi_rows.saturating_sub(at_mi.0));
14129 let mut leaves = Vec::new();
14130 let step = max_tx / MI;
14131 for row in (0..side_mi).step_by(step) {
14132 for col in (0..side_mi).step_by(step) {
14133 read_var_tx_size(
14134 dec,
14135 cdfs,
14136 n,
14137 at_mi,
14138 side,
14139 (max_w_mi, max_h_mi),
14140 (max_tx, max_tx),
14141 0,
14142 row,
14143 col,
14144 &mut leaves,
14145 );
14146 }
14147 }
14148 let single = leaves.len() == 1 && leaves[0].2 == side && leaves[0].3 == side;
14149 // lane-sb128c r6: below the 128 root the ceiling is main's TX_32X32
14150 // ([`inter_txbset_for`] has no 64-point *inter* table set); a 128x128
14151 // block's own var-tx tree legitimately bottoms out at TX_64X64 leaves,
14152 // which the mu-chunk reader above codes as their 32x32 coded corner.
14153 let leaf_ceiling = if side > 64 { 64 } else { 32 };
14154 if !single && leaves.iter().any(|leaf| leaf.2.max(leaf.3) > leaf_ceiling) {
14155 // Only a block wider than a superblock's own 64x64 max transform
14156 // reaches here; this crate has no 64-point *inter* coefficient
14157 // table set ([`inter_txbset_for`] stops at 32).
14158 return Err(unsupported(
14159 "an inter var-tx tree with a leaf transform larger than 32x32",
14160 ));
14161 }
14162 let resolved = leaves.last().map_or(side, |l| l.2);
14163 return Ok((resolved, (!single).then_some(leaves)));
14164 }
14165 let tx = if is_inter {
14166 side.min(64)
14167 } else {
14168 read_tx_size(
14169 dec,
14170 cdfs,
14171 n,
14172 at_mi,
14173 side,
14174 // lane-sb128c r3: `get_tx_size_context` compares the neighbour txfm
14175 // contexts against `tx_size_wide[max_txsize_rect_lookup[bsize]]`,
14176 // which is 64 for BLOCK_128X128 -- never the block's own 128 side.
14177 Some(tx_size_context_txfm(n, at_mi, side.min(64))),
14178 )
14179 };
14180 set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter);
14181 if !is_inter && tx != side {
14182 // lane-intrainter r1: an intra block inside an inter frame whose
14183 // `tx_depth` split its luma transform codes exactly the key-frame
14184 // split path's transform units (`decode_block`'s multi-TU loop),
14185 // raster order over the block. Handed back in the same leaf shape the
14186 // inter var-tx tree uses, so the caller's per-TU luma loop, the
14187 // `record_split_luma` neighbour write-back and the per-TU deblock
14188 // edges are the ones it already runs for a var-tx inter block. A
14189 // caller that has no per-TU intra loop (the 8x8 leaf) refuses on
14190 // seeing `Some` here.
14191 let step = tx / MI;
14192 let mut leaves = Vec::new();
14193 for row in (0..side_mi).step_by(step) {
14194 for col in (0..side_mi).step_by(step) {
14195 leaves.push((row, col, tx, tx));
14196 }
14197 }
14198 INTRA_IN_INTER_SPLIT_TX_HITS.with(|c| {
14199 let mut h = c.get();
14200 h[(side.trailing_zeros() as usize).saturating_sub(3).min(3)] += 1;
14201 c.set(h);
14202 });
14203 return Ok((tx, Some(leaves)));
14204 }
14205 Ok((tx, None))
14206}
14207
14208/// lane-inter4 r2: the shapes whose *rectangular inter* residual this
14209/// decoder codes -- a 2:1 strip whose own max rect transform
14210/// (`max_txsize_rect_lookup[BLOCK_32X16] == TX_32X16`) has both a
14211/// coefficient table set ([`TxbSet::LumaRect32x16Inter`], 512-coefficient
14212/// `eob_pt`) and a `tx_type` alphabet here. 64x32/64x16 strips would need a
14213/// 64-point rect transform, and 16x8/8x16 needs
14214/// `default_inter_ext_tx_cdf[2][TX_8X8]` (the 12-symbol
14215/// `DTT9_IDTX_1DDCT` row at `tx_size_sqr == TX_8X8`, only reachable through a
14216/// rect transform), neither of which exists yet -- both stay refused by name.
14217fn rect_inter_residual_supported(w: usize, h: usize) -> bool {
14218 matches!(
14219 (w, h),
14220 // 2:1 strips whose transform is coded in full (lane-inter4).
14221 (32, 16) | (16, 32) | (16, 8) | (8, 16)
14222 // lane-inter16ab r2: the 16x16-level 1:4 strips. TX_16X4/TX_4X16
14223 // codes all 64 of its positions, and its chroma pair is an 8x4 /
14224 // 4x8 unit (`ss_size_lookup[BLOCK_16X4]` = BLOCK_8X4).
14225 | (16, 4) | (4, 16)
14226 // lane-r14 r2: strips with a 64-px axis. `av1_get_max_eob` codes
14227 // only the low 32 coefficients of a 64-length axis, so these read
14228 // exactly the truncated corner the INTRA superblock-strip path
14229 // already reads (`read_intra_mode_rect`), through
14230 // `av1_get_adjusted_tx_size`'s CDF set. Their `tx_size_sqr_up` is
14231 // `TX_64X64`, so `av1_get_ext_tx_set_type` is `DCT_ONLY` and no
14232 // `tx_type` symbol is coded at all.
14233 | (64, 32) | (32, 64) | (64, 16) | (16, 64)
14234 // lane-inter16ab r4: `sub_tx_size_map[TX_16X4] == TX_8X4`, so a
14235 // split-transform 16x4/4x16 strip has RECTANGULAR 8x4/4x8 leaves.
14236 // Only reachable as a var-tx LEAF -- an 8x4/4x8 inter BLOCK is
14237 // refused earlier ("an inter partition below 8x8").
14238 | (8, 4) | (4, 8)
14239 // lane-sb128c r7: the 128 root's HORZ/VERT halves. These are NOT
14240 // one rectangular transform -- `max_txsize_rect_lookup
14241 // [BLOCK_128X64]` is TX_64X64, so the block tiles into two square
14242 // TX_64X64 units read through the mu-chunk loop, same as the
14243 // 128x128 NONE block's four.
14244 | (128, 64) | (64, 128)
14245 // lane-rectres r1: the 32x32-level 1:4 strips -- THE shape both
14246 // 10-bit film cuts and every measured 1080p offset stop on
14247 // (measured: 6/6 probes refuse at 32x8 or 8x32, nothing else).
14248 // `max_txsize_rect_lookup[BLOCK_32X8] == TX_32X8` codes all 256
14249 // positions, and its chroma pair is a 16x4 / 4x16 unit
14250 // (`ss_size_lookup[BLOCK_32X8]` = BLOCK_16X4).
14251 | (32, 8) | (8, 32)
14252 )
14253}
14254
14255/// The luma coefficient/`tx_type` table set of a whole-block rectangular
14256/// INTER transform unit (lane-inter4 r3). `av1_get_ext_tx_set_type` splits
14257/// the two shapes: a 32x16/16x32 unit has `tx_size_sqr_up == TX_32X32`, so
14258/// it reads the 2-symbol `EXT_TX_SET_DCT_IDTX` set regardless of
14259/// `reduced_tx_set`; a 16x8/8x16 unit has `tx_size_sqr_up == TX_16X16` and
14260/// `tx_size_sqr == TX_8X8`, so it reads `EXT_TX_SET_DCT_IDTX` when reduced
14261/// and the 16-symbol `EXT_TX_SET_ALL16` otherwise -- both at the *8x8* CDF
14262/// row (`txsize_sqr_map`), never the 16x16 one.
14263fn rect_inter_luma_set(w: usize, h: usize) -> Result<TxbSet> {
14264 Ok(match (w, h) {
14265 (32, 16) | (16, 32) => TxbSet::LumaRect32x16Inter,
14266 // lane-inter16ab r4: the 8x4/4x8 split leaf of a 16x4/4x16 strip.
14267 // `av1_get_ext_tx_set_type` (blockd.h:1097) at `tx_size_sqr_up ==
14268 // TX_8X8`, `tx_size_sqr == TX_4X4`, inter: DCT_IDTX when reduced,
14269 // ALL16 otherwise -- both at the TX_4X4 row.
14270 (8, 4) | (4, 8) => {
14271 if REDUCED_TX_SET_INTER.with(std::cell::Cell::get) {
14272 TxbSet::LumaRect8x4Inter
14273 } else {
14274 TxbSet::LumaRect8x4InterSet1
14275 }
14276 }
14277 (16, 4) | (4, 16) => {
14278 if REDUCED_TX_SET_INTER.with(std::cell::Cell::get) {
14279 TxbSet::LumaRect16x4Inter
14280 } else {
14281 TxbSet::LumaRect16x4Inter1
14282 }
14283 }
14284 (16, 8) | (8, 16) => {
14285 if REDUCED_TX_SET_INTER.with(std::cell::Cell::get) {
14286 TxbSet::LumaRect16x8Inter
14287 } else {
14288 TxbSet::LumaRect16x8InterSet1
14289 }
14290 }
14291 // lane-r14 r2: `av1_get_adjusted_tx_size` maps TX_64X32/TX_32X64 to
14292 // TX_32X32 and TX_64X16/TX_16X64 to TX_32X16/TX_16X32, and
14293 // `get_txsize_entropy_ctx`/`txsize_log2_minus4` agree with the
14294 // adjusted size, so the existing sets are bit-exact. Neither carries a
14295 // `tx_type` table (DCT_ONLY above), so the intra/inter split is moot.
14296 // lane-rectres r1: `tx_size_sqr_up[TX_32X8] == TX_32X32`, so
14297 // `av1_get_ext_tx_set_type` is `EXT_TX_SET_DCT_IDTX` for inter with or
14298 // without `reduced_tx_set` -- one set, no `REDUCED_TX_SET_INTER`
14299 // branch, read at the `txsize_sqr_map[TX_32X8] == TX_8X8` row.
14300 (32, 8) | (8, 32) => TxbSet::LumaRect32x8Inter,
14301 (64, 32) | (32, 64) => TxbSet::Luma64,
14302 (64, 16) | (16, 64) => TxbSet::LumaRect32x16,
14303 _ => {
14304 return Err(unsupported(
14305 "a rectangular inter luma transform unit whose shape has no coefficient table set here",
14306 ));
14307 }
14308 })
14309}
14310
14311/// The chroma table set of the same block's single rectangular chroma unit
14312/// (`av1_get_max_uv_txsize`): 16x8/8x16 under a 32x16/16x32 strip, 8x4/4x8
14313/// under a 16x8/8x16 one. Neither codes a `tx_type` symbol -- both inherit
14314/// the luma unit's.
14315fn rect_inter_chroma_set(w: usize, h: usize) -> Result<TxbSet> {
14316 Ok(match (w, h) {
14317 (16, 8) | (8, 16) => TxbSet::ChromaRect16x8,
14318 (8, 4) | (4, 8) => TxbSet::ChromaRect8x4,
14319 // lane-r14 r2: chroma of a 64-axis strip -- 32x16/16x32 under a
14320 // 64x32/32x64 one, 32x8/8x32 under a 64x16/16x64 one. Neither chroma
14321 // unit has a 64-px axis, so both are coded in full; `Chroma16` is the
14322 // exact set for TX_32X8/TX_8X32 (`get_txsize_entropy_ctx` = TX_16X16,
14323 // `txsize_log2_minus4` = 4), same as the intra strip path uses.
14324 (32, 16) | (16, 32) => TxbSet::ChromaRect32x16,
14325 (32, 8) | (8, 32) => TxbSet::Chroma16,
14326 // lane-rectres r1: chroma of a 32x8/8x32 strip. `Chroma8` is the exact
14327 // set for TX_16X4/TX_4X16 (`get_txsize_entropy_ctx` = TX_8X8,
14328 // `txsize_log2_minus4` = 2, 64-coefficient `eob_pt`).
14329 (16, 4) | (4, 16) => TxbSet::Chroma8,
14330 _ => {
14331 return Err(unsupported(
14332 "a rectangular inter chroma transform unit whose shape has no coefficient table set here",
14333 ));
14334 }
14335 })
14336}
14337
14338/// libaom `size_group_lookup[bsize]` for the block shapes this decoder's
14339/// inter path reaches, from the block's TRUE footprint rather than the
14340/// square `side` corner-cut: 8x8/8x16/16x8 -> 1, 16x16/16x32/32x16 -> 2,
14341/// everything 32 and above -> 3.
14342fn size_group_wh(w: usize, h: usize) -> usize {
14343 // lane-inter4 r4: `size_group_lookup[BLOCK_SIZES_ALL]` (libaom
14344 // `common_data.h:60`) is 0 for every block with a 4-px side
14345 // (4x4/4x8/8x4/4x16/16x4), 1 for min side 8, 2 for 16, 3 above -- the old
14346 // `0..=8 => 1` row gave a sub-8 leaf group 1 where libaom says 0.
14347 match w.min(h) {
14348 0..=4 => 0,
14349 8 => 1,
14350 16 => 2,
14351 _ => 3,
14352 }
14353}
14354
14355#[test]
14356fn size_group_wh_matches_libaom_size_group_lookup() {
14357 // `BLOCK_SIZES_ALL` in libaom's own order, with `size_group_lookup`'s
14358 // transcribed values (common_data.h:60-62).
14359 const TABLE: [((usize, usize), usize); 22] = [
14360 ((4, 4), 0), ((4, 8), 0), ((8, 4), 0), ((8, 8), 1), ((8, 16), 1), ((16, 8), 1),
14361 ((16, 16), 2), ((16, 32), 2), ((32, 16), 2), ((32, 32), 3), ((32, 64), 3),
14362 ((64, 32), 3), ((64, 64), 3), ((64, 128), 3), ((128, 64), 3), ((128, 128), 3),
14363 ((4, 16), 0), ((16, 4), 0), ((8, 32), 1), ((32, 8), 1), ((16, 64), 2), ((64, 16), 2),
14364 ];
14365 for ((w, h), want) in TABLE {
14366 assert_eq!(size_group_wh(w, h), want, "size_group_wh({w}, {h})");
14367 }
14368}
14369
14370/// The default (2D) coefficient scan of a rectangular transform.
14371fn rect_scan(w: usize, h: usize) -> Result<&'static [u16]> {
14372 Ok(match (w, h) {
14373 (32, 16) => &SCAN_32X16,
14374 (16, 32) => &SCAN_16X32,
14375 (16, 8) => &SCAN_16X8,
14376 (8, 16) => &SCAN_8X16,
14377 (16, 4) => &SCAN_16X4,
14378 (4, 16) => &SCAN_4X16,
14379 (8, 4) => &SCAN_8X4,
14380 (4, 8) => &SCAN_4X8,
14381 (32, 8) => &SCAN_32X8,
14382 (8, 32) => &SCAN_8X32,
14383 _ => {
14384 return Err(unsupported(
14385 "a rectangular transform unit whose shape has no coefficient scan table here",
14386 ));
14387 }
14388 })
14389}
14390
14391/// [`read_block_tx_size`] for a rectangular inter block (lane-inter4 r2):
14392/// spec 5.11.17 / libaom `read_tx_size_vartx` starting from the block's own
14393/// `max_txsize_rect_lookup` entry, which for a 2:1 strip IS rectangular. The
14394/// depth-0 `txfm_partition` symbol reads its context off the rect transform's
14395/// own width/height; a `0` leaves one whole-block rect transform unit
14396/// (`None`), and a `1` splits it into `sub_tx_size_map`'s two SQUARE
14397/// sub-transforms (`sub_tx_size_map[TX_32X16] == TX_16X16`), from which the
14398/// ordinary square [`read_var_tx_size`] recursion continues at depth 1 -- so
14399/// every leaf of a split rect block is square and the existing square leaf
14400/// loop reconstructs it unchanged.
14401#[allow(clippy::too_many_arguments)]
14402fn read_block_tx_size_rect(
14403 dec: &mut SymbolDecoder,
14404 cdfs: &mut Cdfs,
14405 n: &mut Neighbours,
14406 at_mi: (usize, usize),
14407 (bw, bh): (usize, usize),
14408 (mi_cols, mi_rows): (usize, usize),
14409 skip: bool,
14410) -> Result<Option<Vec<(usize, usize, usize, usize)>>> {
14411 if skip {
14412 // `set_txfm_ctxs(.., skip && is_inter)`: a skipped inter block records
14413 // its own BLOCK size -- width above, height left -- not a transform.
14414 txfm_partition_update_rect(n, at_mi, (bw, bh), (bw, bh));
14415 return Ok(None);
14416 }
14417 // `max_txsize_rect_lookup` is the block's own size, capped at 64 -- and
14418 // `rect_inter_residual_supported` has already excluded everything above 32.
14419 // lane-sb128c r7: except at the 128 root. `max_txsize_rect_lookup
14420 // [BLOCK_128X64] == TX_64X64` (libaom `common_data.h`), so a 128x64 block
14421 // is TWO square top-level transform units side by side and a 64x128 one is
14422 // two stacked -- exactly what libaom `read_block_tx_size`
14423 // (decodeframe.c:1140) codes with its `idy/idx` loop over
14424 // `tx_size_high_unit/tx_size_wide_unit[max_tx_size]`. Each unit reads its
14425 // own `txfm_partition` symbol at depth 0.
14426 if bw.max(bh) > 64 {
14427 let tx = 64usize;
14428 let (max_w_mi, max_h_mi) = (
14429 (bw / MI).min(mi_cols.saturating_sub(at_mi.1)),
14430 (bh / MI).min(mi_rows.saturating_sub(at_mi.0)),
14431 );
14432 let mut leaves = Vec::new();
14433 if !TX_SELECT_INTER.with(std::cell::Cell::get) {
14434 for row in (0..bh / MI).step_by(tx / MI) {
14435 for col in (0..bw / MI).step_by(tx / MI) {
14436 leaves.push((row, col, tx, tx));
14437 }
14438 }
14439 for &(row, col, tw, th) in &leaves {
14440 txfm_partition_update_rect(n, (at_mi.0 + row, at_mi.1 + col), (tw, th), (tw, th));
14441 }
14442 return Ok(Some(leaves));
14443 }
14444 for row in (0..bh / MI).step_by(tx / MI) {
14445 for col in (0..bw / MI).step_by(tx / MI) {
14446 read_var_tx_size(
14447 dec,
14448 cdfs,
14449 n,
14450 at_mi,
14451 bw.max(bh),
14452 (max_w_mi, max_h_mi),
14453 (tx, tx),
14454 0,
14455 row,
14456 col,
14457 &mut leaves,
14458 );
14459 }
14460 }
14461 if leaves.iter().any(|l| l.2.max(l.3) > 64) {
14462 return Err(unsupported(
14463 "an inter var-tx tree with a leaf transform larger than 64x64",
14464 ));
14465 }
14466 return Ok(Some(leaves));
14467 }
14468 let (tx_w, tx_h) = (bw, bh);
14469 if !TX_SELECT_INTER.with(std::cell::Cell::get) {
14470 // `TX_MODE_LARGEST`: no symbol at all, the whole block is one
14471 // transform, and `set_txfm_ctxs` records exactly what
14472 // `txfm_partition_update` would for that same unit.
14473 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
14474 RECT_INTER_TU_HITS.with(|c| c.set(c.get() + 1));
14475 return Ok(None);
14476 }
14477 let ctx = txfm_partition_ctx_rect(
14478 n.above_txfm[at_mi.1],
14479 n.left_txfm[at_mi.0],
14480 bw.max(bh),
14481 tx_w,
14482 tx_h,
14483 );
14484 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
14485 TXFM_SPLIT_READS.with(|c| c.set(c.get() + 1));
14486 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
14487 let (rng, _) = dec.debug_state();
14488 eprintln!(
14489 "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}",
14490 at_mi.0,
14491 at_mi.1,
14492 u8::from(split)
14493 );
14494 }
14495 if !split {
14496 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
14497 RECT_INTER_TU_HITS.with(|c| c.set(c.get() + 1));
14498 return Ok(None);
14499 }
14500 TXFM_SPLIT_HITS.with(|c| c.set(c.get() + 1));
14501 RECT_INTER_TXSPLIT_HITS.with(|c| c.set(c.get() + 1));
14502 // lane-r14 r3: `sub_tx_size_map` (libaom `common_data.c`) stays
14503 // RECTANGULAR under a 1:4 strip -- `[TX_64X16] == TX_32X16`,
14504 // `[TX_16X64] == TX_16X32` -- so the recursion below is the general
14505 // rect one and its leaves carry their own width and height.
14506 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
14507 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(at_mi.1));
14508 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(at_mi.0));
14509 let mut leaves = Vec::new();
14510 for row in (0..bh / MI).step_by(sub_h / MI) {
14511 for col in (0..bw / MI).step_by(sub_w / MI) {
14512 read_var_tx_size(
14513 dec,
14514 cdfs,
14515 n,
14516 at_mi,
14517 bw.max(bh),
14518 (max_w_mi, max_h_mi),
14519 (sub_w, sub_h),
14520 1,
14521 row,
14522 col,
14523 &mut leaves,
14524 );
14525 }
14526 }
14527 Ok(Some(leaves))
14528}
14529
14530/// [`read_inter_plane`] for a rectangular transform unit (lane-inter4 r2):
14531/// the coefficients are read with the rect coefficient machinery
14532/// ([`read_coeffs_rect`], whose `TxClass` handling covers the 1D `V_*`/`H_*`
14533/// types), inverted with the rect inverse transform
14534/// ([`dequant_and_inverse_typed_wh`], which carries the 2:1 `sqrt2` scale),
14535/// and added onto the top-left `w x h` of the block's own square-strided
14536/// motion-compensated prediction buffer. Returns the *rect* coefficient grid
14537/// and the coded `tx_type`.
14538///
14539/// `txb_skip_ctx` is 0 for luma: this unit covers the whole block, i.e.
14540/// `get_txb_ctx`'s `plane_bsize == txsize_to_bsize[tx_size]` branch.
14541#[allow(clippy::too_many_arguments)]
14542fn read_inter_plane_rect(
14543 dec: &mut SymbolDecoder,
14544 cdfs: &mut Cdfs,
14545 set: TxbSet,
14546 (w, h): (usize, usize),
14547 stride: usize,
14548 plane_idx: usize,
14549 around: (bool, bool, i32),
14550 tx_mode: usize,
14551 plane: &mut PlaneBuf,
14552 x: usize,
14553 y: usize,
14554 prediction: &[u16],
14555 inherited_luma_tx_type: Option<TxType>,
14556 luma_skip_ctx: Option<usize>,
14557) -> Result<(Vec<i32>, TxType)> {
14558 let skip_ctx = if plane_idx == 0 {
14559 // `get_txb_ctx_general`: 0 only when this unit IS the whole plane
14560 // block; a var-tx leaf passes its own neighbour-table context.
14561 luma_skip_ctx.unwrap_or(0)
14562 } else {
14563 usize::from(around.0) + usize::from(around.1)
14564 };
14565 let mut coding = cdfs.txb(set, tx_mode);
14566 // `av1_get_ext_tx_set_type`'s DCT-only clamp is on `tx_size_sqr_up`, i.e.
14567 // the *longer* side of this rect transform.
14568 let default_tx_type = match inherited_luma_tx_type {
14569 Some(t) => reduce_inherited_chroma_tx_type(t, w, h),
14570 None => TxType::DctDct,
14571 };
14572 // lane-r14 r2: a 64-length axis codes only its low 32 coefficients
14573 // (`av1_get_max_eob`), so the coded unit is the `min(w,32) x min(h,32)`
14574 // corner, zero-extended into the true `w x h` grid before the inverse
14575 // transform -- exactly what the intra superblock-strip path does. A
14576 // corner that comes out square (32x32, under a 64x32/32x64 strip) reads
14577 // through the SQUARE coefficient reader with `rect_shape = Some((w, h))`,
14578 // because `av1_nz_map_ctx_offset` is indexed by the real, un-adjusted
14579 // rectangular shape (lane-sbpart r8).
14580 let (cw, ch) = (w.min(32), h.min(32));
14581 if plane_idx == 0 && w.max(h) == 64 {
14582 RECT64_INTER_TU_HITS.with(|c| c.set(c.get() + 1));
14583 }
14584 if plane_idx == 0 && (w, h) == (32, 8) || plane_idx == 0 && (w, h) == (8, 32) {
14585 RECT32X8_INTER_TU_HITS.with(|c| {
14586 let mut v = c.get();
14587 v[usize::from(w == 8)] += 1;
14588 c.set(v);
14589 });
14590 }
14591 let (corner, tx_type) = if (cw, ch) == (32, 32) {
14592 let scan32 = default_scan(TX32);
14593 read_coeffs(
14594 dec,
14595 &mut coding,
14596 &scan32,
14597 skip_ctx,
14598 dc_sign_ctx(around.2),
14599 default_tx_type,
14600 Some((w, h)),
14601 )?
14602 } else {
14603 read_coeffs_rect(
14604 dec,
14605 &mut coding,
14606 rect_scan(cw, ch)?,
14607 cw,
14608 ch,
14609 skip_ctx,
14610 dc_sign_ctx(around.2),
14611 default_tx_type,
14612 )?
14613 };
14614 let grid = if (cw, ch) == (w, h) {
14615 corner
14616 } else {
14617 let mut full = vec![0i32; w * h];
14618 for row in 0..ch {
14619 full[row * w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
14620 }
14621 full
14622 };
14623 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
14624 let residual = dequant_and_inverse_typed_wh(
14625 &grid,
14626 w,
14627 h,
14628 bit_depth(),
14629 block_q_idx(),
14630 dc_delta,
14631 ac_delta,
14632 tx_type,
14633 );
14634 // `reconstruct_mc_rect` reads both buffers at the square prediction
14635 // stride, so the dense `w x h` residual is re-laid at that stride first.
14636 let mut strided = vec![0i32; stride * stride];
14637 for row in 0..h {
14638 strided[row * stride..][..w].copy_from_slice(&residual[row * w..][..w]);
14639 }
14640 plane.reconstruct_mc_rect(x, y, stride, w, h, prediction, &strided);
14641 Ok((grid, tx_type))
14642}
14643
14644/// A rect coefficient grid re-laid into the square `stride x stride` grid the
14645/// neighbour/deblock stamps downstream of the residual expect.
14646fn embed_rect_grid(grid: &[i32], w: usize, h: usize, stride: usize) -> Vec<i32> {
14647 let mut full = vec![0i32; stride * stride];
14648 for row in 0..h {
14649 full[row * stride..][..w].copy_from_slice(&grid[row * w..][..w]);
14650 }
14651 full
14652}
14653
14654/// One 8x8 inter leaf's luma residual (lane-txselect): either the whole-8x8
14655/// transform, or -- when [`read_block_tx_size`]'s var-tx tree took the single
14656/// split a `BLOCK_8X8` can take (`split`) -- the four 4x4 transform units in
14657/// raster order, each reading its own coefficient context off the units
14658/// already decoded before it. Returns the block's luma grid (all-zero in the
14659/// split case, whose reconstruction has already happened unit by unit) and
14660/// the `tx_type` chroma inherits: `av1_get_tx_type`'s colocated luma lookup,
14661/// which for a split block lands on the top-left unit.
14662#[allow(clippy::too_many_arguments)]
14663fn read_inter_luma8(
14664 dec: &mut SymbolDecoder,
14665 cdfs: &mut Cdfs,
14666 neighbours: &mut Neighbours,
14667 leaf_mi: (usize, usize),
14668 y: &mut PlaneBuf,
14669 px: usize,
14670 py: usize,
14671 pred_y: &[u16],
14672 mode_for_tx: usize,
14673 base_q_idx: u8,
14674 scan8: &[u16],
14675 scan4: &[u16],
14676 reduced_tx_set: bool,
14677 split: bool,
14678) -> Result<(Vec<i32>, TxType)> {
14679 if !split {
14680 return read_inter_plane(
14681 dec,
14682 cdfs,
14683 if reduced_tx_set {
14684 TxbSet::Luma8Inter
14685 } else {
14686 TxbSet::Luma8InterSet1
14687 },
14688 scan8,
14689 0,
14690 neighbours.around_mi(leaf_mi, 8)[0],
14691 mode_for_tx,
14692 y,
14693 px,
14694 py,
14695 8,
14696 base_q_idx,
14697 pred_y,
14698 None,
14699 None,
14700 );
14701 }
14702 let mut first = TxType::DctDct;
14703 for tu_row in 0..2 {
14704 for tu_col in 0..2 {
14705 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
14706 let mut tu_pred = Vec::with_capacity(16);
14707 for rr in 0..4 {
14708 let start = (tu_row * 4 + rr) * 8 + tu_col * 4;
14709 tu_pred.extend_from_slice(&pred_y[start..start + 4]);
14710 }
14711 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
14712 let (tu_grid, tu_tx_type) = read_inter_plane(
14713 dec,
14714 cdfs,
14715 if reduced_tx_set {
14716 TxbSet::Luma4Inter
14717 } else {
14718 TxbSet::Luma4InterSet1
14719 },
14720 scan4,
14721 0,
14722 neighbours.around_mi(tu_mi, 4)[0],
14723 mode_for_tx,
14724 y,
14725 px + tu_col * 4,
14726 py + tu_row * 4,
14727 4,
14728 base_q_idx,
14729 &tu_pred,
14730 None,
14731 Some(tu_skip_ctx),
14732 )?;
14733 if tu_row == 0 && tu_col == 0 {
14734 first = tu_tx_type;
14735 }
14736 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
14737 }
14738 }
14739 Ok((vec![0i32; 64], first))
14740}
14741
14742/// The [`TxbSet`] one leaf of an inter block's var-tx tree reads its
14743/// coefficient tables from -- the inter counterpart of [`txbset_for`].
14744/// `av1_get_tx_type`'s chroma tail (libaom `av1/common/blockd.h:1291-1305`):
14745/// an inter block's chroma transform inherits the *colocated luma* unit's
14746/// coded `tx_type`, then drops back to `DCT_DCT` unless that type is a member
14747/// of the extended set the CHROMA transform size selects
14748/// (`av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)][tx_type]`,
14749/// `blockd.h:1036`/`1097`). lane-golomb r7: we used to force `DCT_DCT` at
14750/// every chroma side >= 32, but `av1_get_ext_tx_set_type`'s DCT-only rung is
14751/// `tx_size_sqr_up > TX_32X32`; at exactly TX_32X32 an inter block reads
14752/// `EXT_TX_SET_DCT_IDTX`, so a 64x64 inter block whose first luma leaf coded
14753/// `IDTX` inherits IDTX on its 32x32 chroma units. `IDTX` and `DCT_DCT` are
14754/// both `TX_CLASS_2D`, so that mistake left the entropy stream perfectly in
14755/// sync and only corrupted the inverse transform (one 64x64 superblock of
14756/// high-frequency chroma noise, luma bit-exact).
14757fn reduce_inherited_chroma_tx_type(t: TxType, w: usize, h: usize) -> TxType {
14758 use TxType::*;
14759 let sqr_up = w.max(h);
14760 let sqr = w.min(h);
14761 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
14762 // `av1_get_ext_tx_set_type(tx_size, is_inter = 1, reduced)`.
14763 let allowed: &[TxType] = if sqr_up > 32 {
14764 // EXT_TX_SET_DCTONLY
14765 &[DctDct]
14766 } else if sqr_up == 32 || reduced {
14767 // EXT_TX_SET_DCT_IDTX
14768 &[DctDct, Idtx]
14769 } else if sqr == 16 {
14770 // EXT_TX_SET_DTT9_IDTX_1DDCT -- TX_TYPES 0..=11, i.e. everything but
14771 // the four 1D ADST/FLIPADST types.
14772 &[
14773 DctDct, AdstDct, DctAdst, AdstAdst, FlipAdstDct, DctFlipAdst, FlipAdstFlipAdst,
14774 AdstFlipAdst, FlipAdstAdst, Idtx, VDct, HDct,
14775 ]
14776 } else {
14777 // EXT_TX_SET_ALL16
14778 return t;
14779 };
14780 if allowed.contains(&t) { t } else { DctDct }
14781}
14782
14783fn inter_txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
14784 match tx_px {
14785 // lane-sb128c r1: a 128x128 inter block's own luma unit
14786 // (`max_txsize_rect_lookup[BLOCK_128X128] == TX_64X64`).
14787 // `av1_get_ext_tx_set_type` is `DCT_ONLY` at `tx_size_sqr_up ==
14788 // TX_64X64`, so no `tx_type` symbol is coded and the intra/inter sets
14789 // coincide -- exactly the set the whole-64x64 inter block already uses.
14790 64 => TxbSet::Luma64,
14791 32 => TxbSet::Luma32Inter,
14792 16 if reduced_tx_set => TxbSet::Luma16Inter,
14793 16 => TxbSet::Luma16InterSet1,
14794 8 if reduced_tx_set => TxbSet::Luma8Inter,
14795 8 => TxbSet::Luma8InterSet1,
14796 4 if reduced_tx_set => TxbSet::Luma4Inter,
14797 4 => TxbSet::Luma4InterSet1,
14798 _ => unreachable!("a var-tx leaf is never wider than a 64x64 block's 32x32 sub-transform"),
14799 }
14800}
14801
14802/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
14803/// the only four sizes a `TxMode::Select` block's coded coefficient grid
14804/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
14805fn scan_for<'a>(
14806 tx_px: usize,
14807 scan32: &'a [u16],
14808 scan16: &'a [u16],
14809 scan8: &'a [u16],
14810 scan4: &'a [u16],
14811) -> &'a [u16] {
14812 match tx_px {
14813 32 => scan32,
14814 16 => scan16,
14815 8 => scan8,
14816 4 => scan4,
14817 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
14818 }
14819}
14820
14821/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
14822/// from -- 64 is only ever the 64x64-block, depth-0, corner-scanned case
14823/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
14824/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
14825/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
14826/// regardless of the flag (`av1_get_ext_tx_set_type`'s
14827/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
14828/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
14829/// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]).
14830/// [`txbset_for`], for a block libaom's `is_inter_block` calls inter -- which
14831/// an intrabc block is (`blockd.h:373`), so its `tx_type` comes off the
14832/// inter `ext_tx` sets, never the mode-indexed intra ones.
14833fn txbset_for_inter(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
14834 match tx_px {
14835 64 => TxbSet::Luma64,
14836 32 => TxbSet::Luma32Inter,
14837 16 if reduced_tx_set => TxbSet::Luma16Inter,
14838 16 => TxbSet::Luma16InterSet1,
14839 8 if reduced_tx_set => TxbSet::Luma8Inter,
14840 8 => TxbSet::Luma8InterSet1,
14841 _ => TxbSet::Luma64,
14842 }
14843}
14844
14845fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
14846 match tx_px {
14847 64 => TxbSet::Luma64,
14848 32 => TxbSet::Luma32,
14849 16 => TxbSet::Luma16,
14850 8 if reduced_tx_set => TxbSet::Luma8,
14851 8 => TxbSet::Luma8Set1,
14852 4 if reduced_tx_set => TxbSet::Luma4,
14853 4 => TxbSet::Luma4Set1,
14854 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
14855 }
14856}
14857
14858/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
14859/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
14860fn unit_log2(px: u32) -> i32 {
14861 if px == 0 {
14862 0
14863 } else {
14864 px.trailing_zeros() as i32 - 2
14865 }
14866}
14867
14868/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
14869/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
14870/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
14871/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
14872/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
14873/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
14874/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
14875/// block anywhere aborted the whole stream's decode before comparison).
14876fn lf_level(
14877 lf: &LoopFilterParams,
14878 plane_idx: usize,
14879 dir: usize,
14880 ref_frame: i8,
14881 delta_lf: i32,
14882 segment_id: u8,
14883) -> i32 {
14884 let base = i32::from(if plane_idx == 0 {
14885 lf.level[dir]
14886 } else if plane_idx == 1 {
14887 lf.level[2]
14888 } else {
14889 lf.level[3]
14890 });
14891 // spec 7.14.4: the per-superblock `DeltaLF` term applies before the
14892 // ref/mode delta scaling below, and regardless of `delta_enabled`
14893 // (that flag only gates `ref_deltas`/`mode_deltas`).
14894 let base = (base + delta_lf).clamp(0, 63);
14895 // lane-seg, spec 7.14.4 / libaom `av1_loop_filter_frame_init`: this
14896 // block's segment's own `SEG_LVL_ALT_LF_*` delta applies after the
14897 // per-superblock `DeltaLF` term and before the ref/mode deltas below.
14898 // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4)
14899 // for chroma.
14900 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
14901 let base = match seg_feature(usize::from(segment_id), feature) {
14902 Some(data) => (base + data).clamp(0, 63),
14903 None => base,
14904 };
14905 if !lf.delta_enabled {
14906 return base;
14907 }
14908 let scale = 1i32 << (base >> 5);
14909 let is_inter = ref_frame != 0;
14910 let is_globalmv = ref_frame < 0;
14911 let ref_idx = ref_frame.unsigned_abs() as usize;
14912 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
14913 if is_inter {
14914 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
14915 }
14916 lvl.clamp(0, 63)
14917}
14918
14919/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
14920/// no-segmentation, no-delta-LF path and to this decoder's own invariant
14921/// that a coded block's transform is always its own full size -- so a TU
14922/// edge is always also a PU edge, and the "both sides skipped, not a PU
14923/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
14924/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
14925/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
14926fn edge_params(
14927 lf: &LoopFilterParams,
14928 n: &Neighbours,
14929 plane_idx: usize,
14930 dir: usize,
14931 chroma: bool,
14932 x0: usize,
14933 y0: usize,
14934) -> Option<(u8, i32)> {
14935 let (mi_r, mi_c) = (plane_to_mi(chroma, y0), plane_to_mi(chroma, x0));
14936 let cur_tx = if dir == 0 {
14937 tx_px_at(n, chroma, mi_r, mi_c)
14938 } else {
14939 tx_h_px_at(n, chroma, mi_r, mi_c)
14940 };
14941 if cur_tx == 0 || (if dir == 0 { x0 } else { y0 }) % cur_tx as usize != 0 {
14942 return None;
14943 }
14944 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
14945 let (pv_mi_r, pv_mi_c) = if dir == 0 {
14946 (mi_r, mi_c - 1)
14947 } else {
14948 (mi_r - 1, mi_c)
14949 };
14950 let pv_tx = if dir == 0 {
14951 tx_px_at(n, chroma, pv_mi_r, pv_mi_c)
14952 } else {
14953 tx_h_px_at(n, chroma, pv_mi_r, pv_mi_c)
14954 };
14955 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
14956 let delta_idx = if plane_idx == 0 { dir } else { plane_idx + 1 };
14957 let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][delta_idx]);
14958 let pv_delta_lf = i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][delta_idx]);
14959
14960 // spec 7.14.2 / libaom `set_lpf_parameters`: a transform edge between two
14961 // SKIPPED INTER blocks is filtered only when it is also a prediction
14962 // (coded-block) edge -- `!pv_skip || !curr_skipped || pu_edge`. The
14963 // omission of this term (on the stale invariant "a coded block's transform
14964 // is always its own full size", which var-tx broke) had us filtering an
14965 // interior 8-px lattice the reference never touches: on the pinned 192x68
14966 // inter stream frame 1 went from 7244 wrong post-deblock luma px to 0.
14967 let cur_org = n.blk_org_grid[mi_r * n.skip_grid_cols_mi + mi_c];
14968 let pu_edge = if dir == 0 {
14969 mi_c == usize::from(cur_org[1])
14970 } else {
14971 mi_r == usize::from(cur_org[0])
14972 };
14973 if !pu_edge
14974 && cur_ref != 0
14975 && pv_ref != 0
14976 && n.skip_at(mi_r, mi_c)
14977 && n.skip_at(pv_mi_r, pv_mi_c)
14978 {
14979 return None;
14980 }
14981 let cur_level = lf_level(lf, plane_idx, dir, cur_ref, cur_delta_lf, segment_id_at(mi_r, mi_c));
14982 let pv_level = lf_level(
14983 lf,
14984 plane_idx,
14985 dir,
14986 pv_ref,
14987 pv_delta_lf,
14988 segment_id_at(pv_mi_r, pv_mi_c),
14989 );
14990 if cur_level == 0 && pv_level == 0 {
14991 return None;
14992 }
14993 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
14994 let len: u8 = if chroma {
14995 if dim == 0 { 4 } else { 6 }
14996 } else {
14997 [4, 8, 14, 14, 14][dim]
14998 };
14999 let level = if cur_level != 0 { cur_level } else { pv_level };
15000 DEBLOCK_HITS.with(|c| c.set(c.get() + 1));
15001 Some((len, level))
15002}
15003
15004/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
15005fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
15006 let sharpness = i32::from(sharpness);
15007 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
15008 let mut lim = level >> shift;
15009 if sharpness > 0 {
15010 lim = lim.min(9 - sharpness);
15011 }
15012 lim = lim.max(1);
15013 (2 * (level + 2) + lim, lim, level >> 4)
15014}
15015
15016fn sclamp(v: i32) -> i32 {
15017 // libaom's `signed_char_clamp_high`: the clamp range scales with
15018 // `128 << (bit_depth - 8)` alongside the centering constant below.
15019 let scale = 1i32 << (bit_depth() - 8);
15020 v.clamp(-128 * scale, 128 * scale - 1)
15021}
15022
15023fn round_pow2(v: i32, n: u32) -> i32 {
15024 (v + (1 << (n - 1))) >> n
15025}
15026
15027/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
15028/// fallback.
15029fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32) -> [i32; 4] {
15030 if !mask {
15031 return [p1, p0, q0, q1];
15032 }
15033 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
15034 let centre = 128i32 << (bit_depth() - 8);
15035 let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre);
15036 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
15037 let filter = sclamp(outer + 3 * (qs0 - ps0));
15038 let filter1 = sclamp(filter + 4) >> 3;
15039 let filter2 = sclamp(filter + 3) >> 3;
15040 let oq0 = sclamp(qs0 - filter1) + centre;
15041 let op0 = sclamp(ps0 + filter2) + centre;
15042 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
15043 let oq1 = sclamp(qs1 - tap) + centre;
15044 let op1 = sclamp(ps1 + tap) + centre;
15045 [op1, op0, oq0, oq1]
15046}
15047
15048/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
15049/// `filter4`'s narrow taps.
15050#[allow(clippy::too_many_arguments)]
15051fn filter6(
15052 mask: bool,
15053 thresh: i32,
15054 flat: bool,
15055 p2: i32,
15056 p1: i32,
15057 p0: i32,
15058 q0: i32,
15059 q1: i32,
15060 q2: i32,
15061) -> [i32; 4] {
15062 if flat && mask {
15063 [
15064 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
15065 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
15066 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
15067 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
15068 ]
15069 } else {
15070 filter4(mask, thresh, p1, p0, q0, q1)
15071 }
15072}
15073
15074/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
15075#[allow(clippy::too_many_arguments)]
15076fn filter8(
15077 mask: bool,
15078 thresh: i32,
15079 flat: bool,
15080 p3: i32,
15081 p2: i32,
15082 p1: i32,
15083 p0: i32,
15084 q0: i32,
15085 q1: i32,
15086 q2: i32,
15087 q3: i32,
15088) -> [i32; 6] {
15089 if flat && mask {
15090 [
15091 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
15092 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
15093 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
15094 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
15095 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
15096 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
15097 ]
15098 } else {
15099 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1);
15100 [p2, op1, op0, oq0, oq1, q2]
15101 }
15102}
15103
15104/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
15105/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
15106/// way -- they are only ever taps here, never written).
15107#[allow(clippy::too_many_arguments)]
15108fn filter14(
15109 mask: bool,
15110 thresh: i32,
15111 flat: bool,
15112 flat2: bool,
15113 p6: i32,
15114 p5: i32,
15115 p4: i32,
15116 p3: i32,
15117 p2: i32,
15118 p1: i32,
15119 p0: i32,
15120 q0: i32,
15121 q1: i32,
15122 q2: i32,
15123 q3: i32,
15124 q4: i32,
15125 q5: i32,
15126 q6: i32,
15127) -> [i32; 12] {
15128 if flat2 && flat && mask {
15129 [
15130 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
15131 round_pow2(
15132 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
15133 4,
15134 ),
15135 round_pow2(
15136 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
15137 4,
15138 ),
15139 round_pow2(
15140 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
15141 4,
15142 ),
15143 round_pow2(
15144 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
15145 4,
15146 ),
15147 round_pow2(
15148 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
15149 4,
15150 ),
15151 round_pow2(
15152 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
15153 4,
15154 ),
15155 round_pow2(
15156 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
15157 4,
15158 ),
15159 round_pow2(
15160 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
15161 4,
15162 ),
15163 round_pow2(
15164 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
15165 4,
15166 ),
15167 round_pow2(
15168 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
15169 4,
15170 ),
15171 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
15172 ]
15173 } else {
15174 let [op2, op1, op0, oq0, oq1, oq2] =
15175 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3);
15176 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
15177 }
15178}
15179
15180/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
15181/// the first (`q0`) sample past the edge, `outer_stride` advances to the
15182/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
15183/// the next along the edge's own filtering direction.
15184#[allow(clippy::too_many_arguments)]
15185fn filter_edge(
15186 data: &mut [u16],
15187 base: usize,
15188 outer_stride: isize,
15189 tap_stride: isize,
15190 len: u8,
15191 level: i32,
15192 sharpness: u8,
15193) {
15194 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
15195 // libaom `highbd_filter_mask*`/`highbd_flat_mask4`/`highbd_hev_mask`:
15196 // every 8-bit threshold (including the flat masks' fixed `1`) is
15197 // compared against a raw pixel difference on the stream's own bit-depth
15198 // scale, so each is shifted left by `bit_depth - 8` before use.
15199 let shift = bit_depth() - 8;
15200 let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift);
15201 let flat_thresh = 1i32 << shift;
15202 for i in 0..4isize {
15203 let center = (base as isize + i * outer_stride) as usize;
15204 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
15205 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
15206 match len {
15207 4 => {
15208 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
15209 let mask = (p1 - p0).abs() <= limit
15210 && (q1 - q0).abs() <= limit
15211 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
15212 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1);
15213 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
15214 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
15215 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
15216 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
15217 }
15218 6 => {
15219 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
15220 let mask = (p2 - p1).abs() <= limit
15221 && (p1 - p0).abs() <= limit
15222 && (q1 - q0).abs() <= limit
15223 && (q2 - q1).abs() <= limit
15224 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
15225 let flat = (p1 - p0).abs() <= flat_thresh
15226 && (q1 - q0).abs() <= flat_thresh
15227 && (p2 - p0).abs() <= flat_thresh
15228 && (q2 - q0).abs() <= flat_thresh;
15229 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2);
15230 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
15231 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
15232 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
15233 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
15234 }
15235 8 => {
15236 let (p3, p2, p1, p0, q0, q1, q2, q3) =
15237 (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3));
15238 let mask = (p3 - p2).abs() <= limit
15239 && (p2 - p1).abs() <= limit
15240 && (p1 - p0).abs() <= limit
15241 && (q1 - q0).abs() <= limit
15242 && (q2 - q1).abs() <= limit
15243 && (q3 - q2).abs() <= limit
15244 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
15245 let flat = (p1 - p0).abs() <= flat_thresh
15246 && (q1 - q0).abs() <= flat_thresh
15247 && (p2 - p0).abs() <= flat_thresh
15248 && (q2 - q0).abs() <= flat_thresh
15249 && (p3 - p0).abs() <= flat_thresh
15250 && (q3 - q0).abs() <= flat_thresh;
15251 let [op2, op1, op0, oq0, oq1, oq2] =
15252 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3);
15253 data[idx(-3)] = op2.clamp(0, sample_max()) as u16;
15254 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
15255 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
15256 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
15257 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
15258 data[idx(2)] = oq2.clamp(0, sample_max()) as u16;
15259 }
15260 _ => {
15261 let (p6, p5, p4, p3, p2, p1, p0) =
15262 (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1));
15263 let (q0, q1, q2, q3, q4, q5, q6) =
15264 (px(0), px(1), px(2), px(3), px(4), px(5), px(6));
15265 let mask = (p3 - p2).abs() <= limit
15266 && (p2 - p1).abs() <= limit
15267 && (p1 - p0).abs() <= limit
15268 && (q1 - q0).abs() <= limit
15269 && (q2 - q1).abs() <= limit
15270 && (q3 - q2).abs() <= limit
15271 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
15272 let flat = (p1 - p0).abs() <= flat_thresh
15273 && (q1 - q0).abs() <= flat_thresh
15274 && (p2 - p0).abs() <= flat_thresh
15275 && (q2 - q0).abs() <= flat_thresh
15276 && (p3 - p0).abs() <= flat_thresh
15277 && (q3 - q0).abs() <= flat_thresh;
15278 let flat2 = (p4 - p0).abs() <= flat_thresh
15279 && (q4 - q0).abs() <= flat_thresh
15280 && (p5 - p0).abs() <= flat_thresh
15281 && (q5 - q0).abs() <= flat_thresh
15282 && (p6 - p0).abs() <= flat_thresh
15283 && (q6 - q0).abs() <= flat_thresh;
15284 let out = filter14(
15285 mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5,
15286 q6,
15287 );
15288 for (k, v) in (-6..=5isize).zip(out) {
15289 data[idx(k)] = v.clamp(0, sample_max()) as u16;
15290 }
15291 }
15292 }
15293 }
15294}
15295
15296/// One plane's worth of spec 7.14: every vertical edge across the plane,
15297/// then every horizontal edge (the order the spec and libaom both use).
15298fn deblock_plane(
15299 plane: &mut PlaneBuf,
15300 plane_idx: usize,
15301 lf: &LoopFilterParams,
15302 n: &Neighbours,
15303 frame_width: usize,
15304 frame_height: usize,
15305) {
15306 let chroma = plane_idx != 0;
15307 // r7: libaom clips the deblock loop to the CODED frame's own
15308 // width/height, not the mi-aligned `true_width`/`true_height` margin
15309 // (the padding up to the next 8-pixel/superblock boundary that
15310 // reconstruction still fills in but the loop filter never visits).
15311 // Confirmed against the superres gate: with the margin included, the
15312 // last coded mi column's horizontal edges were filtered when libaom's
15313 // real output leaves them untouched (r6's post-deblock diff, 37 px, all
15314 // in columns 44-47); clipping here closes it (3/3 frames pixel-exact).
15315 // lane-golomb r9: the bound is the MI-ROUNDED frame, not the coded
15316 // frame. libaom's `av1_filter_block_plane_vert/horz` walk the superblock
15317 // and stop at `cm->mi_params.mi_cols`/`mi_rows`, which
15318 // `av1_set_mb_mi` derives from `ALIGN_POWER_OF_TWO(width, 3)` -- the
15319 // 8-pixel-aligned frame, i.e. a 68-wide frame is filtered out to column
15320 // 72 and the vertical edge AT x=68 is a real edge that rewrites the
15321 // in-crop columns 64..67. Clipping at `frame_width` skipped it, which is
15322 // the +-1 straddling-band defect (68x192 cq35, frame 1, 141 luma pixels
15323 // all in columns 64..67; frame 0 survived because that edge carried no
15324 // filter level there). r7's superres measurement is preserved: its frame
15325 // was already 8-aligned, so this bound equals `frame_width` there and
15326 // still excludes the superblock padding up to `true_width`.
15327 let (cw, ch) = if chroma {
15328 (frame_width.div_ceil(2), frame_height.div_ceil(2))
15329 } else {
15330 (frame_width, frame_height)
15331 };
15332 let (tw, th, stride) = (
15333 plane.true_width.min(cw),
15334 plane.true_height.min(ch),
15335 plane.width,
15336 );
15337 if std::env::var_os("EC_AV1_DEBLOCK_TRACE_V").is_some() {
15338 eprintln!("DEBLOCK plane={plane_idx} tw={tw} th={th} stride={stride} true={}x{} crop={cw}x{ch}", plane.true_width, plane.true_height);
15339 }
15340 let mut y0 = 0usize;
15341 while y0 < th {
15342 let mut x0 = 4usize;
15343 while x0 < tw {
15344 if let Some((len, level)) = edge_params(lf, n, plane_idx, 0, chroma, x0, y0) {
15345 if std::env::var_os("EC_AV1_DEBLOCK_TRACE_V").is_some() && plane_idx == 0 {
15346 eprintln!("VEDGE x0={x0} y0={y0} len={len} level={level}");
15347 }
15348 filter_edge(
15349 &mut plane.data,
15350 y0 * stride + x0,
15351 stride as isize,
15352 1,
15353 len,
15354 level,
15355 lf.sharpness,
15356 );
15357 }
15358 x0 += 4;
15359 }
15360 y0 += 4;
15361 }
15362 let mut x0 = 0usize;
15363 while x0 < tw {
15364 let mut y0 = 4usize;
15365 while y0 < th {
15366 if let Some((len, level)) = edge_params(lf, n, plane_idx, 1, chroma, x0, y0) {
15367 if std::env::var_os("EC_AV1_DEBLOCK_TRACE").is_some()
15368 && plane_idx == 0
15369 && x0 == 44
15370 {
15371 eprintln!(
15372 "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}",
15373 lf.sharpness
15374 );
15375 }
15376 filter_edge(
15377 &mut plane.data,
15378 y0 * stride + x0,
15379 1,
15380 stride as isize,
15381 len,
15382 level,
15383 lf.sharpness,
15384 );
15385 }
15386 y0 += 4;
15387 }
15388 x0 += 4;
15389 }
15390}
15391
15392fn apply_cdef(
15393 y: &mut PlaneBuf,
15394 u: &mut PlaneBuf,
15395 v: &mut PlaneBuf,
15396 cdef: &CdefParams,
15397 skip_grid: &Neighbours,
15398 // This frame header's own CROPPED luma size, for the straddling-unit
15399 // counter only -- CDEF itself walks the mi-rounded plane.
15400 (frame_w, frame_h): (usize, usize),
15401) {
15402 // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling.
15403 if std::env::var_os("EC_AV1_DEBUG_SKIP_CDEF").is_some() {
15404 return;
15405 }
15406 // lane-cdefstrip r1 instrument, BEFORE either early return so it is valid
15407 // for every frame: an 8x8 CDEF unit none of whose four mi cells a coded
15408 // block wrote this frame. `Neighbours` seeds `skip_grid` all-false, so a
15409 // decode arm that forgets `fill_skip_grid_rect` reads "not skip" and CDEF
15410 // filters a unit libaom's `is_8x8_block_skip` (`cdef.c:29-38`) may exclude.
15411 // Always 0 on every stream measured; a gate asserts it stays 0.
15412 {
15413 let mut r = 0usize;
15414 while r < skip_grid.mi_rows {
15415 let mut c = 0usize;
15416 while c < skip_grid.mi_cols {
15417 if (0..2).any(|rr| {
15418 (0..2).any(|cc| {
15419 !skip_grid
15420 .skip_written
15421 .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc))
15422 .copied()
15423 .unwrap_or(true)
15424 })
15425 }) {
15426 CDEF_UNWRITTEN_SKIP_UNITS.with(|c2| c2.set(c2.get() + 1));
15427 if std::env::var_os("EC_AV1_DEBUG_CDEF_BAND").is_some() {
15428 eprintln!("cdef band unwritten at mi ({r},{c}) px ({},{})", r * 4, c * 4);
15429 }
15430 }
15431 let cell = |rr: usize, cc: usize| {
15432 skip_grid
15433 .skip_grid
15434 .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc))
15435 .copied()
15436 .unwrap_or(false)
15437 };
15438 let first = cell(0, 0);
15439 if (0..2).any(|rr| (0..2).any(|cc| cell(rr, cc) != first)) {
15440 CDEF_MIXED_SKIP_UNITS.with(|c2| c2.set(c2.get() + 1));
15441 }
15442 c += 2;
15443 }
15444 r += 2;
15445 }
15446 }
15447 // `cdef.bits == 0` still means "no filtering at all" whenever the single
15448 // (index 0) strength pair is all-zero -- the fast path every existing
15449 // gate stream takes. A `bits > 0` frame can still be all-zero-strength
15450 // at every index, but that is rare enough not to special-case; the
15451 // per-superblock lookup below degrades to the same index-0 read anyway
15452 // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`).
15453 if cdef.bits == 0
15454 && cdef.y_pri_strength[0] == 0
15455 && cdef.y_sec_strength[0] == 0
15456 && cdef.uv_pri_strength[0] == 0
15457 && cdef.uv_sec_strength[0] == 0
15458 {
15459 return;
15460 }
15461 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
15462 let idx_grid = CDEF_IDX_GRID.with(|g| g.borrow().clone());
15463 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
15464 if sb_cols == 0 {
15465 return 0;
15466 }
15467 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
15468 idx_grid
15469 .get(sb_r * sb_cols + sb_c)
15470 .copied()
15471 .unwrap_or(0) as usize
15472 };
15473 let src_y = y.data.clone();
15474 let src_u = u.data.clone();
15475 let src_v = v.data.clone();
15476 // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`,
15477 // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`.
15478 let coeff_shift = i32::from(bit_depth()) - 8;
15479 let damping = i32::from(cdef.damping) + coeff_shift;
15480 let damping_uv = (damping - 1).max(0);
15481 let mut mi_r = 0usize;
15482 while mi_r < skip_grid.mi_rows {
15483 let mut mi_c = 0usize;
15484 while mi_c < skip_grid.mi_cols {
15485 if skip_grid.is_skip_txfm(mi_r, mi_c) {
15486 CDEF_SKIPPED_UNITS.with(|c| c.set(c.get() + 1));
15487 }
15488 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
15489 let sidx = strength_idx(mi_r, mi_c);
15490 let (ox, oy) = (mi_c * 4, mi_r * 4);
15491 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
15492 let sample_y = |r: i32, c: i32| -> i32 {
15493 let (ny, nx) = (oy as i32 + r, ox as i32 + c);
15494 if ny < 0 || nx < 0 || ny as usize >= y_true_h || nx as usize >= y_true_w {
15495 CDEF_VERY_LARGE
15496 } else {
15497 i32::from(src_y[ny as usize * y_stride + nx as usize])
15498 }
15499 };
15500 // lane-cdef r1: the direction search reads the SAME padded
15501 // block the taps do -- libaom runs `cdef_find_dir` on the
15502 // prepared filter block (`cdef_block.c:296-320` over
15503 // `cdef_prepare_fb`'s buffer, `cdef.c:249-256`), whose columns
15504 // and rows past the mi-rounded frame extent are CDEF_VERY_LARGE.
15505 // Clamping to the last real sample instead made every straddling
15506 // edge 8x8 (odd `mi_cols`/`mi_rows`) pick a different var, hence
15507 // a different `adjust_strength`, hence a +-1 band at the crop edge.
15508 let (dir, var) = cdef_find_dir(coeff_shift, |r, c| sample_y(r as i32, c as i32));
15509
15510 // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
15511 // -- each plane zeroes the shared direction when *its own*
15512 // frame-level primary strength is 0, independent of the
15513 // per-block adjusted `t` and of the other plane's strength.
15514 let y_pri_strength = i32::from(cdef.y_pri_strength[sidx]) << coeff_shift;
15515 let y_sec_strength = i32::from(cdef.y_sec_strength[sidx]) << coeff_shift;
15516 let y_dir = if y_pri_strength != 0 { dir } else { 0 };
15517 let t = cdef_adjust_strength(y_pri_strength, var);
15518 // lane-cdef r1 rung: one line per filtered 8x8 luma CDEF unit.
15519 if std::env::var_os("EC_AV1_CDEF_DBG").is_some() {
15520 eprintln!(
15521 "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}"
15522 );
15523 }
15524 let enable_primary = t != 0;
15525 let enable_secondary = y_sec_strength != 0;
15526 if (ox + 8 > frame_w || oy + 8 > frame_h)
15527 && (enable_primary
15528 || enable_secondary
15529 || cdef.uv_pri_strength[sidx] != 0
15530 || cdef.uv_sec_strength[sidx] != 0)
15531 {
15532 CDEF_STRADDLE_UNITS.with(|c| c.set(c.get() + 1));
15533 }
15534 if enable_primary || enable_secondary {
15535 cdef_filter_block(
15536 sample_y,
15537 y,
15538 ox,
15539 oy,
15540 8,
15541 8,
15542 t,
15543 y_sec_strength,
15544 y_dir,
15545 damping,
15546 damping,
15547 enable_primary,
15548 enable_secondary,
15549 coeff_shift,
15550 );
15551 }
15552
15553 let t_uv = i32::from(cdef.uv_pri_strength[sidx]) << coeff_shift;
15554 let uv_sec_strength = i32::from(cdef.uv_sec_strength[sidx]) << coeff_shift;
15555 let uv_dir = if t_uv != 0 { dir } else { 0 };
15556 let enable_primary_uv = t_uv != 0;
15557 let enable_secondary_uv = uv_sec_strength != 0;
15558 if enable_primary_uv || enable_secondary_uv {
15559 let (cox, coy) = (ox / 2, oy / 2);
15560 for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] {
15561 let (tw, th) = (plane.true_width, plane.true_height);
15562 let stride = plane.width;
15563 let sample_uv = |r: i32, c: i32| -> i32 {
15564 let (ny, nx) = (coy as i32 + r, cox as i32 + c);
15565 if ny < 0 || nx < 0 || ny as usize >= th || nx as usize >= tw {
15566 CDEF_VERY_LARGE
15567 } else {
15568 i32::from(src_p[ny as usize * stride + nx as usize])
15569 }
15570 };
15571 cdef_filter_block(
15572 sample_uv,
15573 plane,
15574 cox,
15575 coy,
15576 4,
15577 4,
15578 t_uv,
15579 uv_sec_strength,
15580 uv_dir,
15581 damping_uv,
15582 damping_uv,
15583 enable_primary_uv,
15584 enable_secondary_uv,
15585 coeff_shift,
15586 );
15587 }
15588 }
15589 }
15590 mi_c += 2;
15591 }
15592 mi_r += 2;
15593 }
15594}
15595
15596/// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
15597/// ordering note: libaom also runs `superres_post_decode` between the two,
15598/// but this decoder never implements super-resolution, so there is nothing
15599/// to interleave). `deblocked_*` is each plane's post-deblock, pre-CDEF
15600/// buffer (the caller clones it before calling [`apply_cdef`]) -- loop
15601/// restoration's stripe-boundary rows read from it instead of the
15602/// CDEF-filtered plane, per `restoration.rs`'s own `lr_sample` doc comment.
15603#[allow(clippy::too_many_arguments)]
15604fn apply_loop_restoration(
15605 y: &mut PlaneBuf,
15606 u: &mut PlaneBuf,
15607 v: &mut PlaneBuf,
15608 deblocked_y: &PlaneBuf,
15609 deblocked_u: &PlaneBuf,
15610 deblocked_v: &PlaneBuf,
15611 lr: &LoopRestorationParams,
15612 grid: &crate::restoration::RestorationGrid,
15613 // lane-golomb r8: this frame header's own (cropped) luma size. Loop
15614 // restoration is the ONE post-decode filter that does NOT run over the
15615 // mi-rounded plane: libaom's `av1_loop_restoration_filter_frame` sizes
15616 // every plane with `av1_get_upsampled_plane_size` -- `plane_w =
15617 // ROUND_POWER_OF_TWO(cm->superres_upscaled_width, ss_x)`, `plane_h =
15618 // ROUND_POWER_OF_TWO(cm->height, ss_y)` (`av1/common/restoration.c:47`)
15619 // -- and asserts it equals the buffer's CROP width
15620 // (`restoration.c:1106`), then `av1_extend_frame(..., plane_w, plane_h,
15621 // ...)` (`restoration.c:1109`) replicates the right/bottom border from
15622 // that cropped edge before any unit is filtered. Deblock and CDEF DO
15623 // walk the mi grid, which is why passing `true_width`/`true_height`
15624 // here went unnoticed until a frame whose size is not a multiple of 8
15625 // (68 -> mi-rounded 72): the LR taps at the last four real columns then
15626 // read this decoder's own decoded samples at columns 68..71 where
15627 // libaom reads column 67 replicated -- +-1 over the straddling band
15628 // (class av1-truesize-lane: true frame size vs mi-rounded).
15629 (frame_w, frame_h): (usize, usize),
15630) {
15631 y.data = crate::restoration::apply_loop_restoration_plane(
15632 &y.data,
15633 &deblocked_y.data,
15634 y.width,
15635 frame_w,
15636 frame_h,
15637 0,
15638 lr.frame_restoration_type[0],
15639 lr.loop_restoration_size[0],
15640 grid,
15641 0,
15642 );
15643 u.data = crate::restoration::apply_loop_restoration_plane(
15644 &u.data,
15645 &deblocked_u.data,
15646 u.width,
15647 frame_w.div_ceil(2),
15648 frame_h.div_ceil(2),
15649 1,
15650 lr.frame_restoration_type[1],
15651 lr.loop_restoration_size[1],
15652 grid,
15653 1,
15654 );
15655 v.data = crate::restoration::apply_loop_restoration_plane(
15656 &v.data,
15657 &deblocked_v.data,
15658 v.width,
15659 frame_w.div_ceil(2),
15660 frame_h.div_ceil(2),
15661 1,
15662 lr.frame_restoration_type[2],
15663 lr.loop_restoration_size[2],
15664 grid,
15665 2,
15666 );
15667}
15668
15669/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
15670/// returning the picture it reconstructs to.
15671///
15672/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
15673/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
15674/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
15675/// `compute_image_size` derives one from the other, but not losslessly: a
15676/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
15677/// what the reconstruction is cropped to on the way out, mirroring
15678/// [`crate::encode::crop_encoded`].
15679///
15680/// # Errors
15681/// Returns an error when a block's partition, mode, skip flag or transform
15682/// type is anything this decoder does not reconstruct (round 2: inter, tx
15683/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
15684/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
15685/// or when the tile payload runs out of the symbols this decode expects (a
15686/// genuinely foreign stream).
15687pub fn decode_key_frame_tile(
15688 data: &[u8],
15689 mi_cols: u32,
15690 mi_rows: u32,
15691 base_q_idx: u8,
15692 frame_width: u32,
15693 frame_height: u32,
15694 enable_filter_intra: bool,
15695 cdef: &CdefParams,
15696 loop_filter: &LoopFilterParams,
15697 tx_select: bool,
15698 reduced_tx_set: bool,
15699 allow_screen_content_tools: bool,
15700 allow_intrabc: bool,
15701) -> Result<Picture> {
15702 let delta = DeltaParams::default();
15703 let single_tile = TileInfo {
15704 mi_col_starts: vec![0, mi_cols],
15705 mi_row_starts: vec![0, mi_rows],
15706 ..TileInfo::default()
15707 };
15708 decode_key_frame_tile_with_cdfs(
15709 &[data],
15710 &single_tile,
15711 mi_cols,
15712 mi_rows,
15713 base_q_idx,
15714 crate::quant::QuantDeltas::default(),
15715 frame_width,
15716 frame_height,
15717 enable_filter_intra,
15718 false,
15719 cdef,
15720 loop_filter,
15721 &LoopRestorationParams::default(),
15722 None,
15723 tx_select,
15724 reduced_tx_set,
15725 allow_screen_content_tools,
15726 allow_intrabc,
15727 delta,
15728 )
15729 .map(|(picture, _)| picture)
15730}
15731
15732thread_local! {
15733 /// lane-superres r3: the real decoded margin beyond `frame_width` up to
15734 /// the mi-aligned `true_width`, set by the most recent
15735 /// [`decode_key_frame_tile_with_cdfs`] OR (lane-superres r10)
15736 /// [`decode_inter_frame_tile_with_cdfs`] call -- both frame kinds crop
15737 /// their reconstructed buffer down from the same mi-aligned extent, so
15738 /// they share this one slot. See each function's own comment at its
15739 /// write site. `None` when there was no margin to save.
15740 static LAST_FRAME_WIDE_MARGIN: std::cell::RefCell<Option<Picture>> =
15741 const { std::cell::RefCell::new(None) };
15742}
15743
15744/// The margin the most recent key- or inter-frame tile decode stashed
15745/// (see [`LAST_FRAME_WIDE_MARGIN`]) -- `stream.rs`'s superres path
15746/// reads this immediately after the call, before any other frame
15747/// decode can overwrite it.
15748pub(crate) fn take_last_frame_wide_margin() -> Option<Picture> {
15749 LAST_FRAME_WIDE_MARGIN.with(|m| m.borrow_mut().take())
15750}
15751
15752/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
15753/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
15754/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
15755/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs,
15756/// since a key frame's own header always forces `primary_ref_frame ==
15757/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table
15758/// alongside the picture, for the caller to save into whichever reference
15759/// slots this frame's `refresh_frame_flags` names.
15760/// The order the 64x64 superblock quadrants of a tile are decoded in.
15761///
15762/// At `sb_size == 64` this is plain raster order over the tile's own
15763/// superblock grid. At `sb_size == 128` libaom's `decode_partition` recurses
15764/// each 128x128 superblock in raster order and visits its four 64x64
15765/// quadrants (TL, TR, BL, BR) before moving to the next superblock, so the
15766/// 64-level bodies must run in that nested order. `row_start` marks the first
15767/// item of each *superblock* row (where the left neighbour context resets),
15768/// `sb_start` the first item of each superblock (where the 128 root's own
15769/// loop-restoration units and partition symbol are read).
15770fn sb_visit_order(r0: u32, r1: u32, c0: u32, c1: u32, sb128: bool) -> Vec<(u32, u32, bool, bool)> {
15771 let mut out = Vec::new();
15772 if !sb128 {
15773 for r in r0..r1 {
15774 for c in c0..c1 {
15775 out.push((r, c, c == c0, true));
15776 }
15777 }
15778 return out;
15779 }
15780 let mut r = r0;
15781 while r < r1 {
15782 let mut first_in_row = true;
15783 let mut c = c0;
15784 while c < c1 {
15785 let mut first_in_sb = true;
15786 for qr in 0..2 {
15787 for qc in 0..2 {
15788 let (rr, cc) = (r + qr, c + qc);
15789 if rr >= r1 || cc >= c1 {
15790 continue;
15791 }
15792 out.push((rr, cc, first_in_row, first_in_sb));
15793 first_in_row = false;
15794 first_in_sb = false;
15795 }
15796 }
15797 c += 2;
15798 }
15799 r += 2;
15800 }
15801 out
15802}
15803
15804/// lane-sb128 r2: the 128x128 superblock root, shared by the key-frame and
15805/// the inter tile loop. Its loop-restoration units are read once for the whole
15806/// 128x128 (spec 5.11.57 is called with the superblock's own size), then one
15807/// partition symbol off the `BLOCK_128X128` CDF (8 symbols, no HORZ_4/VERT_4)
15808/// decides the root -- only SPLIT recurses into the four 64x64 quadrants this
15809/// decoder codes, the other seven arms refuse by name.
15810#[allow(clippy::too_many_arguments)]
15811thread_local! {
15812 /// How many 128x128 superblock roots resolved to `PARTITION_NONE` -- one
15813 /// whole 128x128 block (lane-sb128b r1's gate counter).
15814 pub(crate) static PART128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
15815 /// 128 roots that resolved to PARTITION_HORZ (two 128x64 pieces, or one
15816 /// when the bottom half is out of frame) -- lane-sb128c r7.
15817 pub(crate) static PART128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
15818 /// 128 roots that resolved to PARTITION_VERT (two 64x128 pieces).
15819 pub(crate) static PART128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
15820 /// Of those, the ones decided by the GATHERED bit at a frame edge -- the
15821 /// only shape a 1080p (mi_rows = 270) stream reaches.
15822 pub(crate) static PART128_EDGE_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
15823 pub(crate) static PART128_EDGE_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
15824 /// lane-sb128c r9: 128 roots that resolved to one of the four AB shapes,
15825 /// in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order.
15826 pub(crate) static PART128_AB_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
15827}
15828
15829/// [`PART128_AB_HITS`], for a gate's own before/after delta.
15830pub(crate) fn part128_ab_hits() -> [usize; 4] {
15831 PART128_AB_HITS.with(std::cell::Cell::get)
15832}
15833
15834/// [`PART128_NONE_HITS`], for a gate's own before/after delta.
15835pub(crate) fn part128_none_hits() -> usize {
15836 PART128_NONE_HITS.with(std::cell::Cell::get)
15837}
15838
15839/// [`PART128_HORZ_HITS`], for a gate's own before/after delta.
15840pub(crate) fn part128_horz_hits() -> usize {
15841 PART128_HORZ_HITS.with(std::cell::Cell::get)
15842}
15843
15844/// [`PART128_VERT_HITS`], for a gate's own before/after delta.
15845pub(crate) fn part128_vert_hits() -> usize {
15846 PART128_VERT_HITS.with(std::cell::Cell::get)
15847}
15848
15849/// [`PART128_EDGE_HORZ_HITS`] -- gathered-bit HORZ at the bottom frame edge.
15850pub(crate) fn part128_edge_horz_hits() -> usize {
15851 PART128_EDGE_HORZ_HITS.with(std::cell::Cell::get)
15852}
15853
15854/// [`PART128_EDGE_VERT_HITS`] -- gathered-bit VERT at the right frame edge.
15855pub(crate) fn part128_edge_vert_hits() -> usize {
15856 PART128_EDGE_VERT_HITS.with(std::cell::Cell::get)
15857}
15858
15859thread_local! {
15860 /// How many CHROMA transform units were coded inside a block whose uv
15861 /// plane block is more than one unit (lane-sb128b r2 -- only a 128x128
15862 /// block, four per plane).
15863 pub(crate) static CHROMA_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
15864}
15865
15866/// [`CHROMA_SPLIT_TX_HITS`], for a gate's own before/after delta.
15867pub(crate) fn chroma_split_tx_hits() -> usize {
15868 CHROMA_SPLIT_TX_HITS.with(std::cell::Cell::get)
15869}
15870
15871fn read_sb128_root(
15872 dec: &mut SymbolDecoder,
15873 cdfs: &mut Cdfs,
15874 neighbours: &Neighbours,
15875 lr: &LoopRestorationParams,
15876 lr_grid: &mut crate::restoration::RestorationGrid,
15877 lr_reference: &mut [(
15878 crate::restoration::WienerInfo,
15879 crate::restoration::SgrprojInfo,
15880 ); 3],
15881 sb_r: u32,
15882 sb_c: u32,
15883 mi_cols: u32,
15884 mi_rows: u32,
15885) -> Result<usize> {
15886 let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI);
15887 crate::restoration::read_lr(
15888 dec,
15889 cdfs,
15890 lr,
15891 lr_grid,
15892 lr_reference,
15893 mi_r128,
15894 mi_c128,
15895 SB_MI * 2,
15896 );
15897 let at128 = ((mi_r128 / SUB_MI) as usize, (mi_c128 / SUB_MI) as usize);
15898 let ctx128 = neighbours.partition_ctx(at128, 128);
15899 let (has_cols128, has_rows128) = (mi_c128 + SB_MI < mi_cols, mi_r128 + SB_MI < mi_rows);
15900 let part128 = if has_cols128 && has_rows128 {
15901 PART128_SYMBOLS.with(|c| c.set(c.get() + 1));
15902 let p = dec.symbol(&mut cdfs.partition_w128[ctx128]);
15903 if std::env::var_os("EC_AV1_TRACE").is_some() {
15904 eprintln!("TRACE partition_w128 ctx={ctx128} value={p}");
15905 }
15906 p
15907 } else {
15908 // lane-sb128 r4: the gathered half-out-of-frame reads DECIDE the
15909 // partition, they are not a forced split -- exactly the discarded-bit
15910 // defect the 64 root carries a comment about at `partition_w64`'s
15911 // gathered arm. Value 1 is SPLIT; 0 is HORZ (rows out of frame) or
15912 // VERT (cols out of frame), which the refusal below then names
15913 // instead of silently reconstructing a split.
15914 PART128_GATHERED_SYMBOLS.with(|c| c.set(c.get() + 1));
15915 match (has_cols128, has_rows128) {
15916 (true, false) => {
15917 if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &VERT_ALIKE128)) == 1 {
15918 PARTITION_SPLIT
15919 } else {
15920 PART128_EDGE_HORZ_HITS.with(|c| c.set(c.get() + 1));
15921 PARTITION_HORZ
15922 }
15923 }
15924 (false, true) => {
15925 if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &HORZ_ALIKE128)) == 1 {
15926 PARTITION_SPLIT
15927 } else {
15928 PART128_EDGE_VERT_HITS.with(|c| c.set(c.get() + 1));
15929 PARTITION_VERT
15930 }
15931 }
15932 _ => {
15933 PART128_GATHERED_SYMBOLS.with(|c| c.set(c.get() - 1));
15934 bump_edge_both_cut(3);
15935 PARTITION_SPLIT
15936 }
15937 }
15938 };
15939 // lane-sb128b r1: `PARTITION_NONE` -- one 128x128 block -- is decoded by
15940 // the key-frame caller below. The six remaining arms (HORZ/VERT and the
15941 // four AB shapes) still need the rect/AB machinery at this size.
15942 // lane-sb128c r7: HORZ (two 128x64) and VERT (two 64x128) now decode on
15943 // both tile paths. The four AB shapes (libaom `decode_partition`'s
15944 // PARTITION_HORZ_A..VERT_B, decodeframe.c) still need the mixed
15945 // 128x64 + 64x64 + 64x64 visit order and stay refused by name; a 128
15946 // root has no 1:4 arm at all (`PARTITION_HORZ_4`/`VERT_4` are excluded
15947 // for BLOCK_128X128 by `av1_get_partition_cdf`'s 8-symbol alphabet,
15948 // which stops at VERT_B).
15949 match part128 {
15950 PARTITION_SPLIT => PART128_SPLIT_HITS.with(|c| c.set(c.get() + 1)),
15951 PARTITION_NONE => PART128_NONE_HITS.with(|c| c.set(c.get() + 1)),
15952 PARTITION_HORZ => PART128_HORZ_HITS.with(|c| c.set(c.get() + 1)),
15953 PARTITION_VERT => PART128_VERT_HITS.with(|c| c.set(c.get() + 1)),
15954 // lane-sb128c r9: the four AB shapes at the 128 root -- one
15955 // 128x64/64x128 half plus two 64x64 quadrants, decoded by both tile
15956 // paths below in libaom `decode_partition`'s own visit order.
15957 p if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&p) => {
15958 PART128_AB_HITS.with(|c| {
15959 let mut h = c.get();
15960 h[p - PARTITION_HORZ_A] += 1;
15961 c.set(h);
15962 });
15963 }
15964 _ => {
15965 return Err(unsupported(
15966 "a 128x128 superblock partition value outside the 8-symbol alphabet",
15967 ));
15968 }
15969 }
15970 Ok(part128)
15971}
15972
15973pub(crate) fn decode_key_frame_tile_with_cdfs(
15974 tiles: &[&[u8]],
15975 tile_info: &TileInfo,
15976 mi_cols: u32,
15977 mi_rows: u32,
15978 base_q_idx: u8,
15979 // lane-sbpart r11: this frame header's own per-plane DC/AC quantizer
15980 // deltas (spec 5.9.12), threaded to [`QUANT_DELTAS`] at the top of every
15981 // tile alongside [`CURRENT_Q_IDX`].
15982 deltas: crate::quant::QuantDeltas,
15983 frame_width: u32,
15984 frame_height: u32,
15985 enable_filter_intra: bool,
15986 enable_edge_filter: bool,
15987 cdef: &CdefParams,
15988 loop_filter: &LoopFilterParams,
15989 lr: &LoopRestorationParams,
15990 initial_cdfs: Option<Cdfs>,
15991 tx_select: bool,
15992 reduced_tx_set: bool,
15993 allow_screen_content_tools: bool,
15994 allow_intrabc: bool,
15995 // lane-realworld r4: this frame header's own `delta` (spec 5.9.17/5.9.18)
15996 // -- only `q_present`/`q_res` are actually read ([`maybe_read_delta_q`]);
15997 // `stream.rs` still refuses a frame with `lf_present` set before this
15998 // function is ever called.
15999 delta: DeltaParams,
16000) -> Result<(Picture, Cdfs)> {
16001 if mi_cols == 0 || mi_rows == 0 {
16002 return Err(unsupported("a frame with no mode-info grid"));
16003 }
16004 ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));
16005 let sb128 = sb128();
16006 if sb128 && allow_intrabc {
16007 return Err(unsupported(
16008 "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)",
16009 ));
16010 }
16011 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
16012 INTRABC_MI_GRID.with(|g| {
16013 *g.borrow_mut() = allow_intrabc.then(|| {
16014 (
16015 crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize),
16016 mi_cols as usize,
16017 mi_rows as usize,
16018 )
16019 });
16020 });
16021 INTRABC_DV.with(|c| c.set(None));
16022 CDEF_BITS.with(|c| c.set(cdef.bits));
16023 CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
16024 CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
16025 DELTA_Q_PRESENT.with(|c| c.set(delta.q_present));
16026 DELTA_Q_RES.with(|c| c.set(1i32 << delta.q_res));
16027 DELTA_LF_PRESENT.with(|c| c.set(delta.lf_present));
16028 DELTA_LF_RES.with(|c| c.set(1i32 << delta.lf_res));
16029 DELTA_LF_MULTI.with(|c| c.set(delta.lf_multi));
16030 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
16031 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
16032 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
16033
16034 let mut y = PlaneBuf {
16035 data: vec![0u16; width * height],
16036 width,
16037 height,
16038 true_width,
16039 true_height,
16040 tile_x0: 0,
16041 tile_y0: 0,
16042 tile_x1: width,
16043 tile_y1: height,
16044 };
16045 let mut u = PlaneBuf {
16046 data: vec![0u16; width * height / 4],
16047 width: width / 2,
16048 height: height / 2,
16049 true_width: true_width / 2,
16050 true_height: true_height / 2,
16051 tile_x0: 0,
16052 tile_y0: 0,
16053 tile_x1: width / 2,
16054 tile_y1: height / 2,
16055 };
16056 let mut v = PlaneBuf {
16057 data: vec![0u16; width * height / 4],
16058 width: width / 2,
16059 height: height / 2,
16060 true_width: true_width / 2,
16061 true_height: true_height / 2,
16062 tile_x0: 0,
16063 tile_y0: 0,
16064 tile_x1: width / 2,
16065 tile_y1: height / 2,
16066 };
16067
16068 let scan32 = default_scan(TX32);
16069 let scan16 = default_scan(TX16);
16070 let scan8 = default_scan(TX8);
16071 let scan4 = default_scan(TX4);
16072
16073 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
16074 let mut result_cdfs = base_cdfs.clone();
16075 let mut neighbours = Neighbours::new(
16076 cols32 as usize * 2,
16077 rows32 as usize * 2,
16078 mi_cols as usize,
16079 mi_rows as usize,
16080 );
16081 let mut lr_grid = crate::restoration::RestorationGrid::new(lr, frame_width, frame_height);
16082 let mut lr_reference = [(
16083 crate::restoration::WienerInfo::default(),
16084 crate::restoration::SgrprojInfo::default(),
16085 ); 3];
16086
16087 // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its
16088 // own byte range and its own fresh copy of the frame's initial CDFs
16089 // (spec 5.11.2 `decode_tile`'s `init_symbol`); only the tile named by
16090 // `context_update_tile_id` has its end-of-tile adapted table kept as the
16091 // frame's own output (spec `exit_symbol`) -- every other tile's
16092 // adaptation is discarded, matching the refusal this replaces.
16093 for (tile_idx, &tile_bytes) in tiles.iter().enumerate() {
16094 let tile_num = tile_idx as u32;
16095 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
16096 let mi_row0 = tile_info.mi_row_starts[trow as usize];
16097 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
16098 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
16099 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
16100 // Tile boundaries are always superblock-aligned in mi units (spec
16101 // 5.9.15's uniform/non-uniform derivation both only ever emit
16102 // multiples of the superblock's own mi size), so plain division is
16103 // exact here -- no rounding needed.
16104 // `mi_row0`/`mi_col0` (this tile's own start, `0` or an interior
16105 // tile boundary) are always superblock-aligned by spec 5.9.15; the
16106 // frame's own true final edge (`mi_row_starts`/`mi_col_starts`'
16107 // last entry) is not, so the upper bound needs `div_ceil` the same
16108 // way the whole-frame `sb_rows`/`sb_cols` above does, to keep the
16109 // trailing partial superblock row/column in scope.
16110 let (sb_r0, sb_r1) = ((mi_row0 / SB_MI).min(sb_rows), mi_row1.div_ceil(SB_MI).min(sb_rows));
16111 let (sb_c0, sb_c1) = ((mi_col0 / SB_MI).min(sb_cols), mi_col1.div_ceil(SB_MI).min(sb_cols));
16112
16113 let mut cdfs = base_cdfs.clone();
16114 // spec `decode_tile`: `CurrentQIndex` resets to the frame's own
16115 // `base_q_idx` at the top of every tile, not once per frame.
16116 CURRENT_Q_IDX.with(|c| c.set(i32::from(base_q_idx)));
16117 QUANT_DELTAS.with(|c| c.set(deltas));
16118 CURRENT_DELTA_LF.with(|c| c.set([0; 4]));
16119 if std::env::var_os("EC_AV1_TRACE").is_some() {
16120 eprintln!(
16121 "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
16122 tile_bytes.len(),
16123 &tile_bytes[..tile_bytes.len().min(8)]
16124 );
16125 }
16126 let mut dec = SymbolDecoder::new(tile_bytes);
16127 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize);
16128 y.set_tile_origin(
16129 mi_col0 as usize * 4,
16130 mi_row0 as usize * 4,
16131 (mi_col1 as usize * 4).min(y.width),
16132 (mi_row1 as usize * 4).min(y.height),
16133 );
16134 u.set_tile_origin(
16135 mi_col0 as usize * 2,
16136 mi_row0 as usize * 2,
16137 (mi_col1 as usize * 2).min(u.width),
16138 (mi_row1 as usize * 2).min(u.height),
16139 );
16140 v.set_tile_origin(
16141 mi_col0 as usize * 2,
16142 mi_row0 as usize * 2,
16143 (mi_col1 as usize * 2).min(v.width),
16144 (mi_row1 as usize * 2).min(v.height),
16145 );
16146 TILE_HITS.with(|c| c.set(c.get() + 1));
16147
16148 // lane-sb128b r1: set when the 128 root resolved to `PARTITION_NONE` --
16149 // its one block covers all four 64x64 quadrants, so the remaining three
16150 // visits of this superblock code nothing at all.
16151 let mut sb128_none = false;
16152 for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) {
16153 if row_start {
16154 neighbours.start_row();
16155 }
16156 if sb_start {
16157 sb128_none = false;
16158 }
16159 if sb128_none {
16160 continue;
16161 }
16162 {
16163 // lane-sb128 r1: the 128 root. Its loop-restoration units are read
16164 // once for the whole 128x128 (spec 5.11.57 is called with the
16165 // superblock's own size), then one partition symbol off the
16166 // `BLOCK_128X128` CDF (8 symbols) decides the root -- only SPLIT
16167 // recurses into the four 64x64 quadrants this decoder codes.
16168 if sb128 && sb_start {
16169 let part128 = read_sb128_root(
16170 &mut dec,
16171 &mut cdfs,
16172 &neighbours,
16173 lr,
16174 &mut lr_grid,
16175 &mut lr_reference,
16176 sb_r,
16177 sb_c,
16178 mi_cols,
16179 mi_rows,
16180 )?;
16181 if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part128) {
16182 // lane-sb128c r9: the four AB shapes at the 128 root.
16183 // libaom `decode_partition` (decodeframe.c) codes each as
16184 // two `bsize2` (64x64) squares plus one `subsize`
16185 // (128x64 / 64x128) half, visited HORZ_A = TL, TR, bottom
16186 // half; HORZ_B = top half, BL, BR; VERT_A = TL, BL, right
16187 // half; VERT_B = left half, TR, BR. AB values only come
16188 // from the FULL alphabet symbol, which is only read when
16189 // both halves of the root are inside the frame, so no
16190 // piece needs libaom's `i > 0` frame-edge break (a piece
16191 // may still overhang the bottom/right, which
16192 // `PlaneBuf::reconstruct`'s r8 clip handles).
16193 sb128_none = true;
16194 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
16195 let (br, bc) = (at128.0 + 4, at128.1 + 4);
16196 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
16197 // Only the VERTICAL arms reorder the squares (TL, BL, TR,
16198 // BR), so only they switch libaom's `has_tr_vert_*` /
16199 // `has_bl_vert_*` tables (lane-sb128c r6 visit order).
16200 let _vert_ab =
16201 (part128 == PARTITION_VERT_A || part128 == PARTITION_VERT_B)
16202 .then(crate::encode::Reach::vert_ab_partition);
16203 // One `cdef_idx` literal per CODED BLOCK, at the first
16204 // non-skip one of each 64x64 CDEF unit; the 128x64 /
16205 // 64x128 half covers two units and its read lands in the
16206 // unit holding its origin, so that value is copied to the
16207 // other one (libaom: every mi of the block points at the
16208 // same `MB_MODE_INFO`).
16209 let cdef_copy = |src: (usize, usize), dst: (usize, usize)| {
16210 CDEF_IDX_GRID.with(|g| {
16211 let mut g = g.borrow_mut();
16212 let cols = CDEF_SB_COLS.with(|c| c.get());
16213 if cols == 0 {
16214 return;
16215 }
16216 let (si, di) = (
16217 (q_r + src.0) * cols + q_c + src.1,
16218 (q_r + dst.0) * cols + q_c + dst.1,
16219 );
16220 if q_c + src.1 < cols
16221 && q_c + dst.1 < cols
16222 && si < g.len()
16223 && di < g.len()
16224 {
16225 g[di] = g[si];
16226 }
16227 });
16228 };
16229 macro_rules! square64 {
16230 ($at:expr) => {{
16231 CDEF_TRANSMITTED.with(|c| c.set(false));
16232 decode_block(
16233 &mut dec,
16234 &mut cdfs,
16235 &mut neighbours,
16236 $at,
16237 SB,
16238 TxbSet::Luma64,
16239 TxbSet::Chroma32,
16240 TX32,
16241 TX32,
16242 (&scan32, &scan32),
16243 false,
16244 &mut y,
16245 &mut u,
16246 &mut v,
16247 base_q_idx,
16248 enable_filter_intra,
16249 allow_screen_content_tools,
16250 allow_intrabc,
16251 &scan32,
16252 &scan16,
16253 &scan8,
16254 &scan4,
16255 tx_select,
16256 reduced_tx_set,
16257 )?
16258 }};
16259 }
16260 macro_rules! half128 {
16261 ($at:expr, $bw:expr, $bh:expr, $src:expr, $dst:expr) => {{
16262 CDEF_TRANSMITTED.with(|c| c.set(false));
16263 decode_block_128rect(
16264 &mut dec,
16265 &mut cdfs,
16266 &mut neighbours,
16267 $at,
16268 $bw,
16269 $bh,
16270 &mut y,
16271 &mut u,
16272 &mut v,
16273 base_q_idx,
16274 enable_filter_intra,
16275 allow_screen_content_tools,
16276 tx_select,
16277 reduced_tx_set,
16278 )?;
16279 cdef_copy($src, $dst);
16280 }};
16281 }
16282 match part128 {
16283 PARTITION_HORZ_A => {
16284 square64!(at128);
16285 square64!((at128.0, bc));
16286 half128!((br, at128.1), 128, 64, (1, 0), (1, 1));
16287 }
16288 PARTITION_HORZ_B => {
16289 half128!(at128, 128, 64, (0, 0), (0, 1));
16290 square64!((br, at128.1));
16291 square64!((br, bc));
16292 }
16293 PARTITION_VERT_A => {
16294 square64!(at128);
16295 square64!((br, at128.1));
16296 half128!((at128.0, bc), 64, 128, (0, 1), (1, 1));
16297 }
16298 _ => {
16299 half128!(at128, 64, 128, (0, 0), (1, 0));
16300 square64!((at128.0, bc));
16301 square64!((br, bc));
16302 }
16303 }
16304 continue;
16305 }
16306 if matches!(part128, PARTITION_HORZ | PARTITION_VERT) {
16307 // lane-sb128c r8: libaom `decode_partition`
16308 // (decodeframe.c:1554) codes PARTITION_HORZ at the 128
16309 // root as `subsize = BLOCK_128X64` at (mi_row, mi_col)
16310 // plus a second one at (mi_row + hbs, mi_col) only
16311 // `if (mi_row + hbs < mi_rows)`; PARTITION_VERT mirrors it
16312 // on the column. `hbs` is `mi_size_high[BLOCK_128X128]/2`
16313 // = 16 mi. Both halves together cover the whole root, so
16314 // the remaining three 64x64 quadrant visits code nothing
16315 // (same flag the NONE arm sets).
16316 sb128_none = true;
16317 let horz = part128 == PARTITION_HORZ;
16318 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
16319 let (bw, bh) = if horz { (128usize, 64usize) } else { (64, 128) };
16320 for i in 0..2 {
16321 let at = if horz {
16322 (at128.0 + i * 4, at128.1)
16323 } else {
16324 (at128.0, at128.1 + i * 4)
16325 };
16326 let (blk_mi_r, blk_mi_c) = (at.0 * (SUB / MI), at.1 * (SUB / MI));
16327 if i > 0
16328 && (blk_mi_r >= mi_rows as usize || blk_mi_c >= mi_cols as usize)
16329 {
16330 break;
16331 }
16332 // Each half reads its OWN `cdef_idx` literal
16333 // (libaom `read_cdef` keys the `-1` test on the
16334 // block's own `MB_MODE_INFO`, and the two halves have
16335 // different ones).
16336 CDEF_TRANSMITTED.with(|c| c.set(false));
16337 decode_block_128rect(
16338 &mut dec,
16339 &mut cdfs,
16340 &mut neighbours,
16341 at,
16342 bw,
16343 bh,
16344 &mut y,
16345 &mut u,
16346 &mut v,
16347 base_q_idx,
16348 enable_filter_intra,
16349 allow_screen_content_tools,
16350 tx_select,
16351 reduced_tx_set,
16352 )?;
16353 }
16354 // One `cdef_idx` per BLOCK, copied to every 64x64 CDEF
16355 // unit it covers (the inter path's own fan-out).
16356 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
16357 CDEF_IDX_GRID.with(|g| {
16358 let mut g = g.borrow_mut();
16359 let cols = CDEF_SB_COLS.with(|c| c.get());
16360 if cols == 0 {
16361 return;
16362 }
16363 for (src, dst) in if horz {
16364 [((0, 0), (0, 1)), ((1, 0), (1, 1))]
16365 } else {
16366 [((0, 0), (1, 0)), ((0, 1), (1, 1))]
16367 } {
16368 let (si, di) = (
16369 (q_r + src.0) * cols + q_c + src.1,
16370 (q_r + dst.0) * cols + q_c + dst.1,
16371 );
16372 if q_c + src.1 < cols
16373 && q_c + dst.1 < cols
16374 && si < g.len()
16375 && di < g.len()
16376 {
16377 g[di] = g[si];
16378 }
16379 }
16380 });
16381 continue;
16382 }
16383 if part128 == PARTITION_NONE {
16384 // One 128x128 intra block: four TX_64X64 luma units and a
16385 // single 64x64 chroma unit per plane (`av1_get_max_uv_txsize`
16386 // of a 128x128 block is TX_64X64 over its 64x64 uv plane
16387 // block). No CfL, no filter intra, no palette at this size --
16388 // [`read_intra_mode`]'s own size gates already say so.
16389 sb128_none = true;
16390 CDEF_TRANSMITTED.with(|c| c.set(false));
16391 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
16392 decode_block(
16393 &mut dec,
16394 &mut cdfs,
16395 &mut neighbours,
16396 at128,
16397 SB * 2,
16398 TxbSet::Luma64,
16399 TxbSet::Chroma32,
16400 TX32,
16401 TX32,
16402 (&scan32, &scan32),
16403 false,
16404 &mut y,
16405 &mut u,
16406 &mut v,
16407 base_q_idx,
16408 enable_filter_intra,
16409 allow_screen_content_tools,
16410 allow_intrabc,
16411 &scan32,
16412 &scan16,
16413 &scan8,
16414 &scan4,
16415 tx_select,
16416 reduced_tx_set,
16417 )?;
16418 // libaom writes one `cdef_strength` into the block's own
16419 // `MB_MODE_INFO`, which every mi cell of the block --
16420 // hence all four 64x64 CDEF units -- points at; our grid
16421 // is per-unit, so the read (which only ever lands in the
16422 // top-left unit, `read_cdef`'s index 0) is copied across.
16423 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
16424 CDEF_IDX_GRID.with(|g| {
16425 let mut g = g.borrow_mut();
16426 let cols = CDEF_SB_COLS.with(|c| c.get());
16427 if cols > 0 && q_r * cols + q_c < g.len() {
16428 let idx = g[q_r * cols + q_c];
16429 for (dr, dc) in [(0, 1), (1, 0), (1, 1)] {
16430 let i = (q_r + dr) * cols + q_c + dc;
16431 if q_c + dc < cols && i < g.len() {
16432 g[i] = idx;
16433 }
16434 }
16435 }
16436 });
16437 continue;
16438 }
16439 }
16440 if !sb128 {
16441 crate::restoration::read_lr(
16442 &mut dec,
16443 &mut cdfs,
16444 lr,
16445 &mut lr_grid,
16446 &mut lr_reference,
16447 sb_r * SB_MI,
16448 sb_c * SB_MI,
16449 SB_MI,
16450 );
16451 }
16452 CDEF_TRANSMITTED.with(|c| c.set(false));
16453 let at = (sb_r as usize * 4, sb_c as usize * 4);
16454 let ctx = neighbours.partition_ctx(at, SB);
16455 let (has_cols, has_rows) = (
16456 sb_c * SB_MI + SB_MI / 2 < mi_cols,
16457 sb_r * SB_MI + SB_MI / 2 < mi_rows,
16458 );
16459 // Recomputed at this superblock's own half (spec
16460 // `decode_partition`): a full alphabet symbol when both halves are
16461 // inside the true frame, a single gathered bit when just one is
16462 // (the superblock cannot be left whole, so this is forced split),
16463 // and nothing at all (SPLIT inferred, no bits) when neither is —
16464 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
16465 // three-way write exactly.
16466 let part = if has_cols && has_rows {
16467 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
16468 if std::env::var_os("EC_AV1_TRACE").is_some() {
16469 eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
16470 }
16471 p
16472 } else {
16473 // lane-hgkf r1 (class `parsed-then-discarded`, same finding as
16474 // the unmerged lane-golomb r1): the gathered bit IS the
16475 // partition -- libaom `ec_read_partition_impl` returns
16476 // PARTITION_HORZ (resp. VERT) for 0 and only SPLIT for 1.
16477 // Forcing SPLIT desynced the last superblock row of every
16478 // frame whose height is not a multiple of 64: the ReelB key frames (3840x1608) diverge at mi_row=400 mi_col=0,
16479 // the first block of that row.
16480 match (has_cols, has_rows) {
16481 (true, false) => {
16482 trace_edge((sb_r * SB_MI) as usize, (sb_c * SB_MI) as usize, 12, ctx, dec.debug_state().0 as u32);
16483 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
16484 bump_edge32(4 + b.min(1) as usize);
16485 bump_edge_part(b.min(1) as usize);
16486 if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ }
16487 }
16488 (false, true) => {
16489 trace_edge((sb_r * SB_MI) as usize, (sb_c * SB_MI) as usize, 12, ctx, dec.debug_state().0 as u32);
16490 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
16491 bump_edge32(4 + b.min(1) as usize);
16492 bump_edge_part(b.min(1) as usize);
16493 if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT }
16494 }
16495 _ => {
16496 bump_edge_both_cut(2);
16497 PARTITION_SPLIT
16498 }
16499 }
16500 };
16501 match part {
16502 PARTITION_NONE => {
16503 decode_block(
16504 &mut dec,
16505 &mut cdfs,
16506 &mut neighbours,
16507 at,
16508 SB,
16509 TxbSet::Luma64,
16510 TxbSet::Chroma32,
16511 TX32,
16512 TX32,
16513 (&scan32, &scan32),
16514 false,
16515 &mut y,
16516 &mut u,
16517 &mut v,
16518 base_q_idx,
16519 enable_filter_intra,
16520 allow_screen_content_tools,
16521 allow_intrabc,
16522 &scan32,
16523 &scan16,
16524 &scan8,
16525 &scan4,
16526 tx_select,
16527 reduced_tx_set,
16528 )?;
16529 }
16530 PARTITION_SPLIT => {
16531 for q in 0..4 {
16532 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
16533 if r32 >= rows32 || c32 >= cols32 {
16534 continue;
16535 }
16536 let at32 = (r32 as usize * 2, c32 as usize * 2);
16537 let ctx32 = neighbours.partition_ctx(at32, BLOCK);
16538 let (has_cols32, has_rows32) = (
16539 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
16540 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
16541 );
16542 let part32 = if has_cols32 && has_rows32 {
16543 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
16544 if std::env::var_os("EC_AV1_TRACE").is_some() {
16545 let (rng, _) = dec.debug_state();
16546 eprintln!(
16547 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p} rng={rng}",
16548 r32 * BLOCK_MI,
16549 c32 * BLOCK_MI
16550 );
16551 }
16552 p
16553 } else {
16554 // lane-hgkf r1: the 32-level frame-edge bit is the
16555 // partition too (same libaom reader as the
16556 // superblock level above).
16557 match (has_cols32, has_rows32) {
16558 (true, false) => {
16559 trace_edge((r32 * BLOCK_MI) as usize, (c32 * BLOCK_MI) as usize, 9, ctx32, dec.debug_state().0 as u32);
16560 let b = dec.symbol_fixed(&gather(
16561 &cdfs.partition_w32[ctx32],
16562 VERT_ALIKE,
16563 ));
16564 bump_edge32(b.min(1) as usize);
16565 bump_edge_part(2 + b.min(1) as usize);
16566 if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ }
16567 }
16568 (false, true) => {
16569 trace_edge((r32 * BLOCK_MI) as usize, (c32 * BLOCK_MI) as usize, 9, ctx32, dec.debug_state().0 as u32);
16570 let b = dec.symbol_fixed(&gather(
16571 &cdfs.partition_w32[ctx32],
16572 HORZ_ALIKE,
16573 ));
16574 bump_edge32(b.min(1) as usize);
16575 bump_edge_part(2 + b.min(1) as usize);
16576 if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT }
16577 }
16578 _ => {
16579 bump_edge_both_cut(1);
16580 PARTITION_SPLIT
16581 }
16582 }
16583 };
16584 match part32 {
16585 PARTITION_NONE => {
16586 decode_block(
16587 &mut dec,
16588 &mut cdfs,
16589 &mut neighbours,
16590 at32,
16591 BLOCK,
16592 TxbSet::Luma32,
16593 TxbSet::Chroma16,
16594 TX32,
16595 TX16,
16596 (&scan32, &scan16),
16597 true,
16598 &mut y,
16599 &mut u,
16600 &mut v,
16601 base_q_idx,
16602 enable_filter_intra,
16603 allow_screen_content_tools,
16604 allow_intrabc,
16605 &scan32,
16606 &scan16,
16607 &scan8,
16608 &scan4,
16609 tx_select,
16610 reduced_tx_set,
16611 )?;
16612 }
16613 PARTITION_SPLIT => {
16614 for sub in 0..4 {
16615 let (sr, sc) =
16616 (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
16617 if (sr as u32) * SUB_MI >= mi_rows
16618 || (sc as u32) * SUB_MI >= mi_cols
16619 {
16620 continue;
16621 }
16622 let (has_cols16, has_rows16) = (
16623 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
16624 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
16625 );
16626 let at16 = (sr, sc);
16627 let ctx16 = neighbours.partition_ctx(at16, SUB);
16628 if has_cols16 && has_rows16 {
16629 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
16630 if std::env::var_os("EC_AV1_TRACE").is_some() {
16631 eprintln!(
16632 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}",
16633 at16.0, at16.1
16634 );
16635 }
16636 if part16 == PARTITION_NONE {
16637 decode_block(
16638 &mut dec,
16639 &mut cdfs,
16640 &mut neighbours,
16641 at16,
16642 SUB,
16643 TxbSet::Luma16,
16644 TxbSet::Chroma8,
16645 TX16,
16646 TX8,
16647 (&scan16, &scan8),
16648 true,
16649 &mut y,
16650 &mut u,
16651 &mut v,
16652 base_q_idx,
16653 enable_filter_intra,
16654 allow_screen_content_tools,
16655 allow_intrabc,
16656 &scan32,
16657 &scan16,
16658 &scan8,
16659 &scan4,
16660 tx_select,
16661 reduced_tx_set,
16662 )?;
16663 continue;
16664 }
16665 if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part16) {
16666 // lane-ab16 r1: the four AB (T-shaped) partitions at the 16x16
16667 // level -- two 8x8 squares plus one 16x8/8x16 strip. libaom's
16668 // `decode_partition` visit order (decodeframe.c):
16669 // HORZ_A: TL 8x8, TR 8x8, bottom 16x8
16670 // HORZ_B: top 16x8, BL 8x8, BR 8x8
16671 // VERT_A: TL 8x8, BL 8x8, right 8x16
16672 // VERT_B: left 8x16, TR 8x8, BR 8x8
16673 // The squares go through `decode_leaf8`, the strip through
16674 // `decode_leaf_rect` (real, non-skip 16x8/8x16 coefficients --
16675 // lane-rectx r2-r4; the older `decode_block_rect` this VERT_B arm
16676 // used refuses the non-skip case at this size). Both writers keep
16677 // mi-granular mode/skip/palette records, so a later block's
16678 // `above_mi`/`left_mi` sees the real sub-block, not the coarse
16679 // 16x16 cell.
16680 //
16681 // VERT_A/VERT_B visit TL,BL,TR,BR, so the bottom-left square's
16682 // top-right neighbour is the partition's own not-yet-decoded
16683 // rectangle: libaom switches those squares onto `has_tr_vert_*`/
16684 // `has_bl_vert_*` (`reconintra.c` `get_has_tr_table`), which is
16685 // `Reach::vert_ab_partition()` (lane-part32 r5, cherry-picked here).
16686 let arm = part16 - PARTITION_HORZ_A;
16687 bump_ab16(arm);
16688 if part16 == PARTITION_VERT_B {
16689 VERT_B_INTRA_HITS.with(|c| c.set(c.get() + 1));
16690 }
16691 let _vert_guard = if part16 == PARTITION_VERT_A || part16 == PARTITION_VERT_B {
16692 Some(crate::encode::Reach::vert_ab_partition())
16693 } else {
16694 None
16695 };
16696 let (mi_row0, mi_col0) = (sr * SUB_MI as usize, sc * SUB_MI as usize);
16697 macro_rules! ab_leaf8 {
16698 ($mi:expr, $prev:expr) => {
16699 decode_leaf8(
16700 &mut dec,
16701 &mut cdfs,
16702 &mut neighbours,
16703 at16,
16704 $mi,
16705 (&scan8, &scan4),
16706 $prev,
16707 &mut y,
16708 &mut u,
16709 &mut v,
16710 base_q_idx,
16711 enable_filter_intra,
16712 allow_screen_content_tools,
16713 allow_intrabc,
16714 tx_select,
16715 reduced_tx_set,
16716 )?
16717 };
16718 }
16719 macro_rules! ab_strip {
16720 ($mi:expr, $bw:expr, $bh:expr, $prev:expr) => {
16721 decode_leaf_rect(
16722 &mut dec,
16723 &mut cdfs,
16724 &mut neighbours,
16725 at16,
16726 $mi,
16727 $bw,
16728 $bh,
16729 $prev,
16730 &mut y,
16731 &mut u,
16732 &mut v,
16733 enable_filter_intra,
16734 allow_screen_content_tools,
16735 base_q_idx,
16736 tx_select,
16737 reduced_tx_set,
16738 )?
16739 };
16740 }
16741 let tl = (mi_row0, mi_col0);
16742 let tr = (mi_row0, mi_col0 + 2);
16743 let bl = (mi_row0 + 2, mi_col0);
16744 let br = (mi_row0 + 2, mi_col0 + 2);
16745 let mut done: Vec<((usize, usize), usize)> = Vec::new();
16746 match part16 {
16747 PARTITION_HORZ_A => {
16748 let m_tl = ab_leaf8!(tl, done.last().copied());
16749 done.push((tl, m_tl));
16750 let m_tr = ab_leaf8!(tr, done.last().copied());
16751 done.push((tr, m_tr));
16752 let m_bot = ab_strip!(bl, 16, 8, Some((tl, m_tl)));
16753 done.push((bl, m_bot));
16754 }
16755 PARTITION_HORZ_B => {
16756 let m_top = ab_strip!(tl, 16, 8, None);
16757 done.push((tl, m_top));
16758 let m_bl = ab_leaf8!(bl, done.last().copied());
16759 done.push((bl, m_bl));
16760 let m_br = ab_leaf8!(br, done.last().copied());
16761 done.push((br, m_br));
16762 }
16763 PARTITION_VERT_A => {
16764 let m_tl = ab_leaf8!(tl, done.last().copied());
16765 done.push((tl, m_tl));
16766 let m_bl = ab_leaf8!(bl, done.last().copied());
16767 done.push((bl, m_bl));
16768 let m_right = ab_strip!(tr, 8, 16, Some((tl, m_tl)));
16769 done.push((tr, m_right));
16770 }
16771 _ => {
16772 let m_left = ab_strip!(tl, 8, 16, None);
16773 done.push((tl, m_left));
16774 let m_tr = ab_leaf8!(tr, done.last().copied());
16775 done.push((tr, m_tr));
16776 let m_br = ab_leaf8!(br, done.last().copied());
16777 done.push((br, m_br));
16778 }
16779 }
16780 // Same coarse-slot write-back the real SPLIT path takes: the
16781 // 16x16 cell's single `above_mode`/`left_mode` entry gets the
16782 // sub-block on the parent's bottom / right edge (the mi-exact map
16783 // above wins wherever it has an entry).
16784 write_back_split_modes(&mut neighbours, &done, (mi_row0, mi_col0), (sr, sc));
16785 continue;
16786 }
16787 if part16 == PARTITION_HORZ {
16788 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
16789 let (mi_row0, mi_col0) = (
16790 sr as u32 * SUB_MI,
16791 sc as u32 * SUB_MI,
16792 );
16793 let top = (mi_row0 as usize, mi_col0 as usize);
16794 let bot = (mi_row0 as usize + 2, mi_col0 as usize);
16795 let mode_top = decode_leaf_rect(
16796 &mut dec,
16797 &mut cdfs,
16798 &mut neighbours,
16799 at16,
16800 top,
16801 16,
16802 8,
16803 None,
16804 &mut y,
16805 &mut u,
16806 &mut v,
16807 enable_filter_intra,
16808 allow_screen_content_tools,
16809 base_q_idx,
16810 tx_select,
16811 reduced_tx_set,
16812 )?;
16813 let mode_bot = decode_leaf_rect(
16814 &mut dec,
16815 &mut cdfs,
16816 &mut neighbours,
16817 at16,
16818 bot,
16819 16,
16820 8,
16821 Some((top, mode_top)),
16822 &mut y,
16823 &mut u,
16824 &mut v,
16825 enable_filter_intra,
16826 allow_screen_content_tools,
16827 base_q_idx,
16828 tx_select,
16829 reduced_tx_set,
16830 )?;
16831 neighbours.above_mode[sc] = mode_bot;
16832 neighbours.left_mode[sr] = mode_bot;
16833 continue;
16834 }
16835 if part16 == PARTITION_VERT {
16836 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
16837 let (mi_row0, mi_col0) = (
16838 sr as u32 * SUB_MI,
16839 sc as u32 * SUB_MI,
16840 );
16841 let left = (mi_row0 as usize, mi_col0 as usize);
16842 let right = (mi_row0 as usize, mi_col0 as usize + 2);
16843 let mode_left = decode_leaf_rect(
16844 &mut dec,
16845 &mut cdfs,
16846 &mut neighbours,
16847 at16,
16848 left,
16849 8,
16850 16,
16851 None,
16852 &mut y,
16853 &mut u,
16854 &mut v,
16855 enable_filter_intra,
16856 allow_screen_content_tools,
16857 base_q_idx,
16858 tx_select,
16859 reduced_tx_set,
16860 )?;
16861 let mode_right = decode_leaf_rect(
16862 &mut dec,
16863 &mut cdfs,
16864 &mut neighbours,
16865 at16,
16866 right,
16867 8,
16868 16,
16869 Some((left, mode_left)),
16870 &mut y,
16871 &mut u,
16872 &mut v,
16873 enable_filter_intra,
16874 allow_screen_content_tools,
16875 base_q_idx,
16876 tx_select,
16877 reduced_tx_set,
16878 )?;
16879 neighbours.above_mode[sc] = mode_right;
16880 neighbours.left_mode[sr] = mode_right;
16881 continue;
16882 }
16883 if part16 == PARTITION_HORZ_4
16884 || part16 == PARTITION_VERT_4
16885 {
16886 decode_rect4_16(
16887 &mut dec,
16888 &mut cdfs,
16889 &mut neighbours,
16890 at16,
16891 part16 == PARTITION_HORZ_4,
16892 &mut y,
16893 &mut u,
16894 &mut v,
16895 enable_filter_intra,
16896 allow_screen_content_tools,
16897 base_q_idx,
16898 tx_select,
16899 reduced_tx_set,
16900 )?;
16901 continue;
16902 }
16903 // lane-r14 r2 (verifier note): every
16904 // one of the 10 symbols this CDF can
16905 // produce is handled above, so SPLIT
16906 // is the only value that reaches
16907 // here -- the refusal that used to
16908 // stand here was unreachable and is
16909 // gone from `refusal_inventory`.
16910 debug_assert_eq!(part16, PARTITION_SPLIT);
16911 // A real (non-straddle) SPLIT of a
16912 // whole 16x16 into four 8x8 leaves --
16913 // the same recursion the straddle
16914 // path below already runs when the
16915 // true frame edge forces it, just
16916 // over all four positions instead of
16917 // the one or two the edge leaves.
16918 let (mi_row0, mi_col0) =
16919 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
16920 // Each 8x8 leaf's intra-mode context
16921 // must see its own siblings: the
16922 // bottom-left leaf's ABOVE neighbour
16923 // is leaf 0, not the previously
16924 // decoded leaf 1 (and the bottom-right
16925 // leaf's above is leaf 1, while
16926 // `prev_leaf` only ever carried the
16927 // immediately preceding one). The
16928 // coarse `above_mode`/`left_mode`
16929 // arrays hold one slot per 16x16, so
16930 // the sibling modes are swapped in
16931 // around each leaf call and restored
16932 // after; the loop tail writes the last
16933 // leaf's mode as before.
16934 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
16935 for i in 0..4 {
16936 let (mr, mc) =
16937 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
16938 let leaf_mi = (mr as usize, mc as usize);
16939 let li = i as usize;
16940 let saved_modes =
16941 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
16942 if li >= 2 {
16943 if let Some((below, _)) = sib_modes[li - 2] {
16944 neighbours.above_mode[sc] = below;
16945 }
16946 }
16947 if li % 2 == 1 {
16948 if let Some((_, right)) = sib_modes[li - 1] {
16949 neighbours.left_mode[sr] = right;
16950 }
16951 }
16952 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
16953 let part8 =
16954 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
16955 if std::env::var_os("EC_AV1_TRACE").is_some() {
16956 eprintln!(
16957 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
16958 );
16959 }
16960 let leaf_mode = if part8 == PARTITION_NONE {
16961 decode_leaf8(
16962 &mut dec,
16963 &mut cdfs,
16964 &mut neighbours,
16965 at16,
16966 leaf_mi,
16967 (&scan8, &scan4),
16968 None,
16969 &mut y,
16970 &mut u,
16971 &mut v,
16972 base_q_idx,
16973 enable_filter_intra,
16974 allow_screen_content_tools,
16975 allow_intrabc,
16976 tx_select,
16977 reduced_tx_set,
16978 ).map(|m| (m, m))?
16979 } else if part8 == PARTITION_SPLIT {
16980 decode_leaf_split4(
16981 &mut dec,
16982 &mut cdfs,
16983 &mut neighbours,
16984 at16,
16985 leaf_mi,
16986 &scan4,
16987 None,
16988 &mut y,
16989 &mut u,
16990 &mut v,
16991 base_q_idx,
16992 enable_filter_intra,
16993 allow_intrabc,
16994 reduced_tx_set,
16995 )?
16996 } else if part8 == PARTITION_HORZ
16997 || part8 == PARTITION_VERT
16998 {
16999 decode_leaf_rect8(
17000 &mut dec,
17001 &mut cdfs,
17002 &mut neighbours,
17003 at16,
17004 leaf_mi,
17005 part8 == PARTITION_VERT,
17006 &scan4,
17007 &mut y,
17008 &mut u,
17009 &mut v,
17010 base_q_idx,
17011 enable_filter_intra,
17012 allow_intrabc,
17013 tx_select,
17014 reduced_tx_set,
17015 )?
17016 } else {
17017 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
17018 };
17019 neighbours.above_mode[sc] = saved_modes.0;
17020 neighbours.left_mode[sr] = saved_modes.1;
17021 sib_modes[li] = Some(leaf_mode);
17022 }
17023 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
17024 neighbours.above_mode[sc] = below;
17025 }
17026 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
17027 neighbours.left_mode[sr] = right;
17028 }
17029 continue;
17030 }
17031 // The true edge falls inside this 16x16
17032 // leaf itself (mod-32==8 target sizes,
17033 // lane-av1-rect): one axis only -- an 8x8
17034 // leaf never itself straddles, so the
17035 // block splits cleanly along whichever
17036 // axis is short.
17037 // lane-edgeboth r1: when the true frame
17038 // edge cuts BOTH axes libaom's
17039 // `decode_partition` takes
17040 // `else if (!has_rows && !has_cols)
17041 // partition = PARTITION_SPLIT;` -- no
17042 // symbol of any kind is read, and the four
17043 // 8x8 children are then visited by the
17044 // same loop below, whose
17045 // `mr < mi_rows && mc < mi_cols` filter IS
17046 // libaom's own
17047 // `if (mi_row >= mi_rows || mi_col >= mi_cols) return;`
17048 // early return, so the three out-of-frame
17049 // quadrants get no neighbour or tx-grid
17050 // write.
17051 if !has_cols16 && !has_rows16 {
17052 bump_edge_both_cut(0);
17053 } else {
17054 // lane-golomb r1 (class
17055 // `parsed-then-discarded`): the gathered
17056 // bit IS the partition -- 0 names
17057 // PARTITION_HORZ (resp. VERT), only 1 is
17058 // SPLIT (libaom `ec_read_partition_impl`).
17059 // This path can only walk the four SPLIT
17060 // leaves, so a 0 refuses by name instead
17061 // of desyncing.
17062 trace_edge(sr * SUB_MI as usize, sc * SUB_MI as usize, 6, ctx16, dec.debug_state().0 as u32);
17063 let edge_split = if has_cols16 {
17064 dec.symbol_fixed(&gather(
17065 &cdfs.partition_w16[ctx16],
17066 VERT_ALIKE,
17067 ))
17068 } else {
17069 dec.symbol_fixed(&gather(
17070 &cdfs.partition_w16[ctx16],
17071 HORZ_ALIKE,
17072 ))
17073 };
17074 // lane-hgkf r1: slots 2/3 of
17075 // [`EDGE_PART_HITS`], the gate's proof the
17076 // non-SPLIT edge arm actually decoded.
17077 bump_edge_part(if edge_split == 1 { 3 } else { 2 });
17078 if edge_split == 0 {
17079 // lane-oddh r1: the strip IS decodable
17080 // -- libaom's `decode_partition` codes
17081 // only the FIRST half of an edge
17082 // HORZ/VERT (the second call is
17083 // guarded by the same has_rows/
17084 // has_cols test that made the
17085 // partition non-square), so one
17086 // 16x8 (resp. 8x16) strip covers the
17087 // whole visible band of a frame whose
17088 // height (resp. width) is 8 mod 16 --
17089 // the user's 3840x1608 film.
17090 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
17091 EDGE_RECT_STRIP_HITS.with(|c| c.set(c.get() + 1));
17092 let (mi_row0, mi_col0) =
17093 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
17094 let (bw, bh) = if has_cols16 { (16, 8) } else { (8, 16) };
17095 let mode = decode_leaf_rect(
17096 &mut dec,
17097 &mut cdfs,
17098 &mut neighbours,
17099 at16,
17100 (mi_row0 as usize, mi_col0 as usize),
17101 bw,
17102 bh,
17103 None,
17104 &mut y,
17105 &mut u,
17106 &mut v,
17107 enable_filter_intra,
17108 allow_screen_content_tools,
17109 base_q_idx,
17110 tx_select,
17111 reduced_tx_set,
17112 )?;
17113 neighbours.above_mode[sc] = mode;
17114 neighbours.left_mode[sr] = mode;
17115 continue;
17116 }
17117 }
17118 let (mi_row0, mi_col0) =
17119 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
17120 let leaf_positions: Vec<(u32, u32)> = (0..4)
17121 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
17122 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
17123 .collect();
17124 // See the sibling-mode note in the clean
17125 // SPLIT path above.
17126 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
17127 for (mr, mc) in leaf_positions {
17128 let leaf_mi = (mr as usize, mc as usize);
17129 let li = (((mr - mi_row0) / 2) * 2 + (mc - mi_col0) / 2)
17130 as usize;
17131 let saved_modes =
17132 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
17133 if li >= 2 {
17134 if let Some((below, _)) = sib_modes[li - 2] {
17135 neighbours.above_mode[sc] = below;
17136 }
17137 }
17138 if li % 2 == 1 {
17139 if let Some((_, right)) = sib_modes[li - 1] {
17140 neighbours.left_mode[sr] = right;
17141 }
17142 }
17143 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
17144 let pre8 = dec.debug_state().0;
17145 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
17146 if std::env::var_os("EC_AV1_TRACE").is_some() {
17147 eprintln!(
17148 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8} pre_rng={pre8}"
17149 );
17150 }
17151 let leaf_mode = if part8 == PARTITION_NONE {
17152 decode_leaf8(
17153 &mut dec,
17154 &mut cdfs,
17155 &mut neighbours,
17156 at16,
17157 leaf_mi,
17158 (&scan8, &scan4),
17159 None,
17160 &mut y,
17161 &mut u,
17162 &mut v,
17163 base_q_idx,
17164 enable_filter_intra,
17165 allow_screen_content_tools,
17166 allow_intrabc,
17167 tx_select,
17168 reduced_tx_set,
17169 ).map(|m| (m, m))?
17170 } else if part8 == PARTITION_SPLIT {
17171 decode_leaf_split4(
17172 &mut dec,
17173 &mut cdfs,
17174 &mut neighbours,
17175 at16,
17176 leaf_mi,
17177 &scan4,
17178 None,
17179 &mut y,
17180 &mut u,
17181 &mut v,
17182 base_q_idx,
17183 enable_filter_intra,
17184 allow_intrabc,
17185 reduced_tx_set,
17186 )?
17187 } else if part8 == PARTITION_HORZ
17188 || part8 == PARTITION_VERT
17189 {
17190 decode_leaf_rect8(
17191 &mut dec,
17192 &mut cdfs,
17193 &mut neighbours,
17194 at16,
17195 leaf_mi,
17196 part8 == PARTITION_VERT,
17197 &scan4,
17198 &mut y,
17199 &mut u,
17200 &mut v,
17201 base_q_idx,
17202 enable_filter_intra,
17203 allow_intrabc,
17204 tx_select,
17205 reduced_tx_set,
17206 )?
17207 } else {
17208 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
17209 };
17210 neighbours.above_mode[sc] = saved_modes.0;
17211 neighbours.left_mode[sr] = saved_modes.1;
17212 sib_modes[li] = Some(leaf_mode);
17213 }
17214 // `record()`'s `above_mode`/`left_mode`
17215 // write is a no-op at an 8x8 leaf's own
17216 // side, so force the write once the whole
17217 // 16x16 slot's leaves are done, from the
17218 // last leaf (mirrors the writer's r15
17219 // fix).
17220 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
17221 neighbours.above_mode[sc] = below;
17222 }
17223 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
17224 neighbours.left_mode[sr] = right;
17225 }
17226 }
17227 }
17228 PARTITION_HORZ => {
17229 // lane-intradisp r1: two true 32x16 strips.
17230 decode_block_rect(
17231 &mut dec,
17232 &mut cdfs,
17233 &mut neighbours,
17234 at32,
17235 32,
17236 16,
17237 &mut y,
17238 &mut u,
17239 &mut v,
17240 enable_filter_intra,
17241 allow_screen_content_tools,
17242 base_q_idx,
17243 tx_select,
17244 reduced_tx_set,
17245 )?;
17246 if !has_rows32 {
17247 bump_edge32(2);
17248 }
17249 // lane-hgkf r1: at the frame edge only the first half of the strip is
17250 // coded (libaom `decode_partition` guards the second half with the same
17251 // test that made this partition non-square).
17252 if has_rows32 {
17253 decode_block_rect(
17254 &mut dec,
17255 &mut cdfs,
17256 &mut neighbours,
17257 (at32.0 + 1, at32.1),
17258 32,
17259 16,
17260 &mut y,
17261 &mut u,
17262 &mut v,
17263 enable_filter_intra,
17264 allow_screen_content_tools,
17265 base_q_idx,
17266 tx_select,
17267 reduced_tx_set,
17268 )?;
17269 }
17270 }
17271 PARTITION_VERT => {
17272 // lane-intradisp r1: mirror of PARTITION_HORZ
17273 // above with width/height swapped.
17274 decode_block_rect(
17275 &mut dec,
17276 &mut cdfs,
17277 &mut neighbours,
17278 at32,
17279 16,
17280 32,
17281 &mut y,
17282 &mut u,
17283 &mut v,
17284 enable_filter_intra,
17285 allow_screen_content_tools,
17286 base_q_idx,
17287 tx_select,
17288 reduced_tx_set,
17289 )?;
17290 if !has_cols32 {
17291 bump_edge32(3);
17292 }
17293 // lane-hgkf r1: at the frame edge only the first half of the strip is
17294 // coded (libaom `decode_partition` guards the second half with the same
17295 // test that made this partition non-square).
17296 if has_cols32 {
17297 decode_block_rect(
17298 &mut dec,
17299 &mut cdfs,
17300 &mut neighbours,
17301 (at32.0, at32.1 + 1),
17302 16,
17303 32,
17304 &mut y,
17305 &mut u,
17306 &mut v,
17307 enable_filter_intra,
17308 allow_screen_content_tools,
17309 base_q_idx,
17310 tx_select,
17311 reduced_tx_set,
17312 )?;
17313 }
17314 }
17315 PARTITION_HORZ_A => {
17316 // lane-part32 r1: two 16x16 squares on top +
17317 // a true 32x16 strip below (mirrors
17318 // decode_inter_block's cd6cb6d HORZ_A: TL,
17319 // TR, bottom strip).
17320 INTRA_HORZ_A_HITS.with(|c| c.set(c.get() + 1));
17321 decode_block(
17322 &mut dec,
17323 &mut cdfs,
17324 &mut neighbours,
17325 at32,
17326 SUB,
17327 TxbSet::Luma16,
17328 TxbSet::Chroma8,
17329 TX16,
17330 TX8,
17331 (&scan16, &scan8),
17332 true,
17333 &mut y,
17334 &mut u,
17335 &mut v,
17336 base_q_idx,
17337 enable_filter_intra,
17338 allow_screen_content_tools,
17339 allow_intrabc,
17340 &scan32,
17341 &scan16,
17342 &scan8,
17343 &scan4,
17344 tx_select,
17345 reduced_tx_set,
17346 )?;
17347 decode_block(
17348 &mut dec,
17349 &mut cdfs,
17350 &mut neighbours,
17351 (at32.0, at32.1 + 1),
17352 SUB,
17353 TxbSet::Luma16,
17354 TxbSet::Chroma8,
17355 TX16,
17356 TX8,
17357 (&scan16, &scan8),
17358 true,
17359 &mut y,
17360 &mut u,
17361 &mut v,
17362 base_q_idx,
17363 enable_filter_intra,
17364 allow_screen_content_tools,
17365 allow_intrabc,
17366 &scan32,
17367 &scan16,
17368 &scan8,
17369 &scan4,
17370 tx_select,
17371 reduced_tx_set,
17372 )?;
17373 decode_block_rect(
17374 &mut dec,
17375 &mut cdfs,
17376 &mut neighbours,
17377 (at32.0 + 1, at32.1),
17378 32,
17379 16,
17380 &mut y,
17381 &mut u,
17382 &mut v,
17383 enable_filter_intra,
17384 allow_screen_content_tools,
17385 base_q_idx,
17386 tx_select,
17387 reduced_tx_set,
17388 )?;
17389 }
17390 PARTITION_HORZ_B => {
17391 // lane-part32 r1: a true 32x16 strip on top +
17392 // two 16x16 squares below (mirrors HORZ_A
17393 // with the strip/squares order flipped, same
17394 // shape as libaom decode_partition's HORZ_B).
17395 INTRA_HORZ_B_HITS.with(|c| c.set(c.get() + 1));
17396 decode_block_rect(
17397 &mut dec,
17398 &mut cdfs,
17399 &mut neighbours,
17400 at32,
17401 32,
17402 16,
17403 &mut y,
17404 &mut u,
17405 &mut v,
17406 enable_filter_intra,
17407 allow_screen_content_tools,
17408 base_q_idx,
17409 tx_select,
17410 reduced_tx_set,
17411 )?;
17412 decode_block(
17413 &mut dec,
17414 &mut cdfs,
17415 &mut neighbours,
17416 (at32.0 + 1, at32.1),
17417 SUB,
17418 TxbSet::Luma16,
17419 TxbSet::Chroma8,
17420 TX16,
17421 TX8,
17422 (&scan16, &scan8),
17423 true,
17424 &mut y,
17425 &mut u,
17426 &mut v,
17427 base_q_idx,
17428 enable_filter_intra,
17429 allow_screen_content_tools,
17430 allow_intrabc,
17431 &scan32,
17432 &scan16,
17433 &scan8,
17434 &scan4,
17435 tx_select,
17436 reduced_tx_set,
17437 )?;
17438 decode_block(
17439 &mut dec,
17440 &mut cdfs,
17441 &mut neighbours,
17442 (at32.0 + 1, at32.1 + 1),
17443 SUB,
17444 TxbSet::Luma16,
17445 TxbSet::Chroma8,
17446 TX16,
17447 TX8,
17448 (&scan16, &scan8),
17449 true,
17450 &mut y,
17451 &mut u,
17452 &mut v,
17453 base_q_idx,
17454 enable_filter_intra,
17455 allow_screen_content_tools,
17456 allow_intrabc,
17457 &scan32,
17458 &scan16,
17459 &scan8,
17460 &scan4,
17461 tx_select,
17462 reduced_tx_set,
17463 )?;
17464 }
17465 PARTITION_VERT_A => {
17466 // lane-part32 r1: mirror of HORZ_A with
17467 // width/height swapped (TL, BL, right 16x32
17468 // strip).
17469 INTRA_VERT_A_HITS.with(|c| c.set(c.get() + 1));
17470 let _vert_ab = crate::encode::Reach::vert_ab_partition();
17471 decode_block(
17472 &mut dec,
17473 &mut cdfs,
17474 &mut neighbours,
17475 at32,
17476 SUB,
17477 TxbSet::Luma16,
17478 TxbSet::Chroma8,
17479 TX16,
17480 TX8,
17481 (&scan16, &scan8),
17482 true,
17483 &mut y,
17484 &mut u,
17485 &mut v,
17486 base_q_idx,
17487 enable_filter_intra,
17488 allow_screen_content_tools,
17489 allow_intrabc,
17490 &scan32,
17491 &scan16,
17492 &scan8,
17493 &scan4,
17494 tx_select,
17495 reduced_tx_set,
17496 )?;
17497 decode_block(
17498 &mut dec,
17499 &mut cdfs,
17500 &mut neighbours,
17501 (at32.0 + 1, at32.1),
17502 SUB,
17503 TxbSet::Luma16,
17504 TxbSet::Chroma8,
17505 TX16,
17506 TX8,
17507 (&scan16, &scan8),
17508 true,
17509 &mut y,
17510 &mut u,
17511 &mut v,
17512 base_q_idx,
17513 enable_filter_intra,
17514 allow_screen_content_tools,
17515 allow_intrabc,
17516 &scan32,
17517 &scan16,
17518 &scan8,
17519 &scan4,
17520 tx_select,
17521 reduced_tx_set,
17522 )?;
17523 decode_block_rect(
17524 &mut dec,
17525 &mut cdfs,
17526 &mut neighbours,
17527 (at32.0, at32.1 + 1),
17528 16,
17529 32,
17530 &mut y,
17531 &mut u,
17532 &mut v,
17533 enable_filter_intra,
17534 allow_screen_content_tools,
17535 base_q_idx,
17536 tx_select,
17537 reduced_tx_set,
17538 )?;
17539 }
17540 PARTITION_VERT_B => {
17541 // lane-part32 r1: a true 16x32 strip on the
17542 // left + two 16x16 squares on the right
17543 // (libaom decode_partition VERT_B: left
17544 // strip, TR, BR).
17545 INTRA_VERT_B_HITS.with(|c| c.set(c.get() + 1));
17546 let _vert_ab = crate::encode::Reach::vert_ab_partition();
17547 decode_block_rect(
17548 &mut dec,
17549 &mut cdfs,
17550 &mut neighbours,
17551 at32,
17552 16,
17553 32,
17554 &mut y,
17555 &mut u,
17556 &mut v,
17557 enable_filter_intra,
17558 allow_screen_content_tools,
17559 base_q_idx,
17560 tx_select,
17561 reduced_tx_set,
17562 )?;
17563 decode_block(
17564 &mut dec,
17565 &mut cdfs,
17566 &mut neighbours,
17567 (at32.0, at32.1 + 1),
17568 SUB,
17569 TxbSet::Luma16,
17570 TxbSet::Chroma8,
17571 TX16,
17572 TX8,
17573 (&scan16, &scan8),
17574 true,
17575 &mut y,
17576 &mut u,
17577 &mut v,
17578 base_q_idx,
17579 enable_filter_intra,
17580 allow_screen_content_tools,
17581 allow_intrabc,
17582 &scan32,
17583 &scan16,
17584 &scan8,
17585 &scan4,
17586 tx_select,
17587 reduced_tx_set,
17588 )?;
17589 decode_block(
17590 &mut dec,
17591 &mut cdfs,
17592 &mut neighbours,
17593 (at32.0 + 1, at32.1 + 1),
17594 SUB,
17595 TxbSet::Luma16,
17596 TxbSet::Chroma8,
17597 TX16,
17598 TX8,
17599 (&scan16, &scan8),
17600 true,
17601 &mut y,
17602 &mut u,
17603 &mut v,
17604 base_q_idx,
17605 enable_filter_intra,
17606 allow_screen_content_tools,
17607 allow_intrabc,
17608 &scan32,
17609 &scan16,
17610 &scan8,
17611 &scan4,
17612 tx_select,
17613 reduced_tx_set,
17614 )?;
17615 }
17616 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
17617 // lane-tx64x16 r3: the 1:4 pair at the 32x32
17618 // level -- four 32x8 (or 8x32) strips in
17619 // raster order, `quarter_step` = 2 mi, with
17620 // libaom `decode_partition`'s own `i > 0`
17621 // frame-edge break.
17622 let horz = part32 == PARTITION_HORZ_4;
17623 let base_mi = (at32.0 * (SUB / MI), at32.1 * (SUB / MI));
17624 let mut prev: Option<((usize, usize), usize)> = None;
17625 for i in 0..4 {
17626 let strip_mi = if horz {
17627 (base_mi.0 + i * 2, base_mi.1)
17628 } else {
17629 (base_mi.0, base_mi.1 + i * 2)
17630 };
17631 if i > 0
17632 && (strip_mi.0 >= mi_rows as usize
17633 || strip_mi.1 >= mi_cols as usize)
17634 {
17635 break;
17636 }
17637 let (bw, bh) = if horz { (32, 8) } else { (8, 32) };
17638 let (mode, _uv) = decode_block_rect4(
17639 &mut dec,
17640 &mut cdfs,
17641 &mut neighbours,
17642 strip_mi,
17643 bw,
17644 bh,
17645 prev,
17646 &mut y,
17647 &mut u,
17648 &mut v,
17649 enable_filter_intra,
17650 allow_screen_content_tools,
17651 base_q_idx,
17652 tx_select,
17653 )?;
17654 prev = Some((strip_mi, mode));
17655 }
17656 }
17657 _ => {
17658 return Err(unsupported(format!(
17659 "a 32x32 partition type this decoder does not code (value={part32})"
17660 )));
17661 }
17662 }
17663 }
17664 }
17665 PARTITION_HORZ => {
17666 // lane-sbpart r2: two true 64x32 strips.
17667 decode_block_rect64(
17668 &mut dec,
17669 &mut cdfs,
17670 &mut neighbours,
17671 at,
17672 64,
17673 32,
17674 &mut y,
17675 &mut u,
17676 &mut v,
17677 enable_filter_intra,
17678 allow_screen_content_tools,
17679 base_q_idx,
17680 tx_select,
17681 reduced_tx_set,
17682 )?;
17683 if !has_rows {
17684 bump_edge32(6);
17685 }
17686 // lane-golomb r1: at the frame edge only the first half of the
17687 // strip is coded (libaom `decode_partition` guards the second
17688 // with the same has_rows test that made this partition non-square).
17689 if has_rows {
17690 decode_block_rect64(
17691 &mut dec,
17692 &mut cdfs,
17693 &mut neighbours,
17694 (at.0 + 2, at.1),
17695 64,
17696 32,
17697 &mut y,
17698 &mut u,
17699 &mut v,
17700 enable_filter_intra,
17701 allow_screen_content_tools,
17702 base_q_idx,
17703 tx_select,
17704 reduced_tx_set,
17705 )?;
17706 }
17707 }
17708 PARTITION_VERT => {
17709 // lane-sbpart r2: mirror of PARTITION_HORZ above with
17710 // width/height swapped.
17711 decode_block_rect64(
17712 &mut dec,
17713 &mut cdfs,
17714 &mut neighbours,
17715 at,
17716 32,
17717 64,
17718 &mut y,
17719 &mut u,
17720 &mut v,
17721 enable_filter_intra,
17722 allow_screen_content_tools,
17723 base_q_idx,
17724 tx_select,
17725 reduced_tx_set,
17726 )?;
17727 if !has_cols {
17728 bump_edge32(7);
17729 }
17730 // lane-golomb r1: at the frame edge only the first half of the
17731 // strip is coded (libaom `decode_partition` guards the second
17732 // with the same has_cols test that made this partition non-square).
17733 if has_cols {
17734 decode_block_rect64(
17735 &mut dec,
17736 &mut cdfs,
17737 &mut neighbours,
17738 (at.0, at.1 + 2),
17739 32,
17740 64,
17741 &mut y,
17742 &mut u,
17743 &mut v,
17744 enable_filter_intra,
17745 allow_screen_content_tools,
17746 base_q_idx,
17747 tx_select,
17748 reduced_tx_set,
17749 )?;
17750 }
17751 }
17752 PARTITION_HORZ_A | PARTITION_HORZ_B | PARTITION_VERT_A | PARTITION_VERT_B => {
17753 // lane-part32 r4: the four superblock-level AB arms, each
17754 // two 32x32 squares plus one 64x32/32x64 strip, in
17755 // libaom's own `decode_partition` order (decodeframe.c:
17756 // HORZ_A = TL, TR, bottom strip; HORZ_B = top strip, BL,
17757 // BR; VERT_A = TL, BL, right strip; VERT_B = left strip,
17758 // TR, BR). The pieces are exactly the ones already proven
17759 // by the `PARTITION_NONE`-under-SPLIT (32x32 square) and
17760 // `PARTITION_HORZ`/`VERT` (rect64 strip) arms above.
17761 SB_AB_HITS.with(|c| {
17762 let mut h = c.get();
17763 h[part - PARTITION_HORZ_A] += 1;
17764 c.set(h);
17765 });
17766 // lane-part32 r5: only the two VERTICAL arms reorder the
17767 // square sub-blocks (TL, BL, TR, BR), so only they switch
17768 // libaom's `has_tr`/`has_bl` tables.
17769 let _vert_ab = (part == PARTITION_VERT_A || part == PARTITION_VERT_B)
17770 .then(crate::encode::Reach::vert_ab_partition);
17771 macro_rules! square32 {
17772 ($at:expr) => {
17773 decode_block(
17774 &mut dec,
17775 &mut cdfs,
17776 &mut neighbours,
17777 $at,
17778 BLOCK,
17779 TxbSet::Luma32,
17780 TxbSet::Chroma16,
17781 TX32,
17782 TX16,
17783 (&scan32, &scan16),
17784 true,
17785 &mut y,
17786 &mut u,
17787 &mut v,
17788 base_q_idx,
17789 enable_filter_intra,
17790 allow_screen_content_tools,
17791 allow_intrabc,
17792 &scan32,
17793 &scan16,
17794 &scan8,
17795 &scan4,
17796 tx_select,
17797 reduced_tx_set,
17798 )?
17799 };
17800 }
17801 macro_rules! strip64 {
17802 ($at:expr, $bw:expr, $bh:expr) => {
17803 decode_block_rect64(
17804 &mut dec,
17805 &mut cdfs,
17806 &mut neighbours,
17807 $at,
17808 $bw,
17809 $bh,
17810 &mut y,
17811 &mut u,
17812 &mut v,
17813 enable_filter_intra,
17814 allow_screen_content_tools,
17815 base_q_idx,
17816 tx_select,
17817 reduced_tx_set,
17818 )?
17819 };
17820 }
17821 let (br, bc) = (at.0 + 2, at.1 + 2);
17822 match part {
17823 PARTITION_HORZ_A => {
17824 square32!(at);
17825 square32!((at.0, bc));
17826 strip64!((br, at.1), 64, 32);
17827 }
17828 PARTITION_HORZ_B => {
17829 strip64!(at, 64, 32);
17830 square32!((br, at.1));
17831 square32!((br, bc));
17832 }
17833 PARTITION_VERT_A => {
17834 square32!(at);
17835 square32!((br, at.1));
17836 strip64!((at.0, bc), 32, 64);
17837 }
17838 _ => {
17839 strip64!(at, 32, 64);
17840 square32!((at.0, bc));
17841 square32!((br, bc));
17842 }
17843 }
17844 }
17845 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
17846 // lane-tx64x16: the 1:4 pair at 64x64 -- four 64x16 (or
17847 // 16x64) strips in raster order. `decode_partition`
17848 // (`decodeframe.c`) steps by `quarter_step = mi_size / 4`
17849 // (4 mi = 16 px = one SUB unit here) and BREAKS at the
17850 // frame edge for `i > 0`, so a partial superblock codes
17851 // only the strips whose origin is inside the frame.
17852 let horz = part == PARTITION_HORZ_4;
17853 for i in 0..4 {
17854 let step_mi = i * (SB_MI as usize / 4);
17855 let (this_r_mi, this_c_mi) = if horz {
17856 (sb_r as usize * SB_MI as usize + step_mi, sb_c as usize * SB_MI as usize)
17857 } else {
17858 (sb_r as usize * SB_MI as usize, sb_c as usize * SB_MI as usize + step_mi)
17859 };
17860 if i > 0
17861 && (this_r_mi >= mi_rows as usize || this_c_mi >= mi_cols as usize)
17862 {
17863 break;
17864 }
17865 let strip_at = if horz { (at.0 + i, at.1) } else { (at.0, at.1 + i) };
17866 let (bw, bh) = if horz { (64, 16) } else { (16, 64) };
17867 decode_block_rect64(
17868 &mut dec,
17869 &mut cdfs,
17870 &mut neighbours,
17871 strip_at,
17872 bw,
17873 bh,
17874 &mut y,
17875 &mut u,
17876 &mut v,
17877 enable_filter_intra,
17878 allow_screen_content_tools,
17879 base_q_idx,
17880 tx_select,
17881 reduced_tx_set,
17882 )?;
17883 }
17884 }
17885 _ => {
17886 return Err(unsupported(
17887 "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4",
17888 ));
17889 }
17890 }
17891 }
17892 }
17893
17894 if tile_num == tile_info.context_update_tile_id {
17895 result_cdfs = cdfs;
17896 }
17897 }
17898
17899 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
17900 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
17901 // that isolate whether a decode-order frame's mismatch already exists
17902 // in reconstruction (this dump) vs is introduced by the loop filter
17903 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
17904 // Decode-order frame marker for the EC_OBMC / EC_TRACE_MODE ladders.
17905 if std::env::var_os("EC_OBMC").is_some() || std::env::var_os("EC_TRACE_MODE").is_some() {
17906 eprintln!(
17907 "EC_PICT idx={}",
17908 PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst)
17909 );
17910 }
17911 dump_stage16("EC_AV1_PREFILT_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
17912 if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") {
17913 use std::io::Write;
17914 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
17915 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
17916 let narrow = |p: &PlaneBuf| -> Vec<u8> { p.data.iter().map(|&s| s as u8).collect() };
17917 let _ = f.write_all(&narrow(&y));
17918 let _ = f.write_all(&narrow(&u));
17919 let _ = f.write_all(&narrow(&v));
17920 }
17921 } else {
17922 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
17923 }
17924 if let Ok(path) = std::env::var("EC_AV1_PREFILT_WIDE_DUMP") {
17925 use std::io::Write;
17926 static IDX2: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
17927 let idx = IDX2.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
17928 let crop_wide = |plane: &PlaneBuf| -> Vec<u8> {
17929 let mut out = Vec::with_capacity(plane.true_width * plane.true_height);
17930 for row in 0..plane.true_height {
17931 out.extend(plane.data[row * plane.width..][..plane.true_width].iter().map(|&s| s as u8));
17932 }
17933 out
17934 };
17935 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
17936 let _ = f.write_all(&crop_wide(&y));
17937 let _ = f.write_all(&crop_wide(&u));
17938 let _ = f.write_all(&crop_wide(&v));
17939 }
17940 }
17941 apply_deblock(
17942 &mut y,
17943 &mut u,
17944 &mut v,
17945 loop_filter,
17946 &neighbours,
17947 frame_width as usize,
17948 frame_height as usize,
17949 );
17950 let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());
17951 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
17952 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
17953 // dump above these bisect WHICH filter stage introduced a mismatch.
17954 dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v);
17955 dump_stage16("EC_AV1_POSTDEBLOCK_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
17956 apply_cdef(
17957 &mut y,
17958 &mut u,
17959 &mut v,
17960 cdef,
17961 &neighbours,
17962 (frame_width as usize, frame_height as usize),
17963 );
17964 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
17965 dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
17966 apply_loop_restoration(
17967 &mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid,
17968 (frame_width as usize, frame_height as usize),
17969 );
17970
17971 let (fw, fh) = (frame_width as usize, frame_height as usize);
17972 if fw == width && fh == height {
17973 LAST_FRAME_WIDE_MARGIN.with(|m| *m.borrow_mut() = None);
17974 return Ok((
17975 Picture {
17976 width,
17977 height,
17978 y: y.data,
17979 u: u.data,
17980 v: v.data,
17981 },
17982 result_cdfs,
17983 ));
17984 }
17985 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u16> {
17986 let mut out = Vec::with_capacity(w * h);
17987 for row in 0..h {
17988 out.extend(plane.data[row * plane.width..][..w].iter().copied());
17989 }
17990 out
17991 };
17992 // lane-superres r3: `true_width`/`true_height` (`mi_cols`/`mi_rows` * 4)
17993 // is the real reconstructed extent -- columns `[fw, true_width)` hold
17994 // genuine decoded samples (the last coding block straddles the frame
17995 // edge whenever `frame_width` isn't 8-sample aligned), not padding.
17996 // libaom's superres upscale runs on that buffer's own border-extended
17997 // margin, so it reads those real columns, not a synthetic replicate of
17998 // column `fw - 1`. Stash them for `stream.rs`'s superres path (a real
17999 // aomenc 43->64 stream pinned column-by-column against libaom's own
18000 // `av1_convolve_horiz_rs_c` via `scripts/superres-pin-harness.c` --
18001 // `row6-realedgeval` proved the replicate-of-`fw-1` padding this
18002 // decoder used before was off by 1 at the columns the tap window
18003 // reaches into that real margin; `None` when there is no margin (this
18004 // frame's `true_width`/`true_height` already equal `fw`/`fh`, e.g. a
18005 // non-superres frame whose width just isn't 32-block aligned).
18006 LAST_FRAME_WIDE_MARGIN.with(|m| {
18007 *m.borrow_mut() = if true_width > fw || true_height > fh {
18008 let yc = crop(&y, true_width, true_height);
18009 if let Ok(path) = std::env::var("EC_AV1_MARGIN_DUMP") {
18010 use std::io::Write;
18011 static IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
18012 let idx = IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
18013 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
18014 // corner-cut: this diagnostic dump stays 8-bit-narrowed
18015 // regardless of the stream's real bit depth (debug-only,
18016 // never read by a gate); widen if a >8-bit margin dump
18017 // is ever needed.
18018 let _ = f.write_all(&yc.iter().map(|&s| s as u8).collect::<Vec<u8>>());
18019 }
18020 }
18021 Some(Picture {
18022 width: true_width,
18023 height: true_height,
18024 y: yc,
18025 u: crop(&u, true_width.div_ceil(2), true_height.div_ceil(2)),
18026 v: crop(&v, true_width.div_ceil(2), true_height.div_ceil(2)),
18027 })
18028 } else {
18029 None
18030 }
18031 });
18032 Ok((
18033 Picture {
18034 width: fw,
18035 height: fh,
18036 y: crop(&y, fw, fh),
18037 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
18038 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
18039 },
18040 result_cdfs,
18041 ))
18042}
18043
18044/// `av1_get_pred_context_switchable_interp`'s context for `interp_filter[dir]`
18045/// -- `above`/`left` are the neighbour's own resolved index for this
18046/// direction (0..=2, or `3` = no info, spec `SWITCHABLE_FILTERS`).
18047/// `is_compound` folds in libaom `av1_get_pred_context_switchable_interp`'s
18048/// own `ctx_offset` term (`INTER_FILTER_COMP_OFFSET` = 4, added when *this*
18049/// block itself has a second reference) -- lane-av1idx: a stale "this
18050/// decoder never codes a compound reference" assumption baked this to
18051/// always-0, which desynced the CDF context bucket (not the decoded value
18052/// outright, hence small pixel deltas rather than a hard desync) the moment
18053/// lane-av1blend unmasked plain-average compound blocks on a Switchable-
18054/// filter frame.
18055fn switchable_interp_ctx(above: u8, left: u8, dir: usize, is_compound: bool) -> usize {
18056 let base = dir * 8 + if is_compound { 4 } else { 0 };
18057 let term = if left == above {
18058 left
18059 } else if left == 3 {
18060 above
18061 } else if above == 3 {
18062 left
18063 } else {
18064 3
18065 };
18066 base + term as usize
18067}
18068
18069/// Resolves the interpolation filter kernel(s) an inter block's motion
18070/// compensation reads (spec 5.11.10/5.11.20): a fixed-filter frame
18071/// (`interp_fixed = Some`) never reads a symbol; a `Switchable` frame
18072/// (`interp_fixed = None`) reads `interp_filter[0]` and, when
18073/// `enable_dual_filter`, a second `interp_filter[1]` -- unless
18074/// `force_regular` (this block's own `needs_interp_filter() == 0` case: a
18075/// `GLOBALMV` block, whose global motion is always `IDENTITY` in this
18076/// decoder's scope, spec 5.11.10's `large && YMode == GLOBALMV` branch),
18077/// which forces `EIGHTTAP` without reading anything.
18078#[allow(clippy::too_many_arguments)]
18079fn resolve_interp_filter(
18080 dec: &mut SymbolDecoder,
18081 cdfs: &mut Cdfs,
18082 interp_fixed: Option<mc::InterpFilterKind>,
18083 enable_dual_filter: bool,
18084 force_regular: bool,
18085 above: [u8; 2],
18086 left: [u8; 2],
18087 is_compound: bool,
18088) -> (mc::InterpFilterKind, mc::InterpFilterKind, [u8; 2]) {
18089 if let Some(kind) = interp_fixed {
18090 return (kind, kind, [3, 3]);
18091 }
18092 if force_regular {
18093 return (
18094 mc::InterpFilterKind::Regular,
18095 mc::InterpFilterKind::Regular,
18096 [0, 0],
18097 );
18098 }
18099 // libaom `av1_extract_interp_filter`/`read_mb_interp_filter`: the
18100 // symbol read at `dir=0` becomes the block's *vertical* (`y_filter`)
18101 // kernel, `dir=1` the *horizontal* (`x_filter`) one -- `dir` is not
18102 // "horizontal then vertical" despite `predict_with_filters`' own
18103 // `h_kind`/`v_kind` argument order, which is why this function returns
18104 // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`).
18105 let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound);
18106 if std::env::var_os("EC_AV1_IFDBG").is_some() {
18107 eprintln!(
18108 "IFDBG dir=0 ctx={ctx0} above={above:?} left={left:?} cdf={:?}",
18109 &cdfs.switchable_interp[ctx0][..3]
18110 );
18111 }
18112 let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8;
18113 let sym1 = if enable_dual_filter {
18114 let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound);
18115 if std::env::var_os("EC_AV1_IFDBG").is_some() {
18116 eprintln!(
18117 "IFDBG dir=1 ctx={ctx1} above={above:?} left={left:?} cdf={:?} sym0={sym0}",
18118 &cdfs.switchable_interp[ctx1][..3]
18119 );
18120 }
18121 dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8
18122 } else {
18123 sym0
18124 };
18125 if enable_dual_filter && sym0 != sym1 {
18126 DUAL_FILTER_DIFF_HITS.with(|c| c.set(c.get() + 1));
18127 }
18128 if std::env::var_os("EC_TRACE_MODE").is_some() {
18129 eprintln!(
18130 "EC_IF ctx0={ctx0} above={above:?} left={left:?} sym0={sym0} sym1={sym1} rng={}",
18131 dec.debug_state().0
18132 );
18133 }
18134 (
18135 mc::InterpFilterKind::from_switchable_symbol(sym1 as usize),
18136 mc::InterpFilterKind::from_switchable_symbol(sym0 as usize),
18137 [sym0, sym1],
18138 )
18139}
18140
18141/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`),
18142/// duplicating [`crate::tile`]'s private copy of the same rule.
18143pub(crate) fn intra_inter_ctx(
18144 has_above: bool,
18145 has_left: bool,
18146 above_inter: bool,
18147 left_inter: bool,
18148) -> usize {
18149 match (has_above, has_left) {
18150 (true, true) => {
18151 let (above_intra, left_intra) = (!above_inter, !left_inter);
18152 if above_intra && left_intra {
18153 3
18154 } else {
18155 usize::from(above_intra || left_intra)
18156 }
18157 }
18158 (true, false) => 2 * usize::from(!above_inter),
18159 (false, true) => 2 * usize::from(!left_inter),
18160 (false, false) => 0,
18161 }
18162}
18163
18164/// `CLASS0_SIZE << (class + 2)`, duplicating `crate::tile`'s private
18165/// `mv_class_base` (spec 3): the magnitude an `MV_CLASS_n` component's own
18166/// bits start counting from.
18167fn mv_class_base(class: usize) -> i32 {
18168 if class == 0 { 0 } else { 2i32 << (class + 2) }
18169}
18170
18171/// One motion vector component's non-zero diff (spec 5.11.32
18172/// `read_mv_component`), the inverse of [`crate::tile`]'s private
18173/// `write_mv_component`.
18174fn read_mv_component(
18175 dec: &mut SymbolDecoder,
18176 c: &mut MvComponentCdfs,
18177 allow_high_precision_mv: bool,
18178 force_integer_mv: bool,
18179) -> i32 {
18180 let sign = dec.symbol(&mut c.sign);
18181 let class = dec.symbol(&mut c.class);
18182 let local = if class == 0 {
18183 let bit = dec.symbol(&mut c.class0_bit);
18184 // spec 5.11.32 `mv_class0_fr`: not coded at all when the frame
18185 // forces integer motion vectors -- implicitly `3` (the top
18186 // fractional value) rather than read, else every symbol after it
18187 // in the tile desyncs by one read.
18188 let fr = if force_integer_mv {
18189 3
18190 } else {
18191 dec.symbol(&mut c.class0_fr[bit])
18192 };
18193 // spec 5.11.32 `mv_class0_hp`: read only when the frame allows
18194 // high-precision motion vectors, else implicitly 1 (the low bit
18195 // stays at half-pel precision) -- this crate's own writer always
18196 // leaves the flag off, but a foreign stream can set it per frame.
18197 let hp = if allow_high_precision_mv {
18198 dec.symbol(&mut c.class0_hp)
18199 } else {
18200 1
18201 };
18202 (bit << 3) | (fr << 1) | hp
18203 } else {
18204 let mut d = 0;
18205 for i in 0..class {
18206 d |= dec.symbol(&mut c.bit[i]) << i;
18207 }
18208 // spec 5.11.32 `mv_fr`: same force_integer_mv carve-out as
18209 // `mv_class0_fr` above.
18210 let fr = if force_integer_mv { 3 } else { dec.symbol(&mut c.fr) };
18211 let hp = if allow_high_precision_mv {
18212 dec.symbol(&mut c.hp)
18213 } else {
18214 1
18215 };
18216 (d << 3) | (fr << 1) | hp
18217 };
18218 let mag = mv_class_base(class) + local as i32 + 1;
18219 if sign == 1 { -mag } else { mag }
18220}
18221
18222/// A motion vector coded as a residual against `pred` (spec 5.11.32
18223/// `read_mv`), the inverse of [`crate::tile`]'s private `write_mv`.
18224fn read_mv(
18225 dec: &mut SymbolDecoder,
18226 mv_comp: &mut [MvComponentCdfs; 2],
18227 mv_joint: &mut [u16; 5],
18228 pred: (i32, i32),
18229 allow_high_precision_mv: bool,
18230 force_integer_mv: bool,
18231) -> (i32, i32) {
18232 let joint = dec.symbol(mv_joint);
18233 let mut diff = (0, 0);
18234 if joint == 2 || joint == 3 {
18235 diff.0 = read_mv_component(dec, &mut mv_comp[0], allow_high_precision_mv, force_integer_mv);
18236 }
18237 if joint == 1 || joint == 3 {
18238 diff.1 = read_mv_component(dec, &mut mv_comp[1], allow_high_precision_mv, force_integer_mv);
18239 }
18240 (pred.0 + diff.0, pred.1 + diff.1)
18241}
18242
18243/// One intrabc block's block vector (spec 5.11.13 `read_intrabc_info` ->
18244/// `assign_mv` with `use_intrabc`, libaom `assign_dv`/`av1_find_ref_dv`).
18245///
18246/// The predictor is the ordinary MV stack built against `INTRA_FRAME`
18247/// (`av1_find_mv_refs(..., INTRA_FRAME, ...)`): `nearestmv`, or `nearmv`
18248/// when that is zero, or -- when both are -- the fixed fallback DV one
18249/// superblock up, or `INTRABC_DELAY_PIXELS` (256) plus one superblock to the
18250/// left when this is the tile's first superblock row. The predictor is then
18251/// rounded to full pel, and the difference reads off the *dv* nmv context
18252/// (libaom `ndvc`) at full-pel precision (`MV_SUBPEL_NONE`: no `fr`/`hp`
18253/// symbols, exactly this decoder's `force_integer_mv` carve-out). No DRL
18254/// symbol is coded for a DV, so none of this can move the bitstream
18255/// position -- only the reconstructed vector.
18256fn read_intrabc_dv(
18257 dec: &mut SymbolDecoder,
18258 cdfs: &mut Cdfs,
18259 mi_r: usize,
18260 mi_c: usize,
18261 side: usize,
18262) -> (i32, i32) {
18263 const INTRABC_DELAY_PIXELS: i32 = 256;
18264 let n4 = side / MI;
18265 let stack_pred = INTRABC_MI_GRID.with(|g| {
18266 let g = g.borrow();
18267 g.as_ref().map(|(grid, mi_cols, mi_rows)| {
18268 let stack = crate::mvstack::find_mv_stack(
18269 grid, mi_r, mi_c, n4, n4, 0, /* INTRA_FRAME */
18270 *mi_cols, *mi_rows,
18271 );
18272 if stack.nearest_mv == (0, 0) {
18273 stack.near_mv
18274 } else {
18275 stack.nearest_mv
18276 }
18277 })
18278 });
18279 let mut pred = stack_pred.unwrap_or((0, 0));
18280 if pred == (0, 0) {
18281 // `av1_find_ref_dv` (mvref_common.c). Tile row start is 0 here (the
18282 // single-tile-row case every intrabc gate stream is).
18283 let sb_px = SB_MI as i32 * MI as i32;
18284 pred = if mi_r < SB_MI as usize {
18285 (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8)
18286 } else {
18287 (-sb_px * 8, 0)
18288 };
18289 }
18290 // "Ref DV should not have sub-pel" (`assign_dv`): floor to full pel.
18291 let pred = ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8);
18292 read_mv(dec, &mut cdfs.dv_comp, &mut cdfs.dv_joint, pred, false, true)
18293}
18294
18295/// A 1/8-pel motion vector component converted to the 1/16-pel offset
18296/// [`mc::predict`] takes, duplicating [`crate::encode`]'s private `mv_to_q4`
18297/// (its own doc comment explains the `*2`/`*1` luma/chroma split).
18298fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
18299 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
18300}
18301
18302impl PlaneBuf {
18303 /// Adds `residual` onto an already-computed `prediction` (motion
18304 /// compensation's output, rather than [`predict`]'s intra one), writing
18305 /// the clamped reconstruction into the plane at `(x, y)` -- the inter
18306 /// counterpart of [`PlaneBuf::reconstruct`].
18307 fn reconstruct_mc(
18308 &mut self,
18309 x: usize,
18310 y: usize,
18311 side: usize,
18312 prediction: &[u16],
18313 residual: &[i32],
18314 ) {
18315 self.reconstruct_mc_rect(x, y, side, side, side, prediction, residual);
18316 }
18317
18318 /// [`Self::reconstruct_mc`], writing only a `w`x`h` sub-rectangle of the
18319 /// `side`x`side` `prediction`/`residual` buffers (which stay `side`-square
18320 /// for stride/indexing) -- lane-partitions r1: a true rectangular HORZ/
18321 /// VERT strip is predicted at its enclosing square `side` (matching
18322 /// `HORZ_B`'s already-accepted square-context corner-cut, lane-warp r5)
18323 /// but only its own true `w`x`h` footprint is committed to the plane, so
18324 /// two strips sharing a square's coordinate origin never clobber each
18325 /// other's real pixels.
18326 fn reconstruct_mc_rect(
18327 &mut self,
18328 x: usize,
18329 y: usize,
18330 side: usize,
18331 w: usize,
18332 h: usize,
18333 prediction: &[u16],
18334 residual: &[i32],
18335 ) {
18336 // lane-sb128c r7: a 128x64 half of a 128 root at the BOTTOM frame edge
18337 // is the first block shape whose true footprint overhangs the padded
18338 // coding surface (mi_rows = 198 -> a plane 800 rows tall, block rows
18339 // 768..832). libaom reconstructs those rows into the frame buffer's
18340 // border; nothing reads them back, so they are simply dropped here.
18341 let (h, w) = (h.min(self.height.saturating_sub(y)), w.min(self.width.saturating_sub(x)));
18342 for row in 0..h {
18343 for col in 0..w {
18344 let sample = (i32::from(prediction[row * side + col]) + residual[row * side + col])
18345 .clamp(0, crate::decode::sample_max()) as u16;
18346 self.data[(y + row) * self.width + x + col] = sample;
18347 }
18348 }
18349 }
18350}
18351
18352/// Reads one inter-coded plane's transform block and reconstructs it by
18353/// adding its residual onto a motion-compensated `prediction` -- the inter
18354/// counterpart of [`read_plane`] (every inter transform this decoder reads is
18355/// `side`-square with no oversized-64 case, so there is no padded-grid
18356/// branch to mirror).
18357#[allow(clippy::too_many_arguments)]
18358fn read_inter_plane(
18359 dec: &mut SymbolDecoder,
18360 cdfs: &mut Cdfs,
18361 set: TxbSet,
18362 scan: &[u16],
18363 plane_idx: usize,
18364 around: (bool, bool, i32),
18365 tx_mode: usize,
18366 plane: &mut PlaneBuf,
18367 x: usize,
18368 y: usize,
18369 side: usize,
18370 base_q_idx: u8,
18371 prediction: &[u16],
18372 // lane-chromau: this block's own luma transform's *actual coded*
18373 // `tx_type` -- `av1_get_tx_type` (libaom `blockd.h`): an inter block's
18374 // chroma plane never codes its own `tx_type` symbol, but (unlike an
18375 // intra block, which falls back to `Intra_Mode_To_Tx_Type`) it inherits
18376 // the colocated luma transform's coded type, narrowed to the extended
18377 // set the CHROMA size selects ([`reduce_inherited_chroma_tx_type`]).
18378 // `None` for the luma call itself
18379 // (`plane_idx == 0`), where the `TxbSet`'s own symbol (or the true
18380 // `DCT_DCT` default at 32-point+) already resolves it without help.
18381 inherited_luma_tx_type: Option<TxType>,
18382 // lane-txselect: the luma `txb_skip_ctx` of a transform unit smaller than
18383 // its own block (spec `get_txb_ctx_general`'s `plane_bsize != tx_size`
18384 // branch, [`Neighbours::luma_skip_ctx`]) -- `None` for the whole-block
18385 // transform every non-var-tx caller reads, whose plane-0 context is the
18386 // lone-transform-unit 0.
18387 luma_skip_ctx: Option<usize>,
18388) -> Result<(Vec<i32>, TxType)> {
18389 let skip_ctx = if plane_idx == 0 {
18390 luma_skip_ctx.unwrap_or(0)
18391 } else {
18392 // lane-sb128c r1: on a CHROMA plane this same parameter carries
18393 // `get_txb_ctx`'s own offset instead -- `combine_entropy_contexts(..)`
18394 // is +7 normally and +10 when the plane block is LARGER than the
18395 // transform (a 128x128 block's 64x64 uv plane block with TX_32X32
18396 // units, AV1's only such case), and the `txb_skip_chroma_32` table
18397 // carries the offset-10 rows at +3 (lane-sb128b r3).
18398 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
18399 };
18400 let mut coding = cdfs.txb(set, tx_mode);
18401 let default_tx_type = match inherited_luma_tx_type {
18402 Some(t) => reduce_inherited_chroma_tx_type(t, side, side),
18403 None => TxType::DctDct,
18404 };
18405 let (grid, tx_type) = read_coeffs(
18406 dec,
18407 &mut coding,
18408 scan,
18409 skip_ctx,
18410 dc_sign_ctx(around.2),
18411 default_tx_type,
18412 None,
18413 )?;
18414 note_chroma_class1(plane_idx, tx_type);
18415 // lane-inter8 r1: a 64-point transform covers the whole 64x64 area but
18416 // codes only its top-left 32x32 of frequencies (spec 5.11.40) -- the
18417 // caller hands the 32-point `scan` there, and the coded corner goes into
18418 // the top-left of the true `side`-sized grid before dequantization
18419 // (dqDenom is keyed by the true size, not the corner's), mirroring
18420 // [`read_plane`]'s own `tx_side != side` branch. Every other transform
18421 // this decoder codes has `tx_side == side`, so this is inert below 64.
18422 let tx_side = side.min(32);
18423 let grid = if tx_side == side {
18424 grid
18425 } else {
18426 let mut full = vec![0i32; side * side];
18427 for row in 0..tx_side {
18428 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
18429 }
18430 full
18431 };
18432 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
18433 let residual = dequant_and_inverse_typed(&grid, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type);
18434 plane.reconstruct_mc(x, y, side, prediction, &residual);
18435 Ok((grid, tx_type))
18436}
18437
18438/// Spec 5.11.25's `single_ref_p1`..`p6` tree (reachable only once `comp_mode`
18439/// is known `SINGLE_REFERENCE` -- `decode_stream` refuses any frame with
18440/// `reference_select` set before this is ever called, so that read is never
18441/// needed here). `above_ref`/`left_ref` are `-1` for an intra/unavailable
18442/// neighbour, else the `1..=7` reference that neighbour coded (lane-av1refs).
18443fn read_single_ref(
18444 dec: &mut SymbolDecoder,
18445 cdfs: &mut Cdfs,
18446 above_ref: i8,
18447 above_ref1: Option<i8>,
18448 left_ref: i8,
18449 left_ref1: Option<i8>,
18450) -> i8 {
18451 let above = (above_ref > 0).then_some(above_ref);
18452 let left = (left_ref > 0).then_some(left_ref);
18453 let p1 = dec.symbol(&mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0]);
18454 let ref_frame = if p1 == 1 {
18455 let p2 = dec.symbol(&mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1]);
18456 if p2 == 1 {
18457 ALTREF_FRAME
18458 } else {
18459 let p6 = dec.symbol(&mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5]);
18460 if p6 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
18461 }
18462 } else {
18463 let p3 = dec.symbol(&mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2]);
18464 if p3 == 1 {
18465 let p5 = dec.symbol(&mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4]);
18466 if p5 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
18467 } else {
18468 let p4 = dec.symbol(&mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3]);
18469 if p4 == 1 { LAST2_FRAME } else { LAST_FRAME }
18470 }
18471 };
18472 if ref_frame != LAST_FRAME {
18473 NON_LAST_REF_HITS.with(|c| c.set(c.get() + 1));
18474 let c = match ref_frame {
18475 LAST2_FRAME => &LAST2_HITS,
18476 LAST3_FRAME => &LAST3_HITS,
18477 GOLDEN_FRAME => &GOLDEN_HITS,
18478 BWDREF_FRAME => &BWDREF_HITS,
18479 ALTREF2_FRAME => &ALTREF2_HITS,
18480 ALTREF_FRAME => &ALTREF_HITS,
18481 _ => unreachable!("read_single_ref only ever returns LAST_FRAME..=ALTREF_FRAME"),
18482 };
18483 c.with(|v| v.set(v.get() + 1));
18484 }
18485 ref_frame
18486}
18487
18488/// Spec 5.11.25's `comp_mode` (lane-av1comp): whether an inter block reads
18489/// `SINGLE_REFERENCE` or `COMPOUND_REFERENCE`, only reached once a frame's
18490/// `reference_select` header bit lets a block choose per-block instead of
18491/// fixing the mode. `above`/`left` are `None` for an intra/unavailable
18492/// neighbour, [`NeighbourRef`] for a coded one -- [`reference_mode_ctx`]'s
18493/// own doc. Called from [`decode_inter_block`] once its own `reference_select`
18494/// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same
18495/// way with a coarser (`LAST_FRAME`-only) neighbour shape.
18496/// Resolves a compound reference's own planes -- the same `ref_frame ==
18497/// LAST_FRAME -> ref_y/u/v, else other_refs[ref_frame]` lookup
18498/// [`decode_inter_block`]'s single-ref path already does, factored out so
18499/// the compound path can call it twice (lane-av1comp).
18500fn ref_planes<'a>(
18501 ref_frame: i8,
18502 ref_y: &'a PlaneBuf,
18503 ref_u: &'a PlaneBuf,
18504 ref_v: &'a PlaneBuf,
18505 other_refs: &'a RefSlots,
18506) -> Result<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)> {
18507 if ref_frame == LAST_FRAME {
18508 Ok((ref_y, ref_u, ref_v))
18509 } else {
18510 match other_refs[ref_frame as usize] {
18511 Some((ry, ru, rv)) => Ok((ry, ru, rv)),
18512 None => Err(unsupported(
18513 "a reference frame selected with no picture at this frame's own \
18514 ref_frame_idx slot for it",
18515 )),
18516 }
18517 }
18518}
18519
18520/// libaom `foreach_overlappable_nb_above` (`obmc.h`): walks the mi row
18521/// directly above this block's own column span, one bordering block at a
18522/// time (stepping by that neighbour's own `MiInfo::size`, which is always
18523/// `<= 16` since no block this decoder ever codes exceeds 64x64), collecting
18524/// every *inter* neighbour found (an intra or unset cell is skipped, one mi
18525/// unit at a time, and does not itself count as a step). `max_neighbors`
18526/// caller-bounds the scan: `1` for the eligibility check (any hit at all),
18527/// `av1_build_obmc_inter_prediction`'s own `max_neighbor_obmc` table for the
18528/// real blend pass. lane-intra16x4 r2: libaom's own "4-wide block, treat as
18529/// half of a chroma pair" merge (`obmc.h`'s `mi_step == 1` special case) IS
18530/// ported below -- the round-1 note that no block is narrower than 8px stopped
18531/// being true when the 1:4 partitions landed. A 16x4 / 4x16 strip has
18532/// `mi_size_high`/`mi_size_wide` 1, so libaom snaps the walk back to the pair's
18533/// even index, reads the ODD (chroma-carrying) half as the neighbour and steps
18534/// by 2. Measured: the 16x16 block right of a 16x16-level HORZ_4 partition
18535/// whose strip 0 is inter and strips 1..3 intra counted that inter strip as
18536/// overlappable here, while libaom's pair merge reads the INTRA strip 1 and
18537/// counts none -- so we read a `motion_mode` symbol libaom never wrote (class
18538/// `symbol-consumption-gap`), desyncing the tile at the next coefficient.
18539fn overlappable_above(
18540 grid: &MiGrid,
18541 mi_row: usize,
18542 mi_col: usize,
18543 bw4: usize,
18544 mi_cols: usize,
18545 max_neighbors: usize,
18546) -> Vec<(usize, usize, MiInfo, usize)> {
18547 let mut out = Vec::new();
18548 if mi_row == 0 {
18549 return out;
18550 }
18551 let end_col = (mi_col + bw4).min(mi_cols);
18552 let mut col = mi_col;
18553 while col < end_col && out.len() < max_neighbors {
18554 let cell = grid.get(mi_row - 1, col);
18555 let mut step = cell.map_or(1, |c| c.size).max(1).min(SB_MI as usize);
18556 let mut nb = cell;
18557 // lane-obmcrec r1: the mi the neighbour's `MiInfo` is actually taken
18558 // from -- the pair merge below moves it, and libaom reads that same
18559 // `mbmi`'s `interp_filters` (`av1_setup_build_prediction_by_above_pred`).
18560 let mut src = col;
18561 if step == 1 {
18562 // The pair merge: the walk snaps back to the pair's even column
18563 // and the ODD half (the chroma-carrying one) is the neighbour for
18564 // both -- a 4-wide 1:4 strip is never an OBMC source on its own.
18565 col &= !1;
18566 src = col + 1;
18567 nb = grid.get(mi_row - 1, src);
18568 step = 2;
18569 }
18570 if let Some(info) = nb {
18571 if info.is_inter {
18572 if src != col {
18573 OBMC_PAIR_FILTER_HITS.with(|c| c.set(c.get() + 1));
18574 }
18575 out.push((col - mi_col, step.min(end_col - col), *info, src - mi_col));
18576 }
18577 }
18578 col += step;
18579 }
18580 out
18581}
18582
18583/// `foreach_overlappable_nb_left`'s left-column mirror of
18584/// [`overlappable_above`] -- see its doc for the shared corner-cut.
18585fn overlappable_left(
18586 grid: &MiGrid,
18587 mi_row: usize,
18588 mi_col: usize,
18589 bh4: usize,
18590 mi_rows: usize,
18591 max_neighbors: usize,
18592) -> Vec<(usize, usize, MiInfo, usize)> {
18593 let mut out = Vec::new();
18594 if mi_col == 0 {
18595 return out;
18596 }
18597 let end_row = (mi_row + bh4).min(mi_rows);
18598 let mut row = mi_row;
18599 while row < end_row && out.len() < max_neighbors {
18600 let cell = grid.get(row, mi_col - 1);
18601 // Vertical walk steps by the neighbour's HEIGHT -- a 32x16 strip's
18602 // width (8) would swallow the strip below it.
18603 let mut step = cell.map_or(1, |c| c.size_h).max(1).min(SB_MI as usize);
18604 let mut nb = cell;
18605 // lane-obmcrec r1: see `overlappable_above`'s `src`.
18606 let mut src = row;
18607 if step == 1 {
18608 // The pair merge, left-column mirror: a 4-TALL neighbour (a 16x4
18609 // strip) is half of a chroma pair and the pair's SECOND row is the
18610 // neighbour for both.
18611 row &= !1;
18612 src = row + 1;
18613 nb = grid.get(src, mi_col - 1);
18614 step = 2;
18615 }
18616 if let Some(info) = nb {
18617 if info.is_inter {
18618 if src != row {
18619 OBMC_PAIR_FILTER_HITS.with(|c| c.set(c.get() + 1));
18620 }
18621 out.push((row - mi_row, step.min(end_row - row), *info, src - mi_row));
18622 }
18623 }
18624 row += step;
18625 }
18626 out
18627}
18628
18629/// The warp-sample gather's own `has_top_right` probe (libaom `av1_findSamples`
18630/// calls the same `mvref_common.c` function the MV stack does). lane-sb128 r2:
18631/// this used to hardcode `SB_MI` (a 64x64 superblock) -- at `sb_size == 128`
18632/// libaom's mask loop runs one level further and strips the top-right sample
18633/// off blocks whose neighbour IS decoded, so a warped 128-superblock frame
18634/// picked up wrong warp parameters (frame 6 of the 128 inter gate). Delegates
18635/// to the single sb-aware port in [`crate::mvstack::has_top_right`]; `bs` is
18636/// the block's own side in 4x4 (`mi`) units (square inter leaves only here).
18637fn has_top_right(mi_row: usize, mi_col: usize, bs: usize) -> bool {
18638 crate::mvstack::has_top_right(mi_row, mi_col, bs, bs)
18639}
18640
18641/// `av1_findSamples` (`mvref_common.c`), full port: the up to
18642/// `LEAST_SQUARES_SAMPLES_MAX` (8) above/left/top-left/top-right neighbour
18643/// samples (`record_samples`) that share this block's own single reference
18644/// frame and are themselves single-ref -- `mbmi->num_proj_ref` is
18645/// `.len()` of the returned vec. `bw4` is the block's own side in 4x4 units
18646/// (square, so also `bh4`; a real block's `xd->width`/`xd->height` in
18647/// libaom are also mi units of that same square side here). Each sample's
18648/// own `bw`/`bh` (fed to [`crate::warp::record_sample`]'s offset formula)
18649/// come from the *neighbour* cell's own coded size, not this block's.
18650#[allow(clippy::too_many_arguments)]
18651fn find_samples(
18652 grid: &MiGrid,
18653 mi_row: usize,
18654 mi_col: usize,
18655 bw4: usize,
18656 bh4: usize,
18657 mi_cols: usize,
18658 mi_rows: usize,
18659 ref_frame: i8,
18660) -> Vec<crate::warp::Sample> {
18661 const MAX: usize = crate::warp::LEAST_SQUARES_SAMPLES_MAX;
18662 let up_available = mi_row > 0;
18663 let left_available = mi_col > 0;
18664 let mut samples = Vec::with_capacity(MAX);
18665 let single_ref_match = |info: &MiInfo| info.ref_frame == ref_frame && info.ref_frame1.is_none();
18666 let mut do_tl = true;
18667 let mut do_tr = true;
18668 let rec = |info: &MiInfo, row_offset: i32, sign_r: i32, col_offset: i32, sign_c: i32| {
18669 let nb_bw = (info.size * 4) as i32;
18670 // lane-rect r2: the neighbour's own true height -- a rect strip
18671 // neighbour donates its sample at ITS center (aom pts y=-72 for a
18672 // 32x16 above strip; the square assumption put it at -136).
18673 let nb_bh = (info.size_h * 4) as i32;
18674 crate::warp::record_sample(nb_bw, nb_bh, info.mv, row_offset, sign_r, col_offset, sign_c)
18675 };
18676
18677 'outer: {
18678 if up_available {
18679 let above = grid.get(mi_row - 1, mi_col);
18680 let superblock_width = above.map_or(1, |c| c.size).max(1);
18681 if bw4 <= superblock_width {
18682 let col_offset = -((mi_col % superblock_width) as isize);
18683 if col_offset < 0 {
18684 do_tl = false;
18685 }
18686 if col_offset + superblock_width as isize > bw4 as isize {
18687 do_tr = false;
18688 }
18689 if let Some(info) = above {
18690 if single_ref_match(info) {
18691 samples.push(rec(info, 0, -1, col_offset as i32, 1));
18692 if samples.len() >= MAX {
18693 break 'outer;
18694 }
18695 }
18696 }
18697 } else {
18698 let mut i = 0usize;
18699 let limit = bw4.min(mi_cols.saturating_sub(mi_col));
18700 while i < limit {
18701 let cell = grid.get(mi_row - 1, mi_col + i);
18702 let sw = cell.map_or(1, |c| c.size).max(1);
18703 if let Some(info) = cell {
18704 if single_ref_match(info) {
18705 samples.push(rec(info, 0, -1, i as i32, 1));
18706 if samples.len() >= MAX {
18707 break 'outer;
18708 }
18709 }
18710 }
18711 i += sw;
18712 }
18713 }
18714 }
18715
18716 if left_available {
18717 let left = grid.get(mi_row, mi_col - 1);
18718 let superblock_height = left.map_or(1, |c| c.size_h).max(1);
18719 if bh4 <= superblock_height {
18720 let row_offset = -((mi_row % superblock_height) as isize);
18721 if row_offset < 0 {
18722 do_tl = false;
18723 }
18724 if let Some(info) = left {
18725 if single_ref_match(info) {
18726 samples.push(rec(info, row_offset as i32, 1, 0, -1));
18727 if samples.len() >= MAX {
18728 break 'outer;
18729 }
18730 }
18731 }
18732 } else {
18733 let mut i = 0usize;
18734 let limit = bh4.min(mi_rows.saturating_sub(mi_row));
18735 while i < limit {
18736 let cell = grid.get(mi_row + i, mi_col - 1);
18737 let sh = cell.map_or(1, |c| c.size_h).max(1);
18738 if let Some(info) = cell {
18739 if single_ref_match(info) {
18740 samples.push(rec(info, i as i32, 1, 0, -1));
18741 if samples.len() >= MAX {
18742 break 'outer;
18743 }
18744 }
18745 }
18746 i += sh;
18747 }
18748 }
18749 }
18750
18751 if do_tl && left_available && up_available {
18752 if let Some(info) = grid.get(mi_row - 1, mi_col - 1) {
18753 if single_ref_match(info) {
18754 samples.push(rec(info, 0, -1, 0, -1));
18755 if samples.len() >= MAX {
18756 break 'outer;
18757 }
18758 }
18759 }
18760 }
18761
18762 if do_tr && has_top_right(mi_row, mi_col, bw4) {
18763 let tr_col = mi_col + bw4;
18764 if mi_row > 0 && tr_col < mi_cols {
18765 if let Some(info) = grid.get(mi_row - 1, tr_col) {
18766 if single_ref_match(info) {
18767 samples.push(rec(info, 0, -1, bw4 as i32, 1));
18768 }
18769 }
18770 }
18771 }
18772 }
18773 samples
18774}
18775
18776/// `mbmi->num_proj_ref`: [`find_samples`]'s own count, all that
18777/// `motion_mode_allowed` needs to pick the 3-symbol `motion_mode_cdf` over
18778/// the 2-symbol `obmc_cdf` (spec 5.11.24).
18779#[allow(clippy::too_many_arguments)]
18780fn num_proj_ref(
18781 grid: &MiGrid,
18782 mi_row: usize,
18783 mi_col: usize,
18784 bw4: usize,
18785 bh4: usize,
18786 mi_cols: usize,
18787 mi_rows: usize,
18788 ref_frame: i8,
18789) -> u8 {
18790 find_samples(grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame).len() as u8
18791}
18792
18793/// `av1_get_obmc_mask` (`reconinter.c`): the per-position blend weight
18794/// (`AOM_BLEND_A64` numerator, out of 64) for the neighbour's own
18795/// contribution's *complement* -- i.e. `dst = (mask*orig + (64-mask)*nbr +
18796/// 32) >> 6`, low near the shared border (heavier neighbour weight) rising
18797/// to 64 (no neighbour contribution) away from it. Only the lengths this
18798/// decoder's own overlap sizes ever produce (luma 8/16/32, chroma 4/8/16)
18799/// are transcribed.
18800fn obmc_mask(len: usize) -> &'static [u8] {
18801 // lane-gmaffine r1: the two SHORT masks (libaom `reconinter.c`
18802 // `obmc_mask_1`/`obmc_mask_2`) -- an 8x8 leaf's chroma plane is 4x4, so
18803 // its overlap is 2 (and 1 at a half-block edge). Unreachable until this
18804 // round wired interior 16x16 splits down to real 8x8 leaves, where the
18805 // old `unreachable!()` below fired as a hard panic.
18806 const M1: [u8; 1] = [64];
18807 // lane-inter8 r1: `obmc_mask_2` (`reconinter.c` 753) -- reached by the
18808 // LEFT pass of an 8x8 block's chroma plane (overlap 4 luma columns, 2
18809 // chroma), which only became live once 8x8 inter leaves stopped being
18810 // refused.
18811 const M2: [u8; 2] = [45, 64];
18812 const M4: [u8; 4] = [39, 50, 59, 64];
18813 const M8: [u8; 8] = [36, 42, 48, 53, 57, 61, 64, 64];
18814 const M16: [u8; 16] = [
18815 34, 37, 40, 43, 46, 49, 52, 54, 56, 58, 60, 61, 64, 64, 64, 64,
18816 ];
18817 const M32: [u8; 32] = [
18818 33, 35, 36, 38, 40, 41, 43, 44, 45, 47, 48, 50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 60,
18819 61, 62, 64, 64, 64, 64, 64, 64, 64, 64,
18820 ];
18821 match len {
18822 1 => &M1,
18823 2 => &M2,
18824 4 => &M4,
18825 8 => &M8,
18826 16 => &M16,
18827 32 => &M32,
18828 _ => unreachable!("obmc overlap length outside this decoder's own block-size range"),
18829 }
18830}
18831
18832/// A bordering block's own resolved interp filter kernel, `(h, v)` --
18833/// mirrors [`resolve_interp_filter`]'s own return order from its stored
18834/// `[u8; 2]` (`Neighbours::above_filter`/`left_filter`, `[sym0, sym1]` =
18835/// `[v_sym, h_sym]`). The `[3, 3]` sentinel is only ever stored for an intra
18836/// neighbour (excluded by [`overlappable_above`]/[`overlappable_left`]'s
18837/// `is_inter` gate) or when `interp_fixed` is `Some` for the whole frame
18838/// (handled here first) -- so a sentinel reaching the kernel lookup means the
18839/// stream desynced upstream, and this refuses instead of panicking.
18840fn neighbour_filter(
18841 interp_fixed: Option<mc::InterpFilterKind>,
18842 sym: [u8; 2],
18843) -> Result<(mc::InterpFilterKind, mc::InterpFilterKind)> {
18844 if let Some(kind) = interp_fixed {
18845 return Ok((kind, kind));
18846 }
18847 // lane-golomb r9: this used to hand the sentinel straight to
18848 // `from_switchable_symbol`, which PANICS on any value above 2 -- a crash
18849 // on stream data (measured on a real 192x68 cq40 aomenc stream, where an
18850 // inter leaf below 8x8 desyncs upstream and leaves an unrecorded filter
18851 // behind). A decoder must refuse such a stream by name, never abort the
18852 // process; the desync that produces the sentinel belongs to lane-intersub8.
18853 if sym[0] > 2 || sym[1] > 2 {
18854 return Err(unsupported(
18855 "an OBMC neighbour whose switchable interp filter was never recorded",
18856 ));
18857 }
18858 Ok((
18859 mc::InterpFilterKind::from_switchable_symbol(sym[1] as usize),
18860 mc::InterpFilterKind::from_switchable_symbol(sym[0] as usize),
18861 ))
18862}
18863
18864/// lane-obmcrec r1 MEASUREMENT rung (`EC_OBMCREC=1`): every OBMC neighbour whose
18865/// recorded switchable-filter symbols are the `[3, 3]` "never recorded" sentinel
18866/// -- names the neighbour's own position/shape/reference so the decode path that
18867/// failed to record its filter can be identified. Read-only, off by default.
18868#[allow(clippy::too_many_arguments)]
18869fn obmcrec_probe(
18870 dir: &str,
18871 mi_row: usize,
18872 mi_col: usize,
18873 write_w: usize,
18874 write_h: usize,
18875 off4: usize,
18876 span4: usize,
18877 nb: &MiInfo,
18878 syms: [u8; 2],
18879 cell: Option<MiInfo>,
18880 fixed: bool,
18881) {
18882 if (syms[0] <= 2 && syms[1] <= 2) || std::env::var_os("EC_OBMCREC").is_none() {
18883 return;
18884 }
18885 eprintln!(
18886 "OBMCREC {dir} cur_mi=({mi_row},{mi_col}) cur_wh=({write_w}x{write_h}) off4={off4} \
18887span4={span4} syms={syms:?} fixed={fixed} nb_size=({}x{}) nb_ref={} nb_ref1={:?} nb_mv=({},{}) \
18888nb_newmv={} cell_size={:?} cell_inter={:?} cell_ref={:?} sb_row_off={} sb_col_off={}",
18889 nb.size * 4,
18890 nb.size_h * 4,
18891 nb.ref_frame,
18892 nb.ref_frame1,
18893 nb.mv.0,
18894 nb.mv.1,
18895 nb.is_new_mv,
18896 cell.map(|c| (c.size * 4, c.size_h * 4)),
18897 cell.map(|c| c.is_inter),
18898 cell.map(|c| c.ref_frame),
18899 mi_row % 32,
18900 mi_col % 32,
18901 );
18902}
18903
18904/// One neighbour's own re-prediction over a `w`x`h` region, MC'd fresh
18905/// against its own `mv`/reference/filter (libaom `av1_build_inter_predictor`
18906/// under `av1_setup_build_prediction_by_{above,left}_pred`).
18907#[allow(clippy::too_many_arguments)]
18908fn obmc_neighbour_pred(
18909 refplane: &PlaneBuf,
18910 x: usize,
18911 y: usize,
18912 mv: (i32, i32),
18913 w: usize,
18914 h: usize,
18915 luma: bool,
18916 h_kind: mc::InterpFilterKind,
18917 v_kind: mc::InterpFilterKind,
18918 // lane-scaledref r1: spec 7.11.3.3's x_scale_fp for THIS neighbour's own
18919 // reference (derived from luma widths, applied unchanged to chroma whose
18920 // x_q4 is already in its own plane's pixel units). `REF_NO_SCALE` takes
18921 // the ordinary stride-1 path bit-exact.
18922 x_scale_fp: i64,
18923) -> Vec<u16> {
18924 let mut out = vec![0u16; w * h];
18925 if x_scale_fp == mc::REF_NO_SCALE {
18926 mc::predict_with_filters(
18927 &refplane.data,
18928 refplane.width,
18929 refplane.true_width,
18930 refplane.true_height,
18931 mv_to_q4(x, mv.1, luma),
18932 mv_to_q4(y, mv.0, luma),
18933 w,
18934 h,
18935 h_kind,
18936 v_kind,
18937 &mut out,
18938 );
18939 } else {
18940 mc::predict_scaled(
18941 &refplane.data,
18942 refplane.width,
18943 refplane.true_width,
18944 refplane.true_height,
18945 mv_to_q4(x, mv.1, luma),
18946 mv_to_q4(y, mv.0, luma),
18947 x_scale_fp,
18948 w,
18949 h,
18950 h_kind,
18951 v_kind,
18952 &mut out,
18953 );
18954 }
18955 out
18956}
18957
18958/// Blends `tmp` into `dst` (stride `stride`) at `(ox, oy)`, mask varying by
18959/// row (the above-neighbour pass, `aom_blend_a64_vmask`).
18960/// `ii_weights1d` (reconinter.c:524): the interintra smooth-mask falloff.
18961const II_WEIGHTS_1D: [u8; 128] = [
18962 60, 58, 56, 54, 52, 50, 48, 47, 45, 44, 42, 41, 39, 38, 37, 35, 34, 33, 32,
18963 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 22, 21, 20, 19, 19, 18, 18, 17, 16,
18964 16, 15, 15, 14, 14, 13, 13, 12, 12, 12, 11, 11, 10, 10, 10, 9, 9, 9, 8,
18965 8, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4,
18966 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2,
18967 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1,
18968 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
18969];
18970
18971/// lane-interintra r1: non-wedge interintra prediction for one plane
18972/// (reconinter.c `av1_build_interintra_predictor` + `combine_interintra` +
18973/// `build_smooth_interintra_mask`). Builds the intra predictor for the
18974/// block's II mode (DC/V/H/SMOOTH, angle 0, no filter-intra) from `plane`'s
18975/// own decoded edges at `(x, y)`, then blends it over the inter prediction
18976/// in `pred`: `comp = (mask*intra + (64-mask)*inter + 32) >> 6`
18977/// (`aom_blend_a64_mask`, intra as src0). `ii_size_scales[plane_bsize]`
18978/// reduces to `128 / side` for the square plane sizes this decoder reaches.
18979/// lane-wii r2: `wedge == Some(..)` replaces the mode mask with the wedge
18980/// codebook mask (fixed sign 0; luma stride, 2x2 box-averaged for chroma).
18981fn interintra_blend(
18982 plane: &PlaneBuf,
18983 x: usize,
18984 y: usize,
18985 bw: usize,
18986 bh: usize,
18987 stride: usize,
18988 ii_mode: u8,
18989 wedge: Option<(&'static [u8], usize)>,
18990 pred: &mut [u16],
18991) {
18992 // `interintra_to_intra_mode`: II_DC/II_V/II_H/II_SMOOTH.
18993 let intra_mode = match ii_mode {
18994 0 => crate::intra::DC_PRED,
18995 1 => crate::intra::V_PRED,
18996 2 => crate::intra::H_PRED,
18997 _ => crate::intra::SMOOTH_PRED,
18998 };
18999 let (above, left, corner) = plane.edges_rect(
19000 x,
19001 y,
19002 bw,
19003 bh,
19004 crate::encode::Reach {
19005 above_right: false,
19006 below_left: false,
19007 },
19008 );
19009 let mut intra = vec![0u16; bw * bh];
19010 // Edge filtering never applies here: V/H at delta 0 are plain edge
19011 // copies (angle 90/180 skip the directional walk), DC/SMOOTH carry no
19012 // angle at all.
19013 predict(
19014 intra_mode,
19015 0,
19016 above.as_deref(),
19017 left.as_deref(),
19018 corner,
19019 bw,
19020 bh,
19021 false,
19022 false,
19023 &mut intra,
19024 );
19025 // `ii_size_scales[bsize]` is keyed on the block's LONGER side
19026 // (`MAX_SB_SIZE >> max(bw,bh)` order), not on the square this decoder
19027 // builds the predictor buffer at.
19028 let scale = 128 / bw.max(bh);
19029 for i in 0..bh {
19030 for j in 0..bw {
19031 let m = u32::from(match wedge {
19032 // lane-wii r2: wedge-interintra mask (aom_blend_a64_mask
19033 // over the wedge codebook, intra as src0, fixed sign 0).
19034 // Luma plane: mask rows are luma-resolution, ms == side.
19035 // 4:2:0 chroma: 2x2 box average (reconinter.c sub8x8 --
19036 // subw == subh == 1).
19037 Some((mask, ms)) if ms == stride => mask[i * stride + j],
19038 Some((mask, ms)) => {
19039 let t = 2 * i * ms + 2 * j;
19040 ((u32::from(mask[t])
19041 + u32::from(mask[t + 1])
19042 + u32::from(mask[t + ms])
19043 + u32::from(mask[t + ms + 1])
19044 + 2)
19045 >> 2) as u8
19046 }
19047 None => match ii_mode {
19048 0 => 32,
19049 1 => II_WEIGHTS_1D[i * scale],
19050 2 => II_WEIGHTS_1D[j * scale],
19051 _ => II_WEIGHTS_1D[i.min(j) * scale],
19052 },
19053 });
19054 let idx = i * stride + j;
19055 pred[idx] = ((m * u32::from(intra[i * bw + j]) + (64 - m) * u32::from(pred[idx]) + 32)
19056 >> 6) as u16;
19057 }
19058 }
19059}
19060
19061fn obmc_blend_v(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u16]) {
19062 let mask = obmc_mask(h);
19063 for row in 0..h {
19064 let m = u32::from(mask[row]);
19065 for col in 0..w {
19066 let d = &mut dst[(oy + row) * stride + ox + col];
19067 let t = u32::from(tmp[row * w + col]);
19068 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
19069 }
19070 }
19071}
19072
19073/// Blends `tmp` into `dst` at `(ox, oy)`, mask varying by column (the
19074/// left-neighbour pass, `aom_blend_a64_hmask`).
19075fn obmc_blend_h(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u16]) {
19076 let mask = obmc_mask(w);
19077 for row in 0..h {
19078 for col in 0..w {
19079 let m = u32::from(mask[col]);
19080 let d = &mut dst[(oy + row) * stride + ox + col];
19081 let t = u32::from(tmp[row * w + col]);
19082 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
19083 }
19084 }
19085}
19086
19087/// libaom's own `BLOCK_SIZE` enum index for a `w4`x`h4` (mi-unit) block --
19088/// only for the `EC_OBMC` trace rung below, so it reads byte-identical to
19089/// the instrumented aomdec's `backup_mbmi.bsize`.
19090fn ec_obmc_bsize(w4: usize, h4: usize) -> i32 {
19091 match (w4, h4) {
19092 (1, 1) => 0,
19093 (1, 2) => 1,
19094 (2, 1) => 2,
19095 (2, 2) => 3,
19096 (2, 4) => 4,
19097 (4, 2) => 5,
19098 (4, 4) => 6,
19099 (4, 8) => 7,
19100 (8, 4) => 8,
19101 (8, 8) => 9,
19102 (8, 16) => 10,
19103 (16, 8) => 11,
19104 (16, 16) => 12,
19105 (1, 4) => 16,
19106 (4, 1) => 17,
19107 (2, 8) => 18,
19108 (8, 2) => 19,
19109 (4, 16) => 20,
19110 (16, 4) => 21,
19111 _ => -1,
19112 }
19113}
19114
19115/// The `EC_OBMC` rung: one line per blended neighbour, in the instrumented
19116/// aomdec's own byte format (`decodeframe.c`
19117/// `dec_build_prediction_by_{above,left}_pred`), so the two decoders' OBMC
19118/// neighbour lists diff line for line. `filt` is libaom's packed
19119/// `interp_filters.as_int` = `y_filter | (x_filter << 16)`.
19120#[allow(clippy::too_many_arguments)]
19121fn ec_obmc_trace(
19122 dir: &str,
19123 mi_row: usize,
19124 mi_col: usize,
19125 write_w: usize,
19126 write_h: usize,
19127 rel: usize,
19128 op: usize,
19129 nb: &MiInfo,
19130 h_kind: mc::InterpFilterKind,
19131 v_kind: mc::InterpFilterKind,
19132) {
19133 if std::env::var_os("EC_OBMC").is_none() {
19134 return;
19135 }
19136 let sym = |k: mc::InterpFilterKind| match k {
19137 mc::InterpFilterKind::Smooth => 1u32,
19138 mc::InterpFilterKind::Sharp => 2,
19139 _ => 0,
19140 };
19141 eprintln!(
19142 "EC_OBMC {dir} mi=({mi_row},{mi_col}) wh=({write_w}x{write_h}) rel={rel} op={op} \
19143nbmv=({},{}) nbref={} nbbsize={} filt={}",
19144 nb.mv.0,
19145 nb.mv.1,
19146 nb.ref_frame,
19147 ec_obmc_bsize(nb.size, nb.size_h),
19148 sym(v_kind) | (sym(h_kind) << 16),
19149 );
19150}
19151
19152/// `av1_build_obmc_inter_prediction` (libaom `reconinter.c`): re-predicts
19153/// the overlap strip against each bordering above/left inter neighbour's own
19154/// mv/ref/filter and blends it into this block's just-built single-reference
19155/// prediction, luma then both 4:2:0 chroma planes -- above pass first, then
19156/// left, each reading only the *original* prediction this function was
19157/// handed (never the other pass's own output), matching libaom's own
19158/// independence between the two. `max_neighbor_obmc`'s own cap table
19159/// (`{0,1,2,3,4,4}` indexed by `mi_size_wide_log2`/`_high_log2`, this
19160/// decoder's own square blocks always index the same value both ways) bounds
19161/// how many bordering blocks actually get blended, separate from the
19162/// eligibility scan's own unbounded ("any at all") walk.
19163#[allow(clippy::too_many_arguments)]
19164fn obmc_blend(
19165 grid: &MiGrid,
19166 neighbours: &Neighbours,
19167 mi_row: usize,
19168 mi_col: usize,
19169 bw4: usize,
19170 bh4: usize,
19171 mi_rows: usize,
19172 mi_cols: usize,
19173 side: usize,
19174 write_w: usize,
19175 write_h: usize,
19176 chroma_side: usize,
19177 px: usize,
19178 py: usize,
19179 cpx: usize,
19180 cpy: usize,
19181 ref_y: &PlaneBuf,
19182 ref_u: &PlaneBuf,
19183 ref_v: &PlaneBuf,
19184 other_refs: &RefSlots,
19185 interp_fixed: Option<mc::InterpFilterKind>,
19186 // lane-scaledref r1: this frame's own coded luma width -- each OBMC
19187 // neighbour is re-predicted against ITS OWN reference, which may be
19188 // scaled differently from this block's (spec 7.11.3.3 / libaom
19189 // `av1_setup_build_prediction_by_above_pred` passing that ref's own
19190 // `scale_factors`).
19191 frame_width: usize,
19192 pred_y: &mut [u16],
19193 pred_u: &mut [u16],
19194 pred_v: &mut [u16],
19195) -> Result<()> {
19196 // lane-rect r2 (libaom av1_build_obmc_inter_prediction): each pass has
19197 // its OWN neighbour cap (width-log2 for above, height-log2 for left) and
19198 // overlap (bh/2 rows above, bw/2 cols left) -- one square `side` was
19199 // right only for square blocks.
19200 // libaom `max_neighbor_obmc[6] = { 0, 1, 2, 3, 4, 4 }` indexed by
19201 // `mi_size_wide_log2[bsize]` (above pass) / `mi_size_high_log2` (left):
19202 // 1 mi -> 0, 2 -> 1, 4 -> 2, 8 -> 3, 16+ -> 4. lane-inter4 r3: the old
19203 // `1..=4 => 2` row was right only for blocks at least 16 px on that axis
19204 // -- a 16x8 leaf's LEFT pass (bh4 = 2) walked up to two neighbours where
19205 // libaom walks one, blending an extra 8-px-tall neighbour into every
19206 // rect leaf with two of them on its left edge (class table-narrowed-to-
19207 // the-reachable-sizes; the square gates could never expose it).
19208 let max_nb = |n4: usize| match n4 {
19209 0..=1 => 0,
19210 2 => 1,
19211 3..=4 => 2,
19212 5..=8 => 3,
19213 _ => 4,
19214 };
19215 // lane-inter4 r4: r3 refused OBMC on a 16x8/8x16 leaf (5302 luma pixels
19216 // of one frame wrong). Re-measured on this tree with an `EC_OBMC` rung in
19217 // both decoders on that exact stream: the neighbour lists agree entry for
19218 // entry (position, span, mv, ref, size, filter) and all six pre-filter
19219 // frames are byte-identical to the instrumented aomdec's. The refusal is
19220 // gone; the counter below is what the gate's `--enable-obmc=1` arm reads.
19221 // The only decode-path change between r3's measurement and this one is the
19222 // lane-interbis merge (`build_motion_field`'s compound slot walk), which
19223 // moves temporal MV candidates -- not bisected further.
19224 if matches!((write_w, write_h), (16, 8) | (8, 16)) {
19225 OBMC_RECT_LEAF_HITS.with(|c| c.set(c.get() + 1));
19226 }
19227 // lane-sb128c r1: libaom caps the overlap strip at a 64x64 block's own
19228 // half (`reconinter.c` 860/899: `AOMMIN(block_size_high[bsize],
19229 // block_size_high[BLOCK_64X64]) >> 1`, and the `block_size_wide` mirror) --
19230 // inert below 128, where a 128x128 block would otherwise blend a 64-row
19231 // strip `obmc_mask` has no table for.
19232 let overlap_above = write_h.min(64) / 2;
19233 let overlap_left = write_w.min(64) / 2;
19234 // lane-inter8 r1 / lane-scaledref r1: `av1_skip_u4x4_pred_in_obmc`
19235 // (`reconinter.c` 820, `DISABLE_CHROMA_U8X8_OBMC == 0` -- "one-sided
19236 // obmc") returns `dir == 0` when the chroma plane's own block is
19237 // BLOCK_4X4/8X4/4X8 (an 8x8, 16x8 or 8x16 luma block at 4:2:0): the
19238 // ABOVE pass skips chroma entirely, the LEFT pass still blends it.
19239 let skip_chroma_above = matches!((write_w, write_h), (8, 8) | (16, 8) | (8, 16));
19240
19241 for (off4, span4, nb, src4) in overlappable_above(grid, mi_row, mi_col, bw4, mi_cols, max_nb(bw4))
19242 {
19243 // `Neighbours::above_filter` is indexed in `SUB`(16px)-wide columns
19244 // (this decoder's own outer block-loop granularity), one step
19245 // coarser than the mi(4px) units `overlappable_above` walks in --
19246 // divide back down to that column.
19247 // lane-gmaffine r2: the neighbour's OWN mi-granular filter
19248 // (libaom `av1_setup_build_prediction_by_above_pred` reads
19249 // `above_mbmi->interp_filters`); the 16px-granular `Neighbours` slot
19250 // stays as the fallback for paths that do not record one yet
19251 // (compound), which is what every earlier round used.
19252 let above_syms = neighbours.above_filter[mi_col + src4];
19253 obmcrec_probe(
19254 "above", mi_row, mi_col, write_w, write_h, off4, span4, &nb, above_syms,
19255 grid.get(mi_row - 1, mi_col + src4).copied(), interp_fixed.is_some(),
19256 );
19257 let (h_kind, v_kind) = neighbour_filter(interp_fixed, above_syms)?;
19258 ec_obmc_trace("above", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind);
19259 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
19260 let nb_scale = mc::scale_factor(ny.width, frame_width);
19261 let (bw, bh, ox) = (span4 * 4, overlap_above, off4 * 4);
19262 let tmp_y = obmc_neighbour_pred(ny, px + ox, py, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale);
19263 obmc_blend_v(pred_y, side, ox, 0, bw, bh, &tmp_y);
19264 if !skip_chroma_above {
19265 let (cbw, cbh, cox) = (bw / 2, overlap_above / 2, ox / 2);
19266 let tmp_u = obmc_neighbour_pred(nu, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
19267 obmc_blend_v(pred_u, chroma_side, cox, 0, cbw, cbh, &tmp_u);
19268 let tmp_v = obmc_neighbour_pred(nv, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
19269 obmc_blend_v(pred_v, chroma_side, cox, 0, cbw, cbh, &tmp_v);
19270 }
19271 }
19272
19273 for (off4, span4, nb, src4) in overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, max_nb(bh4))
19274 {
19275 let left_syms = neighbours.left_filter[mi_row + src4];
19276 obmcrec_probe(
19277 "left", mi_row, mi_col, write_w, write_h, off4, span4, &nb, left_syms,
19278 grid.get(mi_row + src4, mi_col - 1).copied(), interp_fixed.is_some(),
19279 );
19280 let (h_kind, v_kind) = neighbour_filter(interp_fixed, left_syms)?;
19281 ec_obmc_trace("left", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind);
19282 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
19283 let nb_scale = mc::scale_factor(ny.width, frame_width);
19284 let (bw, bh, oy) = (overlap_left, span4 * 4, off4 * 4);
19285 let tmp_y = obmc_neighbour_pred(ny, px, py + oy, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale);
19286 obmc_blend_h(pred_y, side, 0, oy, bw, bh, &tmp_y);
19287 let (cbw, cbh, coy) = (overlap_left / 2, bh / 2, oy / 2);
19288 let tmp_u = obmc_neighbour_pred(nu, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
19289 obmc_blend_h(pred_u, chroma_side, 0, coy, cbw, cbh, &tmp_u);
19290 let tmp_v = obmc_neighbour_pred(nv, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale);
19291 obmc_blend_h(pred_v, chroma_side, 0, coy, cbw, cbh, &tmp_v);
19292 }
19293 Ok(())
19294}
19295
19296/// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to
19297/// the square block sizes this decoder ever decodes (32/16/8, all
19298/// `min(w,h) >= 8`, `is_comp_ref_allowed` true): `COMPOUND_DIFFWTD` is then
19299/// always `is_interinter_compound_used`, so the function is always `true`
19300/// for `side` -- kept as a named call (rather than inlined `true`) so a
19301/// future sub-8 block size does not silently misdecode a real stream.
19302fn is_any_masked_compound_used_here(bw: usize, bh: usize) -> bool {
19303 // lane-inter16ab r4 (class sweep of the r3 CDF-row defect):
19304 // `is_comp_ref_allowed(bsize)` is `AOMMIN(block_size_wide, block_size_high)
19305 // >= 8` on the block's TRUE footprint -- a 16x4/4x16 strip is NOT allowed,
19306 // so libaom writes no `comp_group_idx` symbol there at all. Keyed off the
19307 // square `side` we read one the reference never wrote.
19308 bw.min(bh) >= 8
19309}
19310
19311/// The `BLOCK_SIZES_ALL` index of a `bw x bh` block (libaom `enum BLOCK_SIZE`,
19312/// `blockd.h`) -- the row every size-indexed inter CDF table
19313/// (`compound_type_cdf`, `wedge_idx_cdf`) is keyed by. Our `decode_inter_block`
19314/// carries the enclosing SQUARE `side` for context purposes (the accepted
19315/// strip corner-cut), so a 16x8 / 8x16 PARTITION_HORZ/VERT strip that reads
19316/// one of those symbols off `side` alone takes BLOCK_16X16's row and desyncs
19317/// (lane-inter16ab r3: a real 16x8 compound strip with `comp_group_idx == 1`,
19318/// decode-order frame 5, our range 64901 vs the oracle's 47271 at the very
19319/// next block's mode read).
19320fn bsize_all_index(bw: usize, bh: usize) -> Option<usize> {
19321 Some(match (bw, bh) {
19322 (4, 4) => 0,
19323 (4, 8) => 1,
19324 (8, 4) => 2,
19325 (8, 8) => 3,
19326 (8, 16) => 4,
19327 (16, 8) => 5,
19328 (16, 16) => 6,
19329 (16, 32) => 7,
19330 (32, 16) => 8,
19331 (32, 32) => 9,
19332 (32, 64) => 10,
19333 (64, 32) => 11,
19334 (64, 64) => 12,
19335 (64, 128) => 13,
19336 (128, 64) => 14,
19337 (128, 128) => 15,
19338 (4, 16) => 16,
19339 (16, 4) => 17,
19340 (8, 32) => 18,
19341 (32, 8) => 19,
19342 (16, 64) => 20,
19343 (64, 16) => 21,
19344 _ => return None,
19345 })
19346}
19347
19348/// `av1_wedge_params_lookup[bsize].wedge_types > 0` (libaom `reconinter.c`):
19349/// the block sizes that carry a wedge codebook at all. A `compound_type`
19350/// symbol is written only for these; every other size infers
19351/// `COMPOUND_DIFFWTD`.
19352fn wedge_used_bsize(bw: usize, bh: usize) -> bool {
19353 matches!(
19354 (bw, bh),
19355 (8, 8) | (8, 16) | (16, 8) | (16, 16) | (16, 32) | (32, 16) | (32, 32) | (8, 32) | (32, 8)
19356 )
19357}
19358
19359
19360
19361
19362/// Whether a compound reference pair is unidirectional (both references on
19363/// the same temporal side of the current frame) -- `has_uni_comp_refs`
19364/// (libaom `av1_reference_frame_utils.h`/`pred_common.c`'s own definition:
19365/// a pair is `UNIDIR_COMP_REFERENCE` exactly when neither reference is
19366/// backward-while-the-other-is-forward, i.e. `is_backward(ref0) ==
19367/// is_backward(ref1)`). Used to build a real
19368/// [`crate::mvstack::NeighbourRef::uni`] once `ref1` is known, matching
19369/// [`crate::mvstack::comp_reference_type_ctx`]'s own `is_backward` calls.
19370fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool {
19371 let backward = |r: i8| (BWDREF_FRAME..=ALTREF_FRAME).contains(&r);
19372 backward(ref0) == backward(ref1)
19373}
19374
19375/// `get_comp_group_idx_context` (libaom `pred_common.h`): sums the
19376/// above/left neighbour contributions [`Neighbours::record_inter`]/
19377/// [`Neighbours::record_compound_ctx`] already precomputed, clamped to 5.
19378/// lane-inter8 r2: `at_mi` is the block's own top-left in 4x4 mi units --
19379/// an 8x8 leaf used to pass its enclosing 16x16's corner here, so all four
19380/// leaves read the same neighbour cell (class context-read-from-one-cell).
19381fn get_comp_group_idx_context(
19382 neighbours: &Neighbours,
19383 at_mi: (usize, usize),
19384 side: usize,
19385) -> usize {
19386 let _ = side;
19387 let (rmi, cmi) = at_mi;
19388 (neighbours.above_comp_group_idx[cmi] as usize + neighbours.left_comp_group_idx[rmi] as usize)
19389 .min(5)
19390}
19391
19392/// `get_comp_index_context` (libaom `pred_common.h`): the above/left
19393/// neighbour bits plus `3 * (fwd == bck)`, where `fwd`/`bck` are this
19394/// block's own two references' distances from the current frame (spec
19395/// 7.11.3.15's `get_relative_dist`, same convention
19396/// [`crate::compound::dist_wtd_comp_weight_assign`] uses).
19397#[allow(clippy::too_many_arguments)]
19398fn get_comp_index_context(
19399 neighbours: &Neighbours,
19400 at_mi: (usize, usize),
19401 side: usize,
19402 order_hint_bits: u32,
19403 cur_order_hint: u32,
19404 ref0_order_hint: u32,
19405 ref1_order_hint: u32,
19406) -> usize {
19407 let _ = side;
19408 let (rmi, cmi) = at_mi;
19409 let fwd =
19410 crate::motion_field::get_relative_dist(order_hint_bits, ref1_order_hint, cur_order_hint)
19411 .abs();
19412 let bck =
19413 crate::motion_field::get_relative_dist(order_hint_bits, cur_order_hint, ref0_order_hint)
19414 .abs();
19415 let offset = usize::from(fwd == bck);
19416 neighbours.above_compound_idx[cmi] as usize
19417 + neighbours.left_compound_idx[rmi] as usize
19418 + 3 * offset
19419}
19420
19421fn read_comp_mode(
19422 dec: &mut SymbolDecoder,
19423 cdfs: &mut Cdfs,
19424 above: Option<NeighbourRef>,
19425 left: Option<NeighbourRef>,
19426) -> bool {
19427 let ctx = reference_mode_ctx(above, left);
19428 let compound = dec.symbol(&mut cdfs.comp_mode[ctx]) == 1;
19429 if compound {
19430 COMP_MODE_HITS.with(|c| c.set(c.get() + 1));
19431 }
19432 compound
19433}
19434
19435/// Spec 5.11.25's `comp_reference_type` + the `uni_comp_ref`/`comp_ref`/
19436/// `comp_bwdref` trees (libaom `decodemv.c`'s `read_ref_frames` compound
19437/// arm), reached once [`read_comp_mode`] has already returned
19438/// `COMPOUND_REFERENCE`. Returns `(RefFrame[0], RefFrame[1])`.
19439/// `above`/`left` are [`comp_reference_type_ctx`]'s own `NeighbourRef`
19440/// convention; `above_ref`/`left_ref` are the scalar `1..=7`/`-1`
19441/// convention [`read_single_ref`] already uses, for every downstream binary
19442/// decision. libaom `pred_common.c`'s own compound context functions
19443/// (`av1_get_pred_context_uni_comp_ref_p[1|2]`, `comp_ref_p[1|2]`,
19444/// `comp_bwdref_p[1]`) turned out to be exactly [`single_ref_p1_ctx`]..
19445/// [`single_ref_p6_ctx`]/[`uni_comp_ref_p1_ctx`] under a different name
19446/// (same vote-the-neighbours-above-left shape, same forward/backward and
19447/// LAST/LAST2/LAST3/GOLDEN groupings) -- lane-av1comp audited each one
19448/// against the C source rather than porting six near-duplicate functions.
19449/// Its caller today only needs the symbols consumed, correctly, to keep the
19450/// arithmetic decoder's own state in sync before refusing the block by name
19451/// -- the returned pair is not yet threaded into any motion-compensation
19452/// path.
19453fn read_compound_ref_frames(
19454 dec: &mut SymbolDecoder,
19455 cdfs: &mut Cdfs,
19456 above: Option<NeighbourRef>,
19457 left: Option<NeighbourRef>,
19458 above_ref: i8,
19459 left_ref: i8,
19460) -> (i8, i8) {
19461 let a = (above_ref > 0).then_some(above_ref);
19462 let l = (left_ref > 0).then_some(left_ref);
19463 // libaom `av1_collect_neighbors_ref_counts` counts BOTH of a compound
19464 // neighbour's references, not just its first -- `a1`/`l1` carry that
19465 // second reference through to every vote below (lane-av1blend r6: a
19466 // missing `a1`/`l1` here was decoding `compound_idx` off the wrong CDF
19467 // row for a block sitting under a skip_mode-forced compound neighbour).
19468 let a1 = above.and_then(|n| n.ref1);
19469 let l1 = left.and_then(|n| n.ref1);
19470 let type_ctx = comp_reference_type_ctx(above, left);
19471 let unidir = dec.symbol(&mut cdfs.comp_ref_type[type_ctx]) == 0;
19472 if unidir {
19473 UNI_COMP_HITS.with(|c| c.set(c.get() + 1));
19474 // uni_comp_ref (p0): forward vs. backward -- av1_get_pred_context_-
19475 // uni_comp_ref_p is single_ref_p1's own forward/backward vote.
19476 let bit = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0]);
19477 if bit == 1 {
19478 (BWDREF_FRAME, ALTREF_FRAME)
19479 } else {
19480 let p1 = dec.symbol(&mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1]);
19481 if p1 == 1 {
19482 // uni_comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
19483 let p2 = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
19484 if p2 == 1 {
19485 (LAST_FRAME, GOLDEN_FRAME)
19486 } else {
19487 (LAST_FRAME, LAST3_FRAME)
19488 }
19489 } else {
19490 (LAST_FRAME, LAST2_FRAME)
19491 }
19492 }
19493 } else {
19494 // comp_ref (p0): LAST/LAST2 vs. LAST3/GOLDEN, same vote as single_ref_p3.
19495 let bit0 = dec.symbol(&mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0]);
19496 let ref0 = if bit0 == 0 {
19497 // comp_ref_p1: LAST vs. LAST2, same vote as single_ref_p4.
19498 let p1 = dec.symbol(&mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1]);
19499 if p1 == 1 { LAST2_FRAME } else { LAST_FRAME }
19500 } else {
19501 // comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
19502 let p2 = dec.symbol(&mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
19503 if p2 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
19504 };
19505 // comp_bwdref (p0): BWDREF/ALTREF2 vs. ALTREF, same vote as single_ref_p2.
19506 let bit1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0]);
19507 let ref1 = if bit1 == 0 {
19508 // comp_bwdref_p1: BWDREF vs. ALTREF2, same vote as single_ref_p6.
19509 let p1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1]);
19510 if p1 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
19511 } else {
19512 ALTREF_FRAME
19513 };
19514 (ref0, ref1)
19515 }
19516}
19517
19518/// Spec 5.11.24's `compound_mode` (lane-av1comp): which of the eight
19519/// `INTER_COMPOUND_MODES` (`NEAREST_NEARESTMV`..`NEW_NEWMV`, returned as
19520/// `0..=7`) a `COMPOUND_REFERENCE` block takes, reached once
19521/// [`read_comp_mode`] has already returned `COMPOUND_REFERENCE`. `ctx` is
19522/// libaom's `av1_mode_context_analyzer`'s compound branch --
19523/// `compound_mode_ctx_map[ref_mv_ctx >> 1][min(new_mv_ctx, COMP_NEWMV_CTXS
19524/// - 1)]` (`mvref_common.h`) -- folded from [`crate::mvstack::
19525/// find_mv_stack_compound`]'s own `new_mv_ctx`/`ref_mv_ctx`. The read symbol
19526/// is not yet turned into an assigned MV pair or motion-compensated --
19527/// lane-av1comp.
19528fn read_inter_compound_mode(
19529 dec: &mut SymbolDecoder,
19530 cdfs: &mut Cdfs,
19531 new_mv_ctx: usize,
19532 ref_mv_ctx: usize,
19533) -> u8 {
19534 let ctx = cdf::COMPOUND_MODE_CTX_MAP[ref_mv_ctx >> 1][new_mv_ctx.min(4)];
19535 COMPOUND_MODE_HITS.with(|c| c.set(c.get() + 1));
19536 dec.symbol(&mut cdfs.inter_compound_mode[ctx]) as u8
19537}
19538
19539/// spec 7.10.2.10 `assign_mv`'s compound branch, plus the compound half of
19540/// `read_drl_idx` (spec 5.11.24) it depends on -- `mode` is
19541/// [`read_inter_compound_mode`]'s own `0..=7` (`NEAREST_NEARESTMV`..
19542/// `NEW_NEWMV`, libaom `enums.h` order). Every `GLOBAL_GLOBALMV` side reads
19543/// as `(0, 0)` since [`crate::stream::decode_stream`] already refuses any
19544/// non-`IDENTITY` global motion model before a tile is ever decoded.
19545///
19546/// Ported straight from libaom `decodemv.c`'s `read_drl_idx` (the
19547/// `NEW_NEWMV`/`have_nearmv_in_inter_mode` branches) and `assign_mv`/its
19548/// caller's `ref_mv[]`/`nearmv[]` setup: the `NEAR_NEWMV`/`NEW_NEARMV`
19549/// `1 + ref_mv_idx` special case is folded into `new_idx` below, matching
19550/// `read_drl_idx`'s own comment about "offsetting the NEARESTMV mode".
19551fn assign_compound_mv(
19552 dec: &mut SymbolDecoder,
19553 cdfs: &mut Cdfs,
19554 comp_stack: &crate::mvstack::CompoundMvStack,
19555 mode: u8,
19556 allow_high_precision_mv: bool,
19557 force_integer_mv: bool,
19558 // lane-gm r2: `gm_get_motion_vector(ref0)`/`(ref1)` at this block's own
19559 // position, spec 7.10.2.10's `GLOBAL_GLOBALMV` assignment.
19560 global_mv: ((i32, i32), (i32, i32)),
19561) -> ((i32, i32), (i32, i32)) {
19562 const NEAREST_NEARESTMV: u8 = 0;
19563 const NEAR_NEARMV: u8 = 1;
19564 const NEAREST_NEWMV: u8 = 2;
19565 const NEW_NEARESTMV: u8 = 3;
19566 const NEAR_NEWMV: u8 = 4;
19567 const NEW_NEARMV: u8 = 5;
19568 const GLOBAL_GLOBALMV: u8 = 6;
19569 const NEW_NEWMV: u8 = 7;
19570
19571 let mut ref_mv_idx = 0usize;
19572 if mode == NEW_NEWMV {
19573 let mut idx = 0usize;
19574 while idx < 2 && comp_stack.entries.len() > idx + 1 {
19575 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
19576 break;
19577 }
19578 idx += 1;
19579 }
19580 ref_mv_idx = idx;
19581 } else if matches!(mode, NEAR_NEARMV | NEAR_NEWMV | NEW_NEARMV) {
19582 let mut idx = 1usize;
19583 while idx < 3 && comp_stack.entries.len() > idx + 1 {
19584 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
19585 break;
19586 }
19587 idx += 1;
19588 }
19589 ref_mv_idx = idx - 1;
19590 }
19591
19592 let near = comp_stack
19593 .entries
19594 .get(ref_mv_idx + 1)
19595 .map_or(comp_stack.near_mv, |e| (e.mv0, e.mv1));
19596 let new_idx = if matches!(mode, NEAR_NEWMV | NEW_NEARMV) {
19597 ref_mv_idx + 1
19598 } else {
19599 ref_mv_idx
19600 };
19601 let new_pred = comp_stack
19602 .entries
19603 .get(new_idx)
19604 .map_or(comp_stack.nearest_mv, |e| (e.mv0, e.mv1));
19605
19606 let read_new = |dec: &mut SymbolDecoder, cdfs: &mut Cdfs, base: (i32, i32)| {
19607 read_mv(
19608 dec,
19609 &mut cdfs.mv_comp,
19610 &mut cdfs.mv_joint,
19611 base,
19612 allow_high_precision_mv,
19613 force_integer_mv,
19614 )
19615 };
19616
19617 match mode {
19618 NEAREST_NEARESTMV => comp_stack.nearest_mv,
19619 NEAR_NEARMV => near,
19620 NEAREST_NEWMV => (comp_stack.nearest_mv.0, read_new(dec, cdfs, new_pred.1)),
19621 NEW_NEARESTMV => (read_new(dec, cdfs, new_pred.0), comp_stack.nearest_mv.1),
19622 NEAR_NEWMV => (near.0, read_new(dec, cdfs, new_pred.1)),
19623 NEW_NEARMV => (read_new(dec, cdfs, new_pred.0), near.1),
19624 GLOBAL_GLOBALMV => global_mv,
19625 _ => (
19626 read_new(dec, cdfs, new_pred.0),
19627 read_new(dec, cdfs, new_pred.1),
19628 ),
19629 }
19630}
19631
19632/// Derives this query block's own [`crate::mvstack::GmMvTable`] -- one
19633/// `gm_get_motion_vector` (spec 7.10.2.1) result per reference frame, at
19634/// THIS block's own `(mi_row, mi_col, bw4, bh4)` (mvstack.rs's own doc: the
19635/// table is always computed at the *querying* block's position, never a
19636/// donating neighbour's).
19637fn build_gm_mv_table(
19638 global_motion: &[ec_av1_syntax::WarpParams; 7],
19639 mi_row: usize,
19640 mi_col: usize,
19641 bw4: usize,
19642 bh4: usize,
19643 allow_high_precision_mv: bool,
19644 force_integer_mv: bool,
19645) -> crate::mvstack::GmMvTable {
19646 std::array::from_fn(|i| {
19647 let gm = &global_motion[i];
19648 crate::warp::gm_get_motion_vector(
19649 gm.model,
19650 &gm.params,
19651 mi_row,
19652 mi_col,
19653 bw4,
19654 bh4,
19655 allow_high_precision_mv,
19656 force_integer_mv,
19657 )
19658 })
19659}
19660
19661/// Decodes one square inter-frame block (32x32 whole or 16x16 leaf): skip,
19662/// `is_inter`, then either the single-reference/MV-stack/motion-vector chain
19663/// and motion-compensated reconstruction, or the inter frame's own intra
19664/// path (`Y_MODE` by size group, not `KF_Y_MODE` by neighbour), mirroring
19665/// [`crate::tile`]'s `sb_coeff_inter_frame_tile`'s whole-block branch and its
19666/// private `write_inter_frame_leaf` -- both share this one function here,
19667/// parameterised by `side`/the transform sets/scan tables/size group they
19668/// each use.
19669///
19670/// # Errors
19671/// Returns an error when a symbol names anything this decoder does not
19672/// reconstruct: a reference other than `LAST_FRAME`, `GLOBALMV` (round 3;
19673/// `NEARESTMV`/`NEARMV`/`NEWMV` are all reconstructed), or an intra
19674/// mode/tx-type outside what [`read_intra_mode`]/[`read_coeffs`] already
19675/// refuse.
19676#[allow(clippy::too_many_arguments)]
19677/// lane-inter4 r1: 16-px-cell coordinates -> MI (4-px) coordinates, the unit
19678/// [`decode_inter_block`]'s `at` now takes.
19679const fn sub16_to_mi(t: (usize, usize)) -> (usize, usize) {
19680 (t.0 * (SUB / MI), t.1 * (SUB / MI))
19681}
19682
19683fn decode_inter_block(
19684 dec: &mut SymbolDecoder,
19685 cdfs: &mut Cdfs,
19686 neighbours: &mut Neighbours,
19687 grid: &mut MiGrid,
19688 at: (usize, usize),
19689 side: usize,
19690 mi_cols: u32,
19691 mi_rows: u32,
19692 y: &mut PlaneBuf,
19693 u: &mut PlaneBuf,
19694 v: &mut PlaneBuf,
19695 ref_y: &PlaneBuf,
19696 ref_u: &PlaneBuf,
19697 ref_v: &PlaneBuf,
19698 // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own
19699 // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]`
19700 // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME`
19701 // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the
19702 // slot's still empty (an error-resilient stream, or too early in the
19703 // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below.
19704 other_refs: &RefSlots,
19705 sign_bias_table: &SignBiasTable,
19706 // lane-gm r2: this frame header's own `global_motion` table (spec
19707 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` same as `sign_bias_table`
19708 // -- feeds `warp::gm_get_motion_vector` for `GLOBALMV`/`GLOBAL_GLOBALMV`
19709 // assignment and the mv-stack's neighbour substitution.
19710 global_motion: &[ec_av1_syntax::WarpParams; 7],
19711 base_q_idx: u8,
19712 luma_set_intra: TxbSet,
19713 luma_set_inter: TxbSet,
19714 chroma_set: TxbSet,
19715 luma_tx: usize,
19716 chroma_tx: usize,
19717 scan_luma: &[u16],
19718 scan_chroma: &[u16],
19719 // lane-inter4 r3: superseded by `size_group_wh(write_w, write_h)` at the
19720 // one site that read it (`y_mode`) -- a rect strip's group comes from its
19721 // true footprint, not the caller's square `side`. Kept in the signature
19722 // rather than editing twenty call sites.
19723 _size_group: usize,
19724 allow_high_precision_mv: bool,
19725 force_integer_mv: bool,
19726 interp_fixed: Option<mc::InterpFilterKind>,
19727 enable_dual_filter: bool,
19728 tpl_frame: Option<&TplFrameArgs>,
19729 // lane-av1comp: this frame header's own `reference_select` bit -- `false`
19730 // means every block is `SINGLE_REFERENCE` by construction and `comp_mode`
19731 // is never read (spec 5.11.25); `true` reads `comp_mode` per block and
19732 // refuses (rather than silently misdecoding) the ones that pick
19733 // `COMPOUND_REFERENCE`, since two-reference motion compensation is not
19734 // wired yet.
19735 reference_select: bool,
19736 // lane-av1comp: `seq_params`' own masked-compound/distance-weighted-
19737 // compound enable bits, gating `comp_group_idx`/`compound_idx`
19738 // (spec 5.11.25) -- always present (unlike `tpl_frame`), since the
19739 // compound blend weights need this frame's own order hint regardless
19740 // of `use_ref_frame_mvs`.
19741 enable_masked_compound: bool,
19742 // lane-sb128 r4: this sequence header's own `enable_interintra_compound`
19743 // bit (spec 5.11.24's `interintra` read, libaom `decodemv.c`
19744 // read_inter_block_mode_info ~1490-1510) -- read right after `assign_mv`
19745 // and before `read_motion_mode` on the single-ref path below, gated by
19746 // `is_interintra_allowed` (single-ref, `BLOCK_8X8..=BLOCK_32X32`, and
19747 // every mode this single-ref branch can produce is already in
19748 // `SINGLE_INTER_MODE_START..END`); `interintra == 1` is a named refusal
19749 // (inter+intra blended prediction unimplemented) rather than a
19750 // mis-decode.
19751 enable_interintra_compound: bool,
19752 enable_jnt_comp: bool,
19753 order_hint_bits: u32,
19754 order_hint: u32,
19755 ref_order_hints: [u32; 7],
19756 // lane-av1comp round 14: this frame header's own `skip_mode_present` bit
19757 // and `skip_mode_frame` reference pair (spec 5.9.22, `frame.rs`'s
19758 // `read_skip_mode_params`, already 1-based `MV_REFERENCE_FRAME`) --
19759 // `skip_mode` (spec 5.11.23 `read_skip_mode`) is read *before* `skip`
19760 // when this is `true` (every block this decoder reaches is >= 8x8, so
19761 // `is_comp_ref_allowed` never gates it further); a `true` result forces
19762 // `skip_txfm`, `is_inter`, `NEAREST_NEARESTMV` of this pair with no mode/
19763 // DRL symbol read, and a plain average blend with no `comp_group_idx`/
19764 // `compound_idx` read (libaom `decodemv.c` 1604-1619, 1382-1384, 1509).
19765 skip_mode_present: bool,
19766 skip_mode_frame: [u8; 2],
19767 // lane-motionmode round 1: this frame header's own `is_motion_mode_switchable`/
19768 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`).
19769 switchable_motion_mode: bool,
19770 allow_warped_motion: bool,
19771 // lane-warp r5: set by the HORZ_B arm -- the 32x16 top strip is decoded
19772 // as a square 32x32 block, which over-reads a residual unless coded
19773 // `skip`; a non-skip strip must refuse cleanly instead of desyncing.
19774 reject_residual: bool,
19775 // lane-partitions r1: the strip's own true width/height in pixels --
19776 // `side` keeps governing every syntax/CDF/prediction-buffer decision
19777 // (matching `HORZ_B`'s already-accepted square-context corner-cut), but
19778 // the final pixel write and this block's own neighbour-context stamp
19779 // (`record*`/`fill_*_grid`) use `write_w`/`write_h` instead, so a
19780 // PARTITION_HORZ/VERT strip only claims its own true footprint. `side`
19781 // for every existing (square) caller.
19782 write_w: usize,
19783 write_h: usize,
19784 // lane-screen r2: this frame header's own `allow_screen_content_tools`
19785 // bit, threaded to the intra-sub-block branch below -- libaom's
19786 // `read_intra_block_mode_info` (decodemv.c:1065-1107, the inter-frame
19787 // counterpart of `read_intra_frame_mode_info`) reads `y_mode_cdf`
19788 // (never `kf_y_mode_cdf`) and has NO `use_intrabc` call at all (that
19789 // symbol is intra-frame-only, spec `av1_read_mode_info` dispatches on
19790 // `frame_is_intra_only`), but it still calls `read_palette_mode_info`
19791 // under the same `av1_allow_palette` gate as the key-frame path.
19792 allow_screen_content_tools: bool,
19793 // lane-superres r9: this frame's own coded luma width (spec 7.11.3.3) --
19794 // compared against each reference's stored picture width to decide
19795 // whether a scaled-MC path (`mc::predict_scaled`) or the ordinary
19796 // stride-1 one (`mc::predict_with_filters`) applies per reference, and to
19797 // refuse (rather than mis-decode) the warp/OBMC/interintra/compound
19798 // combinations that don't implement scaled MC yet.
19799 frame_width: usize,
19800) -> Result<()> {
19801 // lane-inter4 r1: `at` is in MI units (4 px) so a 32-level 1:4 strip can
19802 // name an 8-px offset; `(r, c)` stays the enclosing 16-px cell for the
19803 // few 16-px-granular uses below.
19804 let (r, c) = (at.0 / (SUB / MI), at.1 / (SUB / MI));
19805 // lane-inter8 r2: the inter side bands are mi-granular; this block's own
19806 // above/left neighbour is the mi cell at its top-left corner (libaom
19807 // `above_mbmi` = mi(mi_row - 1, mi_col)), so a SUB-aligned block reads
19808 // exactly what it read before.
19809 let (rmi, cmi) = at;
19810 let (px, py) = (at.1 * MI, at.0 * MI);
19811 // lane-inter16ab r2: a 16x4 / 4x16 inter strip's chroma is the PAIR's
19812 // (8x4 / 4x8 at the even strip's origin) and is coded only by the odd
19813 // strip (`is_chroma_reference`); every other block keeps its own.
19814 let strip_chroma = INTER_STRIP_CHROMA.with(std::cell::Cell::take);
19815 INTER_LAST_MC.with(|c| c.set(None));
19816 let has_chroma = strip_chroma.is_none_or(|s| s.has_chroma);
19817 let (cpx, cpy) = match strip_chroma {
19818 Some(s) if s.has_chroma => (s.pair_mi.1 * MI / 2, s.pair_mi.0 * MI / 2),
19819 _ => (px / 2, py / 2),
19820 };
19821 let chroma_side = side / 2;
19822 let (write_chroma_w, write_chroma_h) = match strip_chroma {
19823 Some(s) if s.has_chroma => {
19824 if s.horz {
19825 (8, 4)
19826 } else {
19827 (4, 8)
19828 }
19829 }
19830 _ => (write_w / 2, write_h / 2),
19831 };
19832 // lane-midcut r3: `av1_init_warp_params` (libaom reconinter.c) bails per
19833 // PLANE at `block_width < 8 || block_height < 8` -- on the block's own
19834 // dims, not on the square prediction buffer this reader allocates. The
19835 // `chroma_side >= 8` tests below read that buffer's side, so a RECT block
19836 // whose chroma is 8x4 / 4x8 (a 16x8 / 8x16 luma block) warped its chroma
19837 // where libaom keeps the translational prediction (class
19838 // narrow-block-sharp-kernel / rectchroma2: dims read off the square
19839 // buffer). Same for a 4-wide/4-tall luma block under a global warp.
19840 let warp_luma_ok = write_w >= 8 && write_h >= 8;
19841 let warp_chroma_ok = write_chroma_w >= 8 && write_chroma_h >= 8;
19842 if std::env::var_os("EC_MC_TRACE").is_some() {
19843 eprintln!("EC_IB px={px} py={py} side={side} w={write_w} h={write_h}");
19844 }
19845
19846 if std::env::var_os("EC_AV1_TELL").is_some() {
19847 eprintln!(
19848 "TELL mi_row={} mi_col={} label=block_entry side={side} tell={} range={}",
19849 rmi, cmi, dec.debug_bitpos(), dec.debug_state().0
19850 );
19851 }
19852 let skip_mode_ctx =
19853 usize::from(neighbours.above_skip_mode[cmi]) + usize::from(neighbours.left_skip_mode[rmi]);
19854 // lane-comppin r3: skip_mode desync isolation -- dump ctx + the pre-read
19855 // MSAC tell so it can be diffed against an equivalent hook in libaom's
19856 // own `read_skip_mode`/`av1_get_skip_mode_context`.
19857 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
19858 eprintln!(
19859 "EC_SKIPMODE r={r} c={c} ctx={skip_mode_ctx} skip_mode_present={skip_mode_present} tell_before={}",
19860 dec.debug_bitpos()
19861 );
19862 }
19863 // spec 5.11.5 `inter_frame_mode_info`: `inter_segment_id(1)` before
19864 // `skip_mode`/`skip`, `inter_segment_id(0)` after them.
19865 let (seg_mi_r, seg_mi_c) = (rmi, cmi);
19866 let (seg_w_mi, seg_h_mi) = (write_w / 4, write_h / 4);
19867 inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, false, true);
19868 // libaom `read_skip_mode` (decodemv.c): `if (!is_comp_ref_allowed(bsize))
19869 // return 0` -- a 16x4 / 4x16 strip (min(bw, bh) == 4, blockd.h:65) reads
19870 // no `skip_mode` symbol at all.
19871 let comp_allowed = write_w.min(write_h) >= 8;
19872 let skip_mode =
19873 skip_mode_present && comp_allowed && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
19874 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
19875 eprintln!(
19876 "EC_SKIPMODE r={r} c={c} result={skip_mode} tell_after={}",
19877 dec.debug_bitpos()
19878 );
19879 }
19880 if skip_mode {
19881 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
19882 }
19883
19884 let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]);
19885 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
19886 inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, skip, false);
19887 maybe_read_cdef_idx(dec, rmi, cmi, skip);
19888 // lane-inter4 r1: spec 5.11.6's `bSize == sbSize` -- a 64x32/64x16 strip
19889 // is NOT the whole superblock, so its `skip` never suppresses the read.
19890 // lane-sb128c r7: `sbSize` is 128 under `--sb-size=128`, so the whole-block
19891 // test is against the sequence's own superblock side, not a hardcoded 64.
19892 let sb_px = sb_mi_cur() as usize * 4;
19893 let whole_sb = side == sb_px && write_w == sb_px && write_h == sb_px;
19894 maybe_read_delta_q(dec, cdfs, rmi, cmi, whole_sb, skip);
19895 maybe_read_delta_lf(dec, cdfs, rmi, cmi, whole_sb, skip);
19896 let (has_above, has_left) = (
19897 rmi > neighbours.tile_row0_mi,
19898 cmi > neighbours.tile_col0_mi,
19899 );
19900 let (above_inter, left_inter) = (neighbours.above_inter[cmi], neighbours.left_inter[rmi]);
19901 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
19902 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
19903 // lane-sb128c r1: this round wires the INTER half of a 128x128 block (four
19904 // TX_64X64 luma units and four TX_32X32 chroma units interleaved per mu
19905 // chunk). An INTRA block at that size inside an inter frame takes the
19906 // intra tail below, which still codes one whole-block chroma unit and one
19907 // `read_tx_size` at 128 -- refuse by name instead of mis-decoding it.
19908 if std::env::var_os("EC_TRACE_MODE").is_some() {
19909 eprintln!(
19910 "EC_MODE mi_row={} mi_col={} rng={} is_inter={} skip={} side={side}",
19911 rmi,
19912 cmi,
19913 dec.debug_state().0,
19914 u8::from(is_inter),
19915 u8::from(skip)
19916 );
19917 }
19918 // lane-warp r5: see `reject_residual` -- a square-block decode of a
19919 // HORZ_B strip is symbol-exact only for `skip` (no residual, no
19920 // motion_mode/warp symbol). lane-intrarect r1 MOVED this gate from just
19921 // after the `skip` read to here, past `is_inter` (class
19922 // [[refusal-short-circuits-its-own-code]]: at the old place it refused
19923 // 24/24 attempts of this lane's own gate before the intra arm below
19924 // could run). An INTRA strip with its true `write_w`x`write_h` footprint
19925 // now codes its residual rectangularly ([`decode_intra_rect_in_inter`]);
19926 // an INTER one, and a strip decoded with square dimensions anyway, still
19927 // cannot.
19928 // merge b51719f+lane-intrarect: main's `rect_inter_residual_supported`
19929 // term stays -- lane-inter4's 16x8/8x16 inter leaves DO code a
19930 // rectangular residual, and the lane's condition (written before that
19931 // landed) refused every one of them.
19932 if reject_residual
19933 && !skip
19934 && !rect_inter_residual_supported(write_w, write_h)
19935 && (is_inter || (write_w == side && write_h == side))
19936 {
19937 if std::env::var_os("EC_RECTRES").is_some() {
19938 eprintln!(
19939 "EC_RECTRES w={write_w} h={write_h} side={side} skip={} is_inter={} mi_row={rmi} mi_col={cmi}",
19940 u8::from(skip),
19941 u8::from(is_inter)
19942 );
19943 }
19944 return Err(unsupported(
19945 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
19946 ));
19947 }
19948 if std::env::var_os("EC_AV1_TELL").is_some() {
19949 eprintln!(
19950 "TELL mi_row={} mi_col={} label=post_is_inter skip_mode={skip_mode} skip={skip} is_inter={is_inter} tell={} range={}",
19951 rmi, cmi, dec.debug_bitpos(), dec.debug_state().0
19952 );
19953 }
19954
19955 let mode_for_tx;
19956 let uv_predict_mode;
19957 let (luma_grid, u_grid, v_grid);
19958 let block_filter;
19959 let ref_frame_for_lf;
19960 let globalmv_for_lf;
19961 // lane-av1comp: `Some((comp_group_idx, compound_idx))` only for a real
19962 // `COMPOUND_REFERENCE` block -- applied to `neighbours` *after* the
19963 // common `record_inter` call below (which would otherwise stamp the
19964 // single-ref ALTREF-special-case default over it).
19965 let mut compound_ctx: Option<(i8, u8, u8)> = None;
19966 // lane-txselect: `read_block_tx_size`'s leaf transform units (spec
19967 // 5.11.17), `Some` only when this block's var-tx tree resolved to more
19968 // than one luma transform -- read back by the residual loop, the
19969 // coefficient-context write-back and the loop-filter grid fill below.
19970 let mut vartx_leaves: Option<Vec<(usize, usize, usize, usize)>> = None;
19971 let at_mi = at;
19972 // lane-vert46 r1: set when this block's chroma was coded as one 32x32 unit
19973 // per 64x64 "mu" chunk (any side above 64), so the end-of-block record
19974 // below must NOT re-stamp the chroma neighbour context from the assembled
19975 // whole-block grid.
19976 let mut mu_chroma = false;
19977 if is_inter {
19978 let above_nbr = has_above.then(|| NeighbourRef {
19979 is_inter: above_inter,
19980 ref0: if above_inter {
19981 neighbours.above_ref[cmi]
19982 } else {
19983 0
19984 },
19985 ref1: neighbours.above_ref1[cmi],
19986 uni: neighbours.above_ref1[cmi]
19987 .is_some_and(|r1| is_uni_comp_ref(neighbours.above_ref[cmi], r1)),
19988 });
19989 let left_nbr = has_left.then(|| NeighbourRef {
19990 is_inter: left_inter,
19991 ref0: if left_inter {
19992 neighbours.left_ref[rmi]
19993 } else {
19994 0
19995 },
19996 ref1: neighbours.left_ref1[rmi],
19997 uni: neighbours.left_ref1[rmi]
19998 .is_some_and(|r1| is_uni_comp_ref(neighbours.left_ref[rmi], r1)),
19999 });
20000 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
20001 eprintln!(
20002 "EC_PRECOMP r={r} c={c} skip_mode={skip_mode} skip={skip} reference_select={reference_select} tell={}",
20003 dec.debug_bitpos()
20004 );
20005 }
20006 let is_compound =
20007 skip_mode
20008 || (reference_select
20009 // `is_comp_ref_allowed` (blockd.h:65) gates the
20010 // `comp_mode` read exactly as it gates `skip_mode`.
20011 && comp_allowed
20012 && read_comp_mode(dec, cdfs, above_nbr, left_nbr));
20013 if is_compound {
20014 let (ref0, ref1) = if skip_mode {
20015 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
20016 } else {
20017 read_compound_ref_frames(
20018 dec,
20019 cdfs,
20020 above_nbr,
20021 left_nbr,
20022 neighbours.above_ref[cmi],
20023 neighbours.left_ref[rmi],
20024 )
20025 };
20026 let (mi_row, mi_col) = (rmi, cmi);
20027 // lane-rect r2: true footprint, mirroring the single-ref path below.
20028 let bw4 = write_w / 4;
20029 let bh4 = write_h / 4;
20030 // spec 7.10.2.8, doubled per side (`CompoundTplArgs`): same
20031 // `use_ref_frame_mvs` gating as the single-ref `tpl` build
20032 // below, just one `get_relative_dist` per reference.
20033 let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs {
20034 field: t.field,
20035 cur_offset_0: crate::motion_field::get_relative_dist(
20036 t.order_hint_bits,
20037 t.order_hint,
20038 t.ref_order_hints[(ref0 - LAST_FRAME) as usize],
20039 ),
20040 cur_offset_1: crate::motion_field::get_relative_dist(
20041 t.order_hint_bits,
20042 t.order_hint,
20043 t.ref_order_hints[(ref1 - LAST_FRAME) as usize],
20044 ),
20045 allow_high_precision_mv,
20046 });
20047 let gm_table = build_gm_mv_table(
20048 global_motion,
20049 mi_row,
20050 mi_col,
20051 bw4,
20052 bh4,
20053 allow_high_precision_mv,
20054 force_integer_mv,
20055 );
20056 let comp_stack = crate::mvstack::find_mv_stack_compound(
20057 grid,
20058 mi_row,
20059 mi_col,
20060 bw4,
20061 bh4,
20062 (ref0, ref1),
20063 mi_cols as usize,
20064 mi_rows as usize,
20065 sign_bias_table,
20066 &gm_table,
20067 comp_tpl,
20068 );
20069 let compound_mode = if skip_mode {
20070 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
20071 } else {
20072 read_inter_compound_mode(dec, cdfs, comp_stack.new_mv_ctx, comp_stack.ref_mv_ctx)
20073 };
20074 let (mv0, mv1) = assign_compound_mv(
20075 dec,
20076 cdfs,
20077 &comp_stack,
20078 compound_mode,
20079 allow_high_precision_mv,
20080 force_integer_mv,
20081 (gm_table[(ref0 - LAST_FRAME) as usize], gm_table[(ref1 - LAST_FRAME) as usize]),
20082 );
20083 if std::env::var_os("EC_TRACE_MODE").is_some() {
20084 eprintln!(
20085 "EC_MODE_VAL mi_row={mi_row} mi_col={mi_col} mode={} ref0={ref0} ref1={ref1} mv0=({},{}) stack={} rng={}",
20086 compound_mode + 17,
20087 mv0.0,
20088 mv0.1,
20089 comp_stack.entries.len(),
20090 dec.debug_state().0
20091 );
20092 for (i, e) in comp_stack.entries.iter().enumerate() {
20093 eprintln!(
20094 "EC_STACK mi_row={mi_row} mi_col={mi_col} i={i} this=({},{}) comp=({},{}) w={}",
20095 e.mv0.0, e.mv0.1, e.mv1.0, e.mv1.1, e.weight
20096 );
20097 }
20098 }
20099 let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV
20100 // spec `is_nontrans_global_motion`: ALL active refs' models must
20101 // be non-TRANSLATION (IDENTITY counts) for the compound block's
20102 // interp-filter read to be suppressed.
20103 let gm_nontrans = is_globalmv
20104 && global_motion[(ref0 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation
20105 && global_motion[(ref1 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation;
20106 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
20107 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
20108 // lane-cwarp r1: `is_global_mv_block` (blockd.h:421-429) is
20109 // PER REFERENCE SLOT -- mode GLOBAL_GLOBALMV, block >= 8x8, and
20110 // THAT slot's own gm model > TRANSLATION. `bw4`/`bh4` come from
20111 // the write extent below, so recompute the size bound from
20112 // `side` here (the block's own size, what libaom's `bsize`
20113 // is).
20114 let is_global_mv0 = is_globalmv
20115 && side >= 8
20116 && global_motion[(ref0 - LAST_FRAME) as usize].model as u8 > 1;
20117 let is_global_mv1 = is_globalmv
20118 && side >= 8
20119 && global_motion[(ref1 - LAST_FRAME) as usize].model as u8 > 1;
20120 // libaom `av1_init_warp_params` + `allow_warp`'s
20121 // `global_warp_allowed` branch, run once per reference for a
20122 // compound block exactly as for a single-ref one (reconinter.c
20123 // `build_inter_predictors_8x8_and_bigger` loops over `ref` and
20124 // calls `av1_init_warp_params` inside the loop) -- WARPED_CAUSAL
20125 // never reaches here (spec 5.11.27 / libaom `read_motion_mode`:
20126 // `has_second_ref` returns SIMPLE_TRANSLATION), so the local-warp
20127 // arm of `allow_warp` is dead on this path and only the global
20128 // one applies. `force_integer_mv` short-circuits
20129 // `av1_init_warp_params` before `allow_warp`.
20130 let compound_warp = |ref_frame: i8, eligible: bool| {
20131 if eligible
20132 && !force_integer_mv
20133 && !global_motion[(ref_frame - LAST_FRAME) as usize].invalid
20134 {
20135 crate::warp::global_warp_params(
20136 global_motion[(ref_frame - LAST_FRAME) as usize].params,
20137 )
20138 } else {
20139 None
20140 }
20141 };
20142 let warp0 = compound_warp(ref0, is_global_mv0);
20143 let warp1 = compound_warp(ref1, is_global_mv1);
20144 if warp0.is_some() || warp1.is_some() {
20145 COMPOUND_WARP_HITS.with(|c| c.set(c.get() + 1));
20146 }
20147 // spec `get_ref_filter_type`: matches when EITHER of the
20148 // neighbour's two references equals this block's own ref0 --
20149 // `above_ref1`/`left_ref1` is the neighbour's real second
20150 // reference (`record_compound_ctx`) when it was itself a
20151 // compound block; checking `above_ref`/`left_ref` alone drops a
20152 // real filter match down to the "no neighbour" sentinel
20153 // whenever the shared reference sits in the neighbour's SECOND
20154 // slot (lane-av1idx r2).
20155 let above_filter_ctx = if neighbours.above_ref[cmi] == ref0
20156 || neighbours.above_ref1[cmi] == Some(ref0)
20157 {
20158 neighbours.above_filter[cmi]
20159 } else {
20160 [3, 3]
20161 };
20162 let left_filter_ctx = if neighbours.left_ref[rmi] == ref0
20163 || neighbours.left_ref1[rmi] == Some(ref0)
20164 {
20165 neighbours.left_filter[rmi]
20166 } else {
20167 [3, 3]
20168 };
20169 globalmv_for_lf = is_globalmv;
20170 ref_frame_for_lf = ref0;
20171 mode_for_tx = 0;
20172 uv_predict_mode = DC_PRED;
20173 // lane-rect r2: `grid` (mvstack.rs's own MiGrid, distinct from
20174 // `neighbours`) must be stamped with the block's true footprint
20175 // too -- a square `bw4`x`bw4` stamp here claims a rect strip's
20176 // NEXT strip's own rows/cols before it decodes, corrupting
20177 // every later mvstack scan that reads this cell back.
20178 for dr in 0..bh4 {
20179 for dc in 0..bw4 {
20180 grid.set(
20181 mi_row + dr,
20182 mi_col + dc,
20183 MiInfo {
20184 is_inter: true,
20185 ref_frame: ref0,
20186 ref_frame1: Some(ref1),
20187 mv1: Some(mv1),
20188 mv: mv0,
20189 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
20190 size: bw4,
20191 size_h: bh4,
20192 // libaom `is_global_mv_block`: per-ref-slot, mode
20193 // GLOBAL_GLOBALMV, block >= 8x8, and THAT slot's
20194 // own gm model > TRANSLATION (IDENTITY excluded
20195 // too -- the two-predicate trap, distinct from
20196 // `gm_nontrans` above which allows IDENTITY).
20197 is_global_mv0,
20198 is_global_mv1,
20199 },
20200 );
20201 }
20202 }
20203 // spec 5.11.25's `comp_group_idx`/`compound_idx`: only read when
20204 // masked compound / distance-weighted compound are actually
20205 // enabled for this stream -- `is_any_masked_compound_used_here`
20206 // is `true` for every block size this decoder ever reaches
20207 // (`min(side,side) >= 8`, `COMPOUND_DIFFWTD` always eligible
20208 // there), so the gate reduces to the sequence header bit; kept
20209 // as an explicit call so a future smaller block size is not
20210 // silently wrong (libaom `reconinter.h::is_any_masked_compound_used`).
20211 let group_ctx = get_comp_group_idx_context(neighbours, (rmi, cmi), side);
20212 let comp_group_idx = if !skip_mode
20213 && enable_masked_compound
20214 && is_any_masked_compound_used_here(write_w, write_h)
20215 {
20216 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
20217 } else {
20218 0
20219 };
20220 if std::env::var_os("EC_TRACE_MODE").is_some() {
20221 eprintln!(
20222 "EC_CGI mi_row={rmi} mi_col={cmi} ctx={group_ctx} val={comp_group_idx} rng={}",
20223 dec.debug_state().0
20224 );
20225 }
20226 // lane-maskcomp r2 / lane-wedge r3: `Some(mask_type)` for a
20227 // `COMPOUND_DIFFWTD` block, `Some(mask)` (wedge codebook lookup)
20228 // for a `COMPOUND_WEDGE` block -- exactly one of the two is set
20229 // when `comp_group_idx == 1`.
20230 let mut diffwtd_mask_type: Option<u8> = None;
20231 let mut wedge_mask: Option<&'static [u8]> = None;
20232 if comp_group_idx == 1 {
20233 // lane-maskcomp r1: `read_compound_type` (spec 5.11.25,
20234 // libaom `decodemv.c` 1634-1656). `is_interinter_compound_used
20235 // (COMPOUND_WEDGE, bsize)` (`av1_is_wedge_used`,
20236 // `av1_wedge_params_lookup`) is true for every square bsize
20237 // this leaf reaches (8x8/16x16/32x32 all have
20238 // `wedge_types > 0`), so `compound_type` always reads a real
20239 // symbol here -- no alphabet collapse to worry about at this
20240 // block-size family.
20241 // lane-mcomp64 r1: `av1_is_wedge_used` is false at 64x64
20242 // (`av1_wedge_params_lookup[BLOCK_64X64].wedge_types == 0`),
20243 // so libaom's `read_compound_type` (decodemv.c 1634-1656)
20244 // writes NO `compound_type` symbol there and INFERS
20245 // `COMPOUND_DIFFWTD` -- only the 1-bit `mask_type` literal
20246 // follows. `None` here is exactly that inferred arm.
20247 // lane-inter16ab r3: the row is this block's TRUE
20248 // `BLOCK_SIZES_ALL` index, not the enclosing square `side`'s
20249 // -- a 16x8 strip reads `compound_type_cdf[BLOCK_16X8]`.
20250 let wedge_bsize =
20251 bsize_all_index(write_w, write_h).filter(|_| wedge_used_bsize(write_w, write_h));
20252 let compound_type = match wedge_bsize {
20253 Some(b) => dec.symbol(&mut cdfs.compound_type[b]),
20254 None => 1,
20255 };
20256 if let Some(wedge_bsize) = wedge_bsize.filter(|_| compound_type == 0) {
20257 // COMPOUND_WEDGE: lane-wedge r3, codebook checksum-
20258 // verified vs independent C dump (wedge.rs).
20259 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
20260 let wedge_sign = dec.literal(1);
20261 WEDGE_HITS.with(|c| c.set(c.get() + 1));
20262 if let Some(k) = rect_wedge_slot(write_w, write_h) {
20263 RECT_WEDGE_HITS.with(|c| {
20264 let mut a = c.get();
20265 a[k] += 1;
20266 c.set(a);
20267 });
20268 }
20269 // lane-inter16ab r5: the codebook row is this block's TRUE
20270 // footprint (`av1_wedge_params_lookup[bsize]`: hgtw for
20271 // h>w, hltw for h<w, plus that bsize's own signflip row).
20272 // Masks are padded to stride `max(bw,bh) == side`, so the
20273 // square blend below indexes them unchanged and the
20274 // padding never reaches the frame (only `write_w x
20275 // write_h` is written out).
20276 wedge_mask = Some(
20277 crate::wedge::wedge_masks()
20278 .codebook(write_w, write_h)
20279 .mask(wedge_sign as usize, wedge_index as usize),
20280 );
20281 } else {
20282 // COMPOUND_DIFFWTD: `mask_type`, MAX_DIFFWTD_MASK_BITS==1.
20283 let mask_type = dec.literal(1);
20284 diffwtd_mask_type = Some(mask_type as u8);
20285 if wedge_bsize.is_none() {
20286 DIFFWTD_INFERRED_HITS.with(|c| c.set(c.get() + 1));
20287 }
20288 }
20289 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
20290 if write_w != write_h {
20291 RECT_MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
20292 }
20293 }
20294 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): r16/r17
20295 // called this a `predict_compound_intermediate`/`combine_compound`
20296 // reconstruction defect. r1 FALSIFIED that hypothesis outright:
20297 // unmasking and running the real gates
20298 // (a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly,
20299 // a_real_aomenc_stream_with_compound_references_decodes_pixel_exact)
20300 // shows the plain-average blend is bit-exact *most of the time*
20301 // -- `combine_compound`'s two-shift-in-one round2 was proven
20302 // algebraically identical to libaom's separate
20303 // `>>DIST_PRECISION_BITS`-then-`ROUND_POWER_OF_TWO` sequence
20304 // (av1_dist_wtd_convolve_2d_c, convolve.c:402-415) for every
20305 // input, and a whole-pel zero-MV compound block (mv0=mv1=(0,0),
20306 // the common case a lag-in-frames GOP's hidden altref frames
20307 // hit) reproduces aomdec's own pre-deblock dump byte-for-byte
20308 // for several consecutive frames.
20309 //
20310 // The real defect a live gate run isolated (seed 49,
20311 // `fixtures/av1blend-r1-mismatch.obu`): decode-order frame 0
20312 // (keyframe) and frame 1 (first hidden altref, `ref1 ==
20313 // ALTREF_FRAME`) match aomdec's own pre-deblock dump byte for
20314 // byte; decode-order frame 2 -- same shape, same zero MV, only
20315 // difference `ref1 == BWDREF_FRAME` instead of `ALTREF_FRAME` --
20316 // is the *first* frame to diverge (881/6144 luma+chroma bytes).
20317 // Every later frame up through decode-order 9 also mismatches,
20318 // *including* frame 8, whose four blocks are back to
20319 // `ref1 == ALTREF_FRAME` only -- ruling out "BWDREF_FRAME's MC
20320 // math is wrong" (that block's own math is proven exact) in
20321 // favour of "the picture sitting in some DPB slot is already
20322 // wrong by the time frame 2 reads it, and the corruption
20323 // propagates through refresh_frame_flags into every later
20324 // reference regardless of which named ref a later block picks".
20325 // Frames 10 through 18 (once the GOP's lineage stops tracing
20326 // back through the bad slot) are bit-exact again. This points at
20327 // reference-slot bookkeeping (`ref_slots`/`refresh_frame_flags`
20328 // in `stream.rs`'s `decode_stream`, or `ref_order_hints`/DPB
20329 // indexing feeding `dist_wtd_comp_weight_assign`) around
20330 // BWDREF_FRAME specifically, not at the MC/blend arithmetic in
20331 // mc.rs. Not isolated further within lane-av1blend's budget --
20332 // refuse by name rather than ship a blend that is right only
20333 // sometimes. Ceiling: r13/r14's MC plumbing above this line
20334 // stays -- only the plain-average reconstruct is masked off
20335 // again. Upgrade: instrument `ref_slots`/`refresh_frame_flags`
20336 // per decode-order frame (which slot each `Frame` OBU refreshes,
20337 // and which slot each `ref_frame_idx[BWDREF_FRAME - LAST_FRAME]`
20338 // reads) against aomdec's own `RefCntBuffer` bookkeeping on
20339 // `fixtures/av1blend-r1-mismatch.obu`, starting at decode-order
20340 // frame 2.
20341 //
20342 // r2 (fresh fixture, seed 45, same recipe -- the original r1
20343 // fixture is gitignored and could not be regenerated byte-exact):
20344 // static review of `stream.rs`'s `ref_slots`/`refresh_frame_flags`/
20345 // `cdf_slots` bookkeeping and the `show_existing_frame` refresh
20346 // arm (spec 7.21: only refreshes on a shown KEY frame, which the
20347 // parser already enforces at `frame.rs:791/815` -- `refresh_frame_flags`
20348 // is forced 0 on every non-key `show_existing_frame`) turned up
20349 // nothing wrong; `other_refs`/`ref_planes` slot indexing for
20350 // `BWDREF_FRAME` is spec-correct too. A live unmasked run
20351 // isolated a *different, smaller* shape than r1's: decode-order
20352 // frame 3 (a `ref1 == BWDREF_FRAME`, zero-MV, simple-average
20353 // compound block) is the first to diverge from ffmpeg (worst
20354 // delta 1, luma only, clustered at 32-pixel block edges) even
20355 // though BOTH its compound inputs -- the key frame and
20356 // decode-order frame 2's own picture (`ref1 == ALTREF_FRAME`,
20357 // itself proven bit-exact: it is later re-shown via
20358 // `show_existing_frame` and matches ffmpeg exactly) -- are
20359 // independently pixel-exact, and the blend arithmetic is the
20360 // same proven-exact formula. That rules out "wrong slot"/"stale
20361 // picture" for this fixture: the inputs are right, so the defect
20362 // is in decode-order frame 3's *own* per-block decode (entropy
20363 // desync from compound-CDF adaptation carried across a slot, or
20364 // the compound mode/MV read itself) -- not in `ref_slots`/
20365 // `refresh_frame_flags`. Not isolated further within budget.
20366 // Upgrade: bisect decode-order frame 3's tile decode against a
20367 // synced `EC_TOK`/`EC_PART` trace from the instrumented aomdec
20368 // build (`/tmp/libaom-src/build/decoder-debug/aomdec`) on
20369 // `fixtures/av1blend-r1-mismatch.obu` (seed 45 now, not seed 49)
20370 // -- the pre-deblock dump frame-index alignment between this
20371 // crate and that aomdec build is NOT 1:1 on this fixture (23
20372 // dumps here vs 24 there), so calibrate that first.
20373 // r3 (this round): pre-deblock buffers were bisected byte-for-byte
20374 // against an instrumented aomdec build (frame-index alignment
20375 // recalibrated via content-hash matching rather than the raw
20376 // dump count -- the keyframe never calls a pre-deblock dump at
20377 // all, since only `decode_inter_frame_tile` does, which is the
20378 // whole "23 vs 24" gap, not a real bug).
20379 // Decode-order frame 3 (`fixtures/av1blend-r1-mismatch.obu`,
20380 // seed 45) is still the first divergence: PRE-deblock differs
20381 // from aomdec's own pre-deblock dump by up to 1, on ~20% of
20382 // luma pixels, clustered where its two compound inputs' pixel
20383 // values disagree by more than a couple of levels -- both
20384 // inputs (the keyframe and decode-order frame 2's own picture)
20385 // are independently proven bit-exact (pre- and post-deblock)
20386 // against aomdec, and `decodemv`'s own EC_TRACE (mode/mv/skip)
20387 // matches this decoder's block loop exactly for every block in
20388 // this frame. Solving `aomval = (key*w0 + bwd*w1 + 8) >> 4` for
20389 // every mismatching pixel against `key`/`bwd` (both known-exact)
20390 // picks out `w0=9, w1=7` for the majority (525/846) with zero
20391 // matches for the plain average this decoder actually emits or
20392 // the reversed `w0=7, w1=9` -- i.e. `compound_idx` is being
20393 // decoded as `1` (simple average, spec `COMPOUND_AVERAGE`) when
20394 // the real bitstream encoded `0` (`COMPOUND_DISTWTD`,
20395 // `dist_wtd_comp_weight_assign`'s own weights for this frame's
20396 // order-hint distances 2/3 land on exactly `(9, 7)` -- this
20397 // decoder's own `dist_wtd_comp_weight_assign` was independently
20398 // re-verified against `QUANT_DIST_WEIGHT`/`QUANT_DIST_LOOKUP_TABLE`
20399 // by hand for these distances and gives the same `(9, 7)`).
20400 // `get_comp_index_context` was checked line-for-line against
20401 // libaom's `pred_common.h` (the `fwd`/`bck` distance halves, the
20402 // `above_mi`/`left_mi` `has_second_ref`/`ALTREF_FRAME` fallback,
20403 // the `3 * offset` term) and matches; `Default_Compound_Idx_Cdf`
20404 // (`cdf.rs`'s `COMPOUND_IDX`) matches `entropymode.c`'s
20405 // `default_compound_idx_cdfs` value-for-value; the read is
20406 // gated on `!skip_mode && enable_jnt_comp`, matching libaom's
20407 // `has_second_ref(mbmi) && !mbmi->skip_mode` outer guard plus
20408 // `order_hint_info.enable_dist_wtd_comp` inner guard. The
20409 // remaining 321/846 mismatched pixels do NOT fit `(9, 7)`
20410 // either -- some blocks in this frame plausibly decode a
20411 // genuinely different (correct, context-dependent) compound_idx
20412 // than block (0,0)'s own -- so this is not simply "always wrong
20413 // the same way": table/context/gate are all individually
20414 // verified correct, yet the decoded VALUE at this specific
20415 // symbol is wrong at least once in this frame. Not isolated
20416 // further within budget. Upgrade: instrument `dec.symbol`'s own
20417 // range/bit state (`rng`/`tell`, matching aomdec's own EC_PART
20418 // trace fields) immediately before and after the `compound_idx`
20419 // read specifically, not just the surrounding mode/mv/skip
20420 // trace which does match -- the desync (if any) is local to
20421 // this one read, not a wider stream desync.
20422 //
20423 // r5 (this round): the `resolve_interp_filter` call used to sit
20424 // right here, ahead of `comp_group_idx`/`compound_idx` -- spec
20425 // 5.11.19/libaom `decodemv.c:1575` reads `interp_filter` AFTER
20426 // `read_compound_type`, not before, so that was a genuine
20427 // ordering bug for a Switchable-filter frame (moved below, past
20428 // the `compound_ctx = Some(...)` line). It does NOT explain this
20429 // fixture's own mismatch, though: `av1blend-r1-mismatch.obu`'s
20430 // header carries a *fixed* interpolation filter
20431 // (`interp_fixed = Some(Regular)`, confirmed live via a
20432 // one-off dump), so `resolve_interp_filter` never read a symbol
20433 // in either position -- zero bits moved, decoded values
20434 // unchanged before and after the reorder. Kept anyway: it is a
20435 // real spec-order fix for the next Switchable-filter compound
20436 // stream, independently correct regardless of this fixture.
20437 //
20438 // Also ruled out this round: comparing this crate's own
20439 // `SymbolDecoder::debug_bitpos()` against aomdec's
20440 // `aom_reader_tell()` at the block boundary is NOT a valid
20441 // desync probe -- they are different quantities (raw consumed
20442 // input bits vs. an entropy-cost estimate that advances without
20443 // a literal byte fetch), so equal/unequal bitpos proves nothing
20444 // either way. Do not repeat that comparison; instead trace
20445 // `range`/`value` (this crate) against libaom's own internal
20446 // `dif`/`rng` (needs new instrumentation in both) immediately
20447 // after each read *upstream* of this one in the same block:
20448 // `read_comp_mode`, `read_compound_ref_frames` (comp_ref_type/
20449 // uni_comp_ref/comp_ref/comp_bwdref), `read_inter_compound_mode`,
20450 // and the DRL loop. All of those independently decoded the SAME
20451 // values this crate and aomdec both show (ref0=1, ref1=5, mode
20452 // NEAREST_NEARESTMV, mv=(0,0)) -- but an upstream *context*
20453 // miscomputation can still decode the identical symbol value off
20454 // a slightly different CDF, narrowing `range` by a different
20455 // amount than aomdec without changing the decoded value itself,
20456 // and only surface as a wrong decode a few reads later exactly
20457 // like this. `get_comp_index_context` and the `COMPOUND_IDX`
20458 // table were independently re-verified again this round and are
20459 // still correct; the four candidates above were not re-audited
20460 // this round. Refusing here (rather than shipping a value-exact-
20461 // most-of-the-time blend) until one of them is found wrong.
20462 // r6/r7: found and fixed one real bug (mvstack.rs ref_ctx family
20463 // undercounted compound neighbours in the single_ref_p*/comp_ref*/
20464 // comp_bwdref* context reads -- kept, real fix). Unmasking on
20465 // that fix alone and running the wide gate sweep (many seeds,
20466 // `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`/
20467 // `a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly`,
20468 // cq-level=45) still mismatches roughly half the time, at
20469 // different frames each run for the SAME seed -- aomenc's own
20470 // cpu-used=0 RD search is run-to-run nondeterministic (noted
20471 // above), so this is a second, still-unfound compound_idx defect,
20472 // not the one r6/r7 fixed. r6's own residual-mismatch note (321/
20473 // 846 pixels not fitting the (9,7)-vs-plain-average hypothesis
20474 // either) already flagged more than one bug here. Re-masking:
20475 // do not ship a blend that is right only sometimes.
20476 // lane-av1idx r1: fixed one real bug this round
20477 // (`switchable_interp_ctx` never folded in libaom's
20478 // `INTER_FILTER_COMP_OFFSET` for a compound block's own
20479 // interp_filter context -- kept). Pinned
20480 // `fixtures/av1idx-refsel-pin.obu` (seed 61, reference_select
20481 // gate) still mismatches after that fix (decode-order frame 8
20482 // first, small deltas, worst 1-2, propagating through later
20483 // frames via DPB reference) -- a second, still-unfound bug.
20484 // Re-masking: see that fixture + `scratch_isolate_pinned_mismatch`
20485 // (`EC_AV1_PIN=fixtures/av1idx-refsel-pin.obu EC_AV1_PIN_N=20`)
20486 // for the next round's starting point.
20487 // lane-maskcomp r2: `compound_idx` is only read when
20488 // `comp_group_idx == 0` (libaom `decodemv.c:1606`) -- a masked
20489 // (wedge/diffwtd) block never also carries a distance-weighted
20490 // split. This gate was missing before r2 (dead code: the masked
20491 // path always refused earlier, so it never executed with
20492 // `comp_group_idx == 1` in practice).
20493 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
20494 && !skip_mode
20495 && enable_jnt_comp
20496 {
20497 let idx_ctx = get_comp_index_context(
20498 neighbours,
20499 (rmi, cmi),
20500 side,
20501 order_hint_bits,
20502 order_hint,
20503 ref_order_hints[(ref0 - LAST_FRAME) as usize],
20504 ref_order_hints[(ref1 - LAST_FRAME) as usize],
20505 );
20506 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
20507 if std::env::var_os("EC_TRACE_MODE").is_some() {
20508 eprintln!(
20509 "EC_CIDX mi_row={rmi} mi_col={cmi} ctx={idx_ctx} val={idx} rng={}",
20510 dec.debug_state().0
20511 );
20512 }
20513 if idx == 1 {
20514 (8, 8, 1u8)
20515 } else {
20516 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
20517 order_hint_bits,
20518 order_hint,
20519 ref_order_hints[(ref0 - LAST_FRAME) as usize],
20520 ref_order_hints[(ref1 - LAST_FRAME) as usize],
20521 );
20522 (fwd, bck, 0u8)
20523 }
20524 } else {
20525 (8, 8, 1u8)
20526 };
20527 compound_ctx = Some((ref1, comp_group_idx as u8, compound_idx));
20528 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
20529 eprintln!(
20530 "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={}",
20531 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
20532 );
20533 }
20534
20535 // spec 5.11.19/libaom `decodemv.c` 1575: `read_mb_interp_filter`
20536 // comes AFTER `read_compound_type` (the `comp_group_idx`/
20537 // `compound_idx` reads just above), not before -- moved here
20538 // (lane-av1blend r5) from its old position ahead of those reads,
20539 // which stole their bits for a Switchable-filter compound block
20540 // and desynced every symbol read after it in the tile.
20541 // `av1_is_interp_needed` is also 0 for `skip_mode` blocks: the
20542 // filter is derived (Regular), never read -- same
20543 // conditional-read contract as the WARPED_CAUSAL suppression on
20544 // the single-ref path below.
20545 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
20546 dec,
20547 cdfs,
20548 interp_fixed,
20549 enable_dual_filter,
20550 gm_nontrans || skip_mode,
20551 above_filter_ctx,
20552 left_filter_ctx,
20553 true,
20554 );
20555 block_filter = resolved_filter;
20556
20557 // lane-scaledref r1: each compound tap scales INDEPENDENTLY off
20558 // its own stored reference's luma width (spec 7.11.3.3 derives
20559 // x_scale_fp per reference; libaom `av1_setup_pre_planes` builds
20560 // one `scale_factors` per `ref_frame`), so the two taps can carry
20561 // different ratios in the same block. `REF_NO_SCALE` reduces
20562 // `predict_compound_intermediate`'s walk to the ordinary
20563 // stride-1 one, so the unscaled case is unchanged.
20564 let scale0 = mc::scale_factor(py0.width, frame_width);
20565 let scale1 = mc::scale_factor(py1.width, frame_width);
20566 if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE {
20567 SCALED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
20568 }
20569 // lane-scaledref r2: the MIXED case -- one tap scaled, the other
20570 // not -- is the one an all-frames-scaled recipe never produces,
20571 // and the one a single shared scale factor would get wrong.
20572 if (scale0 == mc::REF_NO_SCALE) != (scale1 == mc::REF_NO_SCALE) {
20573 MIXED_SCALE_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
20574 }
20575
20576 let mut inter0_y = vec![0i32; side * side];
20577 mc::predict_compound_intermediate_kern(
20578 &py0.data,
20579 py0.width,
20580 py0.true_width,
20581 py0.true_height,
20582 mv_to_q4(px, mv0.1, true),
20583 mv_to_q4(py, mv0.0, true),
20584 scale0,
20585 side,
20586 side,
20587 write_w,
20588 write_h,
20589 h_filter,
20590 v_filter,
20591 &mut inter0_y,
20592 );
20593 // lane-cwarp r1: this reference's own GLOBAL warp replaces the
20594 // translational tap (libaom `av1_warp_plane` with
20595 // `conv_params->is_compound`); the blend below is unchanged.
20596 if let Some(wp) = &warp0.as_ref().filter(|_| warp_luma_ok) {
20597 crate::warp::warp_affine_compound(
20598 wp, &py0.data, py0.true_width as i32, py0.true_height as i32,
20599 py0.width as i32, &mut inter0_y, px as i32, py as i32, side as i32,
20600 side as i32, side as i32, 0, 0,
20601 );
20602 }
20603 let mut inter1_y = vec![0i32; side * side];
20604 mc::predict_compound_intermediate_kern(
20605 &py1.data,
20606 py1.width,
20607 py1.true_width,
20608 py1.true_height,
20609 mv_to_q4(px, mv1.1, true),
20610 mv_to_q4(py, mv1.0, true),
20611 scale1,
20612 side,
20613 side,
20614 write_w,
20615 write_h,
20616 h_filter,
20617 v_filter,
20618 &mut inter1_y,
20619 );
20620 // lane-cwarp r1: this reference's own GLOBAL warp replaces the
20621 // translational tap (libaom `av1_warp_plane` with
20622 // `conv_params->is_compound`); the blend below is unchanged.
20623 if let Some(wp) = &warp1.as_ref().filter(|_| warp_luma_ok) {
20624 crate::warp::warp_affine_compound(
20625 wp, &py1.data, py1.true_width as i32, py1.true_height as i32,
20626 py1.width as i32, &mut inter1_y, px as i32, py as i32, side as i32,
20627 side as i32, side as i32, 0, 0,
20628 );
20629 }
20630 let mut pred_y = vec![0u16; side * side];
20631 let mut diffwtd_mask_y = Vec::new();
20632 // lane-wedge r3: `mask_y` is the DIFFWTD buffer just computed OR
20633 // the wedge codebook lookup (comp_group_idx==1's two mutually
20634 // exclusive branches) -- same [`mc::blend_masked_compound`] call
20635 // either way, only the mask source differs.
20636 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
20637 diffwtd_mask_y = vec![0u8; side * side];
20638 DIFFWTD_HITS.with(|c| c.set(c.get() + 1));
20639 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
20640 Some(diffwtd_mask_y.as_slice())
20641 } else {
20642 wedge_mask
20643 };
20644 if let Some(mask_y) = mask_y {
20645 mc::blend_masked_compound(
20646 &inter0_y, &inter1_y, mask_y, side, side, side, false, &mut pred_y,
20647 );
20648 } else {
20649 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
20650 }
20651
20652 let mut inter0_u = vec![0i32; chroma_side * chroma_side];
20653 mc::predict_compound_intermediate_kern(
20654 &pu0.data,
20655 pu0.width,
20656 pu0.true_width,
20657 pu0.true_height,
20658 mv_to_q4(cpx, mv0.1, false),
20659 mv_to_q4(cpy, mv0.0, false),
20660 scale0,
20661 chroma_side,
20662 chroma_side,
20663 write_chroma_w,
20664 write_chroma_h,
20665 h_filter,
20666 v_filter,
20667 &mut inter0_u,
20668 );
20669 // `av1_init_warp_params` bails when the PLANE's block is
20670 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
20671 // block of an 8x8 luma block stays translational.
20672 if let Some(wp) = &warp0 {
20673 if warp_chroma_ok {
20674 crate::warp::warp_affine_compound(
20675 wp, &pu0.data, pu0.true_width as i32, pu0.true_height as i32,
20676 pu0.width as i32, &mut inter0_u, cpx as i32, cpy as i32,
20677 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
20678 );
20679 }
20680 }
20681 let mut inter1_u = vec![0i32; chroma_side * chroma_side];
20682 mc::predict_compound_intermediate_kern(
20683 &pu1.data,
20684 pu1.width,
20685 pu1.true_width,
20686 pu1.true_height,
20687 mv_to_q4(cpx, mv1.1, false),
20688 mv_to_q4(cpy, mv1.0, false),
20689 scale1,
20690 chroma_side,
20691 chroma_side,
20692 write_chroma_w,
20693 write_chroma_h,
20694 h_filter,
20695 v_filter,
20696 &mut inter1_u,
20697 );
20698 // `av1_init_warp_params` bails when the PLANE's block is
20699 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
20700 // block of an 8x8 luma block stays translational.
20701 if let Some(wp) = &warp1 {
20702 if warp_chroma_ok {
20703 crate::warp::warp_affine_compound(
20704 wp, &pu1.data, pu1.true_width as i32, pu1.true_height as i32,
20705 pu1.width as i32, &mut inter1_u, cpx as i32, cpy as i32,
20706 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
20707 );
20708 }
20709 }
20710 let mut pred_u = vec![0u16; chroma_side * chroma_side];
20711 if let Some(mask_y) = mask_y {
20712 mc::blend_masked_compound(
20713 &inter0_u,
20714 &inter1_u,
20715 mask_y,
20716 side,
20717 chroma_side,
20718 chroma_side,
20719 true,
20720 &mut pred_u,
20721 );
20722 } else {
20723 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
20724 }
20725
20726 let mut inter0_v = vec![0i32; chroma_side * chroma_side];
20727 mc::predict_compound_intermediate_kern(
20728 &pv0.data,
20729 pv0.width,
20730 pv0.true_width,
20731 pv0.true_height,
20732 mv_to_q4(cpx, mv0.1, false),
20733 mv_to_q4(cpy, mv0.0, false),
20734 scale0,
20735 chroma_side,
20736 chroma_side,
20737 write_chroma_w,
20738 write_chroma_h,
20739 h_filter,
20740 v_filter,
20741 &mut inter0_v,
20742 );
20743 // `av1_init_warp_params` bails when the PLANE's block is
20744 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
20745 // block of an 8x8 luma block stays translational.
20746 if let Some(wp) = &warp0 {
20747 if warp_chroma_ok {
20748 crate::warp::warp_affine_compound(
20749 wp, &pv0.data, pv0.true_width as i32, pv0.true_height as i32,
20750 pv0.width as i32, &mut inter0_v, cpx as i32, cpy as i32,
20751 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
20752 );
20753 }
20754 }
20755 let mut inter1_v = vec![0i32; chroma_side * chroma_side];
20756 mc::predict_compound_intermediate_kern(
20757 &pv1.data,
20758 pv1.width,
20759 pv1.true_width,
20760 pv1.true_height,
20761 mv_to_q4(cpx, mv1.1, false),
20762 mv_to_q4(cpy, mv1.0, false),
20763 scale1,
20764 chroma_side,
20765 chroma_side,
20766 write_chroma_w,
20767 write_chroma_h,
20768 h_filter,
20769 v_filter,
20770 &mut inter1_v,
20771 );
20772 // `av1_init_warp_params` bails when the PLANE's block is
20773 // narrower/shorter than 8 (`block_width < 8`), so a 4x4 chroma
20774 // block of an 8x8 luma block stays translational.
20775 if let Some(wp) = &warp1 {
20776 if warp_chroma_ok {
20777 crate::warp::warp_affine_compound(
20778 wp, &pv1.data, pv1.true_width as i32, pv1.true_height as i32,
20779 pv1.width as i32, &mut inter1_v, cpx as i32, cpy as i32,
20780 chroma_side as i32, chroma_side as i32, chroma_side as i32, 1, 1,
20781 );
20782 }
20783 }
20784 let mut pred_v = vec![0u16; chroma_side * chroma_side];
20785 if let Some(mask_y) = mask_y {
20786 mc::blend_masked_compound(
20787 &inter0_v,
20788 &inter1_v,
20789 mask_y,
20790 side,
20791 chroma_side,
20792 chroma_side,
20793 true,
20794 &mut pred_v,
20795 );
20796 } else {
20797 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
20798 }
20799
20800 // lane-inter4 r2: a rectangular strip's transform tree starts from
20801 // its own rect `max_txsize_rect_lookup` entry, not a square one.
20802 let rect_tu = (write_w, write_h) != (side, side);
20803 vartx_leaves = if rect_tu {
20804 read_block_tx_size_rect(
20805 dec,
20806 cdfs,
20807 neighbours,
20808 at_mi,
20809 (write_w, write_h),
20810 (mi_cols as usize, mi_rows as usize),
20811 skip,
20812 )?
20813 } else {
20814 read_block_tx_size(
20815 dec,
20816 cdfs,
20817 neighbours,
20818 at_mi,
20819 side,
20820 (mi_cols as usize, mi_rows as usize),
20821 true,
20822 skip,
20823 )?
20824 .1
20825 };
20826 if skip {
20827 y.reconstruct_mc_rect(
20828 px,
20829 py,
20830 side,
20831 write_w,
20832 write_h,
20833 &pred_y,
20834 &vec![0i32; side * side],
20835 );
20836 u.reconstruct_mc_rect(
20837 cpx,
20838 cpy,
20839 chroma_side,
20840 write_chroma_w,
20841 write_chroma_h,
20842 &pred_u,
20843 &vec![0i32; chroma_side * chroma_side],
20844 );
20845 v.reconstruct_mc_rect(
20846 cpx,
20847 cpy,
20848 chroma_side,
20849 write_chroma_w,
20850 write_chroma_h,
20851 &pred_v,
20852 &vec![0i32; chroma_side * chroma_side],
20853 );
20854 luma_grid = vec![0i32; side * side];
20855 u_grid = vec![0i32; chroma_side * chroma_side];
20856 v_grid = vec![0i32; chroma_side * chroma_side];
20857 } else {
20858 // lane-inter4 r2: a rect strip's coefficient context spans its
20859 // OWN width above and height left -- reading `side` cells both
20860 // ways indexes past the tile's last mi row for a bottom strip.
20861 let around = if rect_tu {
20862 neighbours.around_mi_rect(at_mi, write_w, write_h)
20863 } else {
20864 neighbours.around_mi(at, side)
20865 };
20866 let luma_tx_type;
20867 // lane-sb128c r1: a 128x128 inter block's four chroma units
20868 // are read INSIDE the luma leaf loop (one per 64x64 mu chunk);
20869 // these collect them for the block-level neighbour write-back.
20870 let mut u_units = vec![0i32; chroma_side * chroma_side];
20871 let mut v_units = vec![0i32; chroma_side * chroma_side];
20872 if let Some(leaves) = vartx_leaves.clone() {
20873 // spec 5.11.17's transform tree, leaf by leaf in the order
20874 // `read_var_tx_size` coded it: each unit reads its own
20875 // coefficients against the neighbour magnitudes the
20876 // earlier units already wrote, and reconstructs over its
20877 // own slice of the block's motion-compensated predictor.
20878 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
20879 let mut first_tx_type = TxType::DctDct;
20880 for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() {
20881 let tu_mi = (at_mi.0 + row, at_mi.1 + col);
20882 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
20883 let (tu_grid, tu_tx_type) = if tw == th {
20884 let tx_px = tw;
20885 let mut tu_pred = Vec::with_capacity(tx_px * tx_px);
20886 for rr in 0..tx_px {
20887 let start = (row * MI + rr) * side + col * MI;
20888 tu_pred.extend_from_slice(&pred_y[start..start + tx_px]);
20889 }
20890 let scan = default_scan(tx_px.min(32));
20891 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI);
20892 read_inter_plane(
20893 dec,
20894 cdfs,
20895 inter_txbset_for(tx_px, reduced),
20896 &scan,
20897 0,
20898 neighbours.around_mi(tu_mi, tx_px)[0],
20899 mode_for_tx,
20900 y,
20901 tu_px,
20902 tu_py,
20903 tx_px,
20904 base_q_idx,
20905 &tu_pred,
20906 None,
20907 Some(tu_skip_ctx),
20908 )?
20909 } else {
20910 // lane-r14 r3: a 1:4 strip's `sub_tx_size_map`
20911 // sub-transform is RECTANGULAR (TX_64X16 ->
20912 // TX_32X16, TX_16X64 -> TX_16X32), so this leaf is
20913 // read with the rect coefficient machinery, at its
20914 // own `txb_skip_ctx`/neighbour spans -- the unit is
20915 // smaller than its block, so `get_txb_ctx_general`'s
20916 // neighbour table applies, not the lone-TU 0.
20917 vartx_rect_leaf_hit(tw, th);
20918 let tu_skip_ctx =
20919 neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI);
20920 let start = row * MI * side + col * MI;
20921 read_inter_plane_rect(
20922 dec,
20923 cdfs,
20924 rect_inter_luma_set(tw, th)?,
20925 (tw, th),
20926 side,
20927 0,
20928 neighbours.around_mi_rect(tu_mi, tw, th)[0],
20929 mode_for_tx,
20930 y,
20931 tu_px,
20932 tu_py,
20933 &pred_y[start..],
20934 None,
20935 Some(tu_skip_ctx),
20936 )?
20937 };
20938 if idx == 0 {
20939 first_tx_type = tu_tx_type;
20940 }
20941 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
20942 // lane-sb128c r1: libaom's `decode_token_recon_block`
20943 // walks 64x64 "mu" chunks (`mu_blocks_wide/high =
20944 // mi_size_wide[BLOCK_64X64]`) and codes EVERY PLANE of
20945 // a chunk before the next one, so a 128x128 block
20946 // interleaves Y,U,V per quadrant -- the same order the
20947 // intra 128 path reads (lane-sb128b r3, measured
20948 // against aomdec's `EC_TRACE_COEFF`). Below 128 a block
20949 // is a single chunk and this never fires.
20950 if side > 64 {
20951 let chunk = (row / 16, col / 16);
20952 let done = idx + 1 == leaves.len()
20953 || (leaves[idx + 1].0 / 16, leaves[idx + 1].1 / 16) != chunk;
20954 if done {
20955 let (cr, cc) = chunk;
20956 // `av1_get_max_uv_txsize(BLOCK_128X128)` =
20957 // `av1_get_adjusted_tx_size(TX_64X64)` =
20958 // TX_32X32: one 32x32 chroma unit per chunk.
20959 let cu_tx = 32usize;
20960 let luma_span = cu_tx * 2;
20961 let cu_mi = (at_mi.0 + cr * 16, at_mi.1 + cc * 16);
20962 let cu_around = neighbours.around_mi(cu_mi, luma_span);
20963 let (cu_x, cu_y) = (cpx + cc * cu_tx, cpy + cr * cu_tx);
20964 let cu_scan = default_scan(cu_tx);
20965 for plane_idx in 1..3 {
20966 let (src, buf) = if plane_idx == 1 {
20967 (&pred_u, &mut *u)
20968 } else {
20969 (&pred_v, &mut *v)
20970 };
20971 let mut cu_pred = Vec::with_capacity(cu_tx * cu_tx);
20972 for rr in 0..cu_tx {
20973 let start =
20974 (cr * cu_tx + rr) * chroma_side + cc * cu_tx;
20975 cu_pred.extend_from_slice(&src[start..start + cu_tx]);
20976 }
20977 let cu_grid = read_inter_plane(
20978 dec,
20979 cdfs,
20980 chroma_set,
20981 &cu_scan,
20982 plane_idx,
20983 cu_around[plane_idx],
20984 mode_for_tx,
20985 buf,
20986 cu_x,
20987 cu_y,
20988 cu_tx,
20989 base_q_idx,
20990 &cu_pred,
20991 Some(first_tx_type),
20992 Some(3),
20993 )?
20994 .0;
20995 // Immediately, so the NEXT chunk's unit
20996 // reads this one's coefficient context.
20997 neighbours.record_mi_chroma(
20998 cu_mi, luma_span, luma_span, plane_idx, &cu_grid,
20999 );
21000 CHROMA_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
21001 mu_chroma = true;
21002 let dst = if plane_idx == 1 {
21003 &mut u_units
21004 } else {
21005 &mut v_units
21006 };
21007 for rr in 0..cu_tx {
21008 let start =
21009 (cr * cu_tx + rr) * chroma_side + cc * cu_tx;
21010 dst[start..start + cu_tx]
21011 .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]);
21012 }
21013 }
21014 }
21015 }
21016 }
21017 // `av1_get_tx_type`'s chroma lookup scales the chroma
21018 // position back to luma, so an inter block's chroma
21019 // inherits the *first* (top-left) luma unit's coded type.
21020 luma_tx_type = first_tx_type;
21021 luma_grid = vec![0i32; side * side];
21022 } else if rect_tu {
21023 // The whole-block rectangular transform unit
21024 // (`txfm_partition` said 0 at depth 0).
21025 let (grid, tx_type) = read_inter_plane_rect(
21026 dec,
21027 cdfs,
21028 rect_inter_luma_set(write_w, write_h)?,
21029 (write_w, write_h),
21030 side,
21031 0,
21032 around[0],
21033 mode_for_tx,
21034 y,
21035 px,
21036 py,
21037 &pred_y,
21038 None,
21039 None,
21040 )?;
21041 luma_tx_type = tx_type;
21042 luma_grid = embed_rect_grid(&grid, write_w, write_h, side);
21043 } else {
21044 (luma_grid, luma_tx_type) = read_inter_plane(
21045 dec,
21046 cdfs,
21047 luma_set_inter,
21048 scan_luma,
21049 0,
21050 around[0],
21051 mode_for_tx,
21052 y,
21053 px,
21054 py,
21055 side,
21056 base_q_idx,
21057 &pred_y,
21058 None,
21059 None,
21060 )?;
21061 }
21062 if side > 64 {
21063 // Already read inside the mu-chunk loop above -- at the 128
21064 // root a rect (128x64/64x128) block's chroma is per mu
21065 // chunk too, so this test comes BEFORE the `rect_tu` one.
21066 u_grid = std::mem::take(&mut u_units);
21067 v_grid = std::mem::take(&mut v_units);
21068 } else if rect_tu {
21069 // `av1_get_max_uv_txsize(bsize)`: the chroma transform of a
21070 // 2:1 strip is the strip's own rect chroma size (16x8 /
21071 // 8x16), one unit for the whole block, and it codes no
21072 // `tx_type` symbol -- it inherits the luma unit's.
21073 let (uw, uh) = (write_chroma_w, write_chroma_h);
21074 u_grid = embed_rect_grid(
21075 &read_inter_plane_rect(
21076 dec,
21077 cdfs,
21078 rect_inter_chroma_set(write_chroma_w, write_chroma_h)?,
21079 (uw, uh),
21080 chroma_side,
21081 1,
21082 around[1],
21083 mode_for_tx,
21084 u,
21085 cpx,
21086 cpy,
21087 &pred_u,
21088 Some(luma_tx_type),
21089 None,
21090 )?
21091 .0,
21092 uw,
21093 uh,
21094 chroma_side,
21095 );
21096 v_grid = embed_rect_grid(
21097 &read_inter_plane_rect(
21098 dec,
21099 cdfs,
21100 rect_inter_chroma_set(write_chroma_w, write_chroma_h)?,
21101 (uw, uh),
21102 chroma_side,
21103 2,
21104 around[2],
21105 mode_for_tx,
21106 v,
21107 cpx,
21108 cpy,
21109 &pred_v,
21110 Some(luma_tx_type),
21111 None,
21112 )?
21113 .0,
21114 uw,
21115 uh,
21116 chroma_side,
21117 );
21118 } else {
21119 u_grid = read_inter_plane(
21120 dec,
21121 cdfs,
21122 chroma_set,
21123 scan_chroma,
21124 1,
21125 around[1],
21126 mode_for_tx,
21127 u,
21128 cpx,
21129 cpy,
21130 chroma_side,
21131 base_q_idx,
21132 &pred_u,
21133 Some(luma_tx_type),
21134 None,
21135 )?
21136 .0;
21137 v_grid = read_inter_plane(
21138 dec,
21139 cdfs,
21140 chroma_set,
21141 scan_chroma,
21142 2,
21143 around[2],
21144 mode_for_tx,
21145 v,
21146 cpx,
21147 cpy,
21148 chroma_side,
21149 base_q_idx,
21150 &pred_v,
21151 Some(luma_tx_type),
21152 None,
21153 )?
21154 .0;
21155 }
21156 }
21157 } else {
21158 let ref_frame =
21159 read_single_ref(
21160 dec,
21161 cdfs,
21162 neighbours.above_ref[cmi],
21163 neighbours.above_ref1[cmi],
21164 neighbours.left_ref[rmi],
21165 neighbours.left_ref1[rmi],
21166 );
21167 ref_frame_for_lf = ref_frame;
21168 if std::env::var_os("EC_AV1_TELL").is_some() {
21169 let (mi_row, mi_col) = (rmi, cmi);
21170 eprintln!(
21171 "TELL mi_row={mi_row} mi_col={mi_col} label=post_ref_frame ref={ref_frame} tell={} range={}",
21172 dec.debug_bitpos(), dec.debug_state().0
21173 );
21174 }
21175 // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own
21176 // stacked defects (lf_level ref/mode-delta forwarding, the
21177 // switchable_interp ref-frame ctx gate, and a film-grain synthesis
21178 // gap that looked like a GOLDEN MC bug by survivor bias -- see the
21179 // ledger) are all closed; GOLDEN_FRAME decodes live via `other_refs`
21180 // below same as every other non-`LAST_FRAME` reference. lane-av1refs
21181 // widens this from GOLDEN alone to every reference `read_single_ref`
21182 // can name.
21183 let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME {
21184 (ref_y, ref_u, ref_v)
21185 } else {
21186 match other_refs[ref_frame as usize] {
21187 Some((ry, ru, rv)) => (ry, ru, rv),
21188 None => {
21189 return Err(unsupported(
21190 "a reference frame selected with no picture at this frame's own \
21191 ref_frame_idx slot for it",
21192 ));
21193 }
21194 }
21195 };
21196
21197 let (mi_row, mi_col) = (rmi, cmi);
21198 // lane-rect r2: the mv stack must be queried with the block's
21199 // REAL extent (libaom `av1_get_mv_refs` gets bw4/bh4 from
21200 // xd->width/xd->height, not a square guess) -- `write_w`/
21201 // `write_h` already name the true HORZ/VERT/HORZ_B strip
21202 // footprint (r1's plumbing), so derive bw4/bh4 from those
21203 // instead of the old `side`-square (HORZ_B-only) heuristic.
21204 let bw4 = write_w / 4;
21205 let bh4 = write_h / 4;
21206 // spec 7.10.2.8: only reached when the frame header set
21207 // `use_ref_frame_mvs` (`tpl_frame` is `Some` then, `None`
21208 // otherwise) -- `cur_offset_0` is this query block's own resolved
21209 // `ref_frame`'s distance from the current frame (spec 7.9.3),
21210 // recomputed per block since different blocks pick different refs.
21211 let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
21212 field: t.field,
21213 cur_offset_0: crate::motion_field::get_relative_dist(
21214 t.order_hint_bits,
21215 t.order_hint,
21216 t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
21217 ),
21218 allow_high_precision_mv,
21219 });
21220 let gm_table = build_gm_mv_table(
21221 global_motion,
21222 mi_row,
21223 mi_col,
21224 bw4,
21225 bh4,
21226 allow_high_precision_mv,
21227 force_integer_mv,
21228 );
21229 let stack = find_mv_stack_with_sign_bias(
21230 grid,
21231 mi_row,
21232 mi_col,
21233 bw4,
21234 bh4,
21235 ref_frame,
21236 mi_cols as usize,
21237 mi_rows as usize,
21238 sign_bias_table,
21239 &gm_table,
21240 tpl,
21241 );
21242 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
21243 let mut is_globalmv = false;
21244 // lane-interbis r1: which single-ref mode this block resolved to,
21245 // in the oracle's own numbering (NEARESTMV=13 .. NEWMV=16), for
21246 // the `EC_MODE_VAL` value ladder below.
21247 let mut dbg_mode = 16u32;
21248 let (mv, is_new_mv) = if !not_new {
21249 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
21250 // read at most two `drl_mode` bits, one per stack entry past the
21251 // first, stopping at the first `0`. The chosen index selects
21252 // which stack entry `read_mv`'s base predictor comes from
21253 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
21254 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
21255 let mut idx = 0usize;
21256 while idx < 2 && stack.entries.len() > idx + 1 {
21257 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
21258 break;
21259 }
21260 idx += 1;
21261 }
21262 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
21263 (
21264 read_mv(
21265 dec,
21266 &mut cdfs.mv_comp,
21267 &mut cdfs.mv_joint,
21268 base_mv,
21269 allow_high_precision_mv,
21270 force_integer_mv,
21271 ),
21272 true,
21273 )
21274 } else {
21275 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
21276 is_globalmv = !not_zero;
21277 let mv = if !not_zero {
21278 // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already
21279 // computed at this block's own position in `gm_table`.
21280 dbg_mode = 15;
21281 gm_table[(ref_frame - LAST_FRAME) as usize]
21282 } else {
21283 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
21284 dbg_mode = if nearest { 13 } else { 14 };
21285 if nearest {
21286 stack.nearest_mv
21287 } else {
21288 // NEARMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting
21289 // at 1): read at most two more `drl_mode` bits, one per stack
21290 // entry past the second, stopping at the first `0`.
21291 // `drl_ctx[idx]` is the context between `entries[idx]` and
21292 // `entries[idx + 1]` (`MvStack::drl_ctx`'s own doc), which is
21293 // exactly the pair this index is choosing between.
21294 let mut idx = 1usize;
21295 while idx < 3 && stack.entries.len() > idx + 1 {
21296 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
21297 break;
21298 }
21299 idx += 1;
21300 }
21301 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
21302 }
21303 };
21304 (mv, false)
21305 };
21306 if std::env::var_os("EC_TRACE_MODE").is_some() {
21307 for (i, e) in stack.entries.iter().enumerate() {
21308 eprintln!(
21309 "EC_STACK mi_row={mi_row} mi_col={mi_col} ref={ref_frame} i={i} this=({},{}) comp=(0,0) w={}",
21310 e.mv.0, e.mv.1, e.weight
21311 );
21312 }
21313 eprintln!(
21314 "EC_MODE_VAL mi_row={mi_row} mi_col={mi_col} mode={dbg_mode} ref0={ref_frame} ref1=-1 mv0=({},{}) stack={} rng={}",
21315 mv.0,
21316 mv.1,
21317 stack.entries.len(),
21318 dec.debug_state().0
21319 );
21320 }
21321 // lane-gm r2: the two libaom predicates single-ref GLOBALMV
21322 // blocks need -- `is_global_mv_block` (blockd.h:421-429, mode
21323 // GLOBAL* AND model > TRANSLATION AND min(bw,bh) >= 8px, gating
21324 // `motion_mode_eligible`/`MiInfo::is_global_mv0` below) and
21325 // `is_nontrans_global_motion` (reconinter.h:420-425, model !=
21326 // TRANSLATION -- IDENTITY counts here -- gating the interp
21327 // filter suppress below). Do NOT unify these.
21328 let gm_model = global_motion[(ref_frame - LAST_FRAME) as usize].model;
21329 let min_bw_bh4 = bw4.min(bh4);
21330 let is_global_mv_block = is_globalmv && gm_model as u8 > 1 && min_bw_bh4 >= 2;
21331 let gm_nontrans =
21332 is_globalmv && gm_model != ec_av1_syntax::WarpModel::Translation && min_bw_bh4 >= 2;
21333 if std::env::var_os("EC_AV1_TELL").is_some() {
21334 eprintln!(
21335 "TELL mi_row={mi_row} mi_col={mi_col} label=post_assign_mv tell={} range={}",
21336 dec.debug_bitpos(), dec.debug_state().0
21337 );
21338 }
21339 // lane-sb128 r4: `interintra` (spec 5.11.24; libaom
21340 // `decodemv.c` read_inter_block_mode_info ~1490-1510), placed
21341 // right after `assign_mv` and before `read_motion_mode` below --
21342 // libaom's own sequential order. `is_interintra_allowed_bsize`
21343 // (`BLOCK_8X8..=BLOCK_32X32`) is the only real gate on this
21344 // single-ref path: `is_interintra_allowed_ref` always holds here
21345 // (single ref, `ref_frame[1]` not yet `INTRA_FRAME`) and
21346 // `is_interintra_allowed_mode` always holds (every mode this
21347 // branch produces -- NEARESTMV/NEARMV/GLOBALMV/NEWMV -- is
21348 // `SINGLE_INTER_MODE_START..END` by construction).
21349 // `size_group_lookup`: BLOCK_16X16 -> 2, BLOCK_32X32 -> 3.
21350 let mut interintra_mode: Option<u8> = None;
21351 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
21352 // lane-inter4 r1: `is_interintra_allowed_bsize` is
21353 // `BLOCK_8X8..=BLOCK_32X32` in libaom's enum ORDER, which excludes
21354 // every 1:4 shape (BLOCK_8X32 = 18, BLOCK_32X8 = 19) even though
21355 // both dimensions are in range -- reading this symbol on a 1:4
21356 // strip is a symbol the reference never wrote.
21357 let interintra_shape =
21358 write_w.max(write_h) <= 32 && write_w.max(write_h) / write_w.min(write_h) <= 2;
21359 if enable_interintra_compound
21360 && !skip_mode
21361 && (side == 16 || side == 32)
21362 && interintra_shape
21363 {
21364 // lane-inter4 r3: `size_group_lookup` reads the block's
21365 // TRUE footprint -- a 16x8 strip is group 1, a 32x16 strip
21366 // group 2, not their square `side`'s 2/3.
21367 let bsize_group = size_group_wh(write_w, write_h);
21368 let interintra = dec.symbol(&mut cdfs.interintra[bsize_group]) == 1;
21369 if interintra {
21370 // lane-interintra r1 (decodemv.c 1540-1555): interintra_mode,
21371 // then -- gated on block size ALONE, never the
21372 // `enable_interintra_wedge` seq bit -- the wedge flag
21373 // (`av1_is_wedge_used(bsize)` holds for 16x16/32x32).
21374 let ii = dec.symbol(&mut cdfs.interintra_mode[bsize_group]) as u8;
21375 // lane-inter16ab r3 (same class as the compound
21376 // `compound_type` row below): the row is the block's TRUE
21377 // `BLOCK_SIZES_ALL` index -- a 16x8 / 32x16 interintra
21378 // strip is BLOCK_16X8 / BLOCK_32X16, not its square
21379 // `side`'s BLOCK_16X16 / BLOCK_32X32.
21380 let wedge_bsize = bsize_all_index(write_w, write_h)
21381 .expect("interintra shape is a BLOCK_SIZES_ALL size");
21382 let wedge = dec.symbol(&mut cdfs.wedge_interintra[wedge_bsize]) == 1;
21383 if wedge {
21384 // lane-wii r2 (spec 5.11.25): `wedge_index` is an
21385 // ADAPTING CDF symbol over the same `wedge_bsize` row;
21386 // NO sign symbol follows -- libaom fixes
21387 // INTERINTRA_WEDGE_SIGN 0 (blockd.h).
21388 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
21389 WII_HITS.with(|c| c.set(c.get() + 1));
21390 if let Some(k) = rect_wedge_slot(write_w, write_h) {
21391 RECT_WII_HITS.with(|c| {
21392 let mut a = c.get();
21393 a[k] += 1;
21394 c.set(a);
21395 });
21396 }
21397 // lane-inter16ab r5: true-footprint codebook row,
21398 // mask padded to stride `max(bw,bh) == side` -- see
21399 // the compound site's own comment.
21400 wedge_mask = Some((
21401 crate::wedge::wedge_masks()
21402 .codebook(write_w, write_h)
21403 .mask(0, wedge_index as usize),
21404 side,
21405 ));
21406 } else {
21407 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
21408 }
21409 interintra_mode = Some(ii);
21410 }
21411 }
21412 if std::env::var_os("EC_AV1_TELL").is_some() {
21413 eprintln!(
21414 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interintra tell={} range={}",
21415 dec.debug_bitpos(), dec.debug_state().0
21416 );
21417 }
21418 // lane-motionmode round 1: `read_motion_mode` (spec 5.11.24;
21419 // libaom `decodemv.c` read_inter_block_mode_info, ~1520-1528),
21420 // placed right after MV assignment and before the switchable
21421 // interp filter read below (`read_mb_interp_filter`, decodemv.c
21422 // ~1600) -- libaom's own sequential order. `motion_mode_allowed`
21423 // (`reconinter.h`) reduces, for every block this single-ref path
21424 // reaches, to "does an inter neighbour border the above row or
21425 // left column": `is_motion_variation_allowed_bsize` always holds
21426 // (`side` is never below 16px on this path), `ref_frame[1] !=
21427 // INTRA_FRAME` always holds (no interintra reader here),
21428 // `is_motion_variation_allowed_compound` always holds (this is
21429 // the single-ref branch), and `is_global_mv_block` never
21430 // triggers (this decoder's global motion is always `IDENTITY`,
21431 // so its warp `type` is never `> TRANSLATION`). A stream with
21432 // `allow_warped_motion=1` is refused right at an eligible block
21433 // rather than guessed at: `av1_findSamples`/`num_proj_ref` is
21434 // not ported, so this decoder cannot tell a real
21435 // `WARPED_CAUSAL`-eligible block (3-symbol `motion_mode_cdf`)
21436 // from an `OBMC_CAUSAL`-only one (2-symbol `obmc_cdf`) whenever
21437 // the header allows warp -- reading the wrong alphabet desyncs
21438 // the tile.
21439 // An interintra block has `ref_frame[1] == INTRA_FRAME`, which
21440 // fails libaom's `is_motion_variation_allowed_compound`: the
21441 // motion_mode symbol is NOT read (SIMPLE_TRANSLATION implied).
21442 let motion_mode_eligible = switchable_motion_mode
21443 && !skip_mode
21444 // `is_motion_variation_allowed_bsize` (blockd.h:1455):
21445 // min(bw, bh) >= 8, false for a 16x4 / 4x16 strip.
21446 && write_w.min(write_h) >= 8
21447 && interintra_mode.is_none()
21448 && (!overlappable_above(grid, mi_row, mi_col, bw4, mi_cols as usize, 1).is_empty()
21449 || !overlappable_left(grid, mi_row, mi_col, bh4, mi_rows as usize, 1)
21450 .is_empty())
21451 // libaom `motion_mode_allowed`: a GLOBALMV block whose model
21452 // is non-IDENTITY-non-TRANSLATION under free (non-integer)
21453 // mv reads no motion_mode/obmc symbol at all -- implicit
21454 // SIMPLE_TRANSLATION.
21455 && !(is_global_mv_block && !force_integer_mv);
21456 let mut obmc_selected = false;
21457 // lane-warp round 2: `Some` when motion_mode == WARPED_CAUSAL
21458 // *and* the local warp estimate is valid (`!wm_params.invalid`,
21459 // `av1_find_projection`) -- an invalid estimate falls back to
21460 // this block's own translational mv, same as any other block
21461 // (spec `allow_warp`/`reconinter.c` -- global warp is never the
21462 // fallback here since this decoder's global motion is always
21463 // IDENTITY).
21464 let mut warp_params: Option<crate::warp::WarpParams> = None;
21465 // Tracks the SYMBOL value, not projection validity: libaom's
21466 // `av1_is_interp_needed` suppresses the interp-filter read for
21467 // `motion_mode == WARPED_CAUSAL` even when the projection later
21468 // falls back to translation. Its third suppressor,
21469 // `is_nontrans_global_motion`, matches our unconditional
21470 // `is_globalmv` only because this decoder codes global motion as
21471 // IDENTITY (non-TRANSLATION) and never reads switchable filters
21472 // below 8x8 -- porting TRANSLATION global motion must add the
21473 // wmtype check here.
21474 let mut warped_selected = false;
21475 if motion_mode_eligible {
21476 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 ->
21477 // 0/1/2/3; lane-rect r2: a rect strip reads its OWN bsize row
21478 // (libaom `motion_mode_cdf[mbmi->bsize]`: BLOCK_16X32 -> 4,
21479 // BLOCK_32X16 -> 5 in our packed table) -- rect-flake-1's
21480 // strip motion_mode read diverged on the square row.
21481 // lane-inter4 r1: every rect shape this decoder can now
21482 // reach reads its OWN libaom bsize row (the packed order is
21483 // documented on `cdf::MOTION_MODE`); a wrong row is a wrong
21484 // interval narrowing, not a wrong value (class
21485 // wrong-alphabet-same-value).
21486 let bsize_idx = match (write_w, write_h) {
21487 // lane-sb128c r5: the 128 root's own rows come FIRST --
21488 // the square arm below maps 128 to row 4 (BLOCK_16X32).
21489 (64, 128) => 14,
21490 (128, 64) => 15,
21491 (128, 128) => 16,
21492 (w, h) if w == h => (w.trailing_zeros() - 3) as usize,
21493 (16, 32) => 4,
21494 (32, 16) => 5,
21495 (32, 64) => 6,
21496 (64, 32) => 7,
21497 (8, 32) => 8,
21498 (32, 8) => 9,
21499 (16, 64) => 10,
21500 (64, 16) => 11,
21501 // lane-inter4 r3: the 16x16-level rect inter leaves.
21502 (8, 16) => 12,
21503 (16, 8) => 13,
21504 _ => {
21505 return Err(unsupported(
21506 "a motion_mode symbol for a block shape with no CDF row here",
21507 ));
21508 }
21509 };
21510 // `motion_mode_allowed` reads the 3-symbol `motion_mode_cdf`
21511 // instead of the 2-symbol `obmc_cdf` exactly when
21512 // `num_proj_ref >= 1` under `allow_warped_motion`.
21513 // lane-scaledref r2 + lane-fimv r1: libaom
21514 // `motion_mode_allowed` (`blockd.h:1484`) requires BOTH
21515 // `!av1_is_scaled(block_ref_scale_factors[0])` and
21516 // `!xd->cur_frame_force_integer_mv` for WARPED_CAUSAL --
21517 // under a scaled reference (superres) OR on a frame whose
21518 // header set `force_integer_mv` (screen content) the block
21519 // reads the 2-symbol `obmc_cdf`, never the 3-symbol
21520 // `motion_mode_cdf`. Reading the wrong alphabet here narrows
21521 // the arithmetic coder by the wrong amount and predicts the
21522 // rest of the tile off a diverged state: silently wrong
21523 // pixels, not a desync error. `force_integer_mv` is the
21524 // per-frame value (spec 5.9.2: coded per frame only when
21525 // `seq_force_integer_mv == SELECT_INTEGER_MV`, threaded from
21526 // `FrameHeader::force_integer_mv`).
21527 // libaom `av1_is_scaled` is `x_scale_fp != REF_NO_SCALE ||
21528 // y_scale_fp != REF_NO_SCALE`; the y half is unreachable here
21529 // because a reference whose height differs from this frame's
21530 // true size is refused before any tile decodes ("a reference
21531 // picture whose height does not match this frame's own true
21532 // size", ~14681). Whoever lifts that refusal adds the y term.
21533 let ref_is_scaled =
21534 mc::scale_factor(py_ref.width, frame_width) != mc::REF_NO_SCALE;
21535 let proj_ok = num_proj_ref(
21536 grid,
21537 mi_row,
21538 mi_col,
21539 bw4,
21540 bh4,
21541 mi_cols as usize,
21542 mi_rows as usize,
21543 ref_frame,
21544 ) >= 1;
21545 let warp_eligible =
21546 allow_warped_motion && !ref_is_scaled && !force_integer_mv && proj_ok;
21547 if allow_warped_motion && proj_ok && ref_is_scaled {
21548 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.set(c.get() + 1));
21549 }
21550 if allow_warped_motion && proj_ok && !ref_is_scaled && force_integer_mv {
21551 FIMV_ALPHABET_HITS.with(|c| c.set(c.get() + 1));
21552 }
21553 if warp_eligible {
21554 let mode = dec.symbol(&mut cdfs.motion_mode[bsize_idx]);
21555 match mode {
21556 0 => {}
21557 1 => {
21558 obmc_selected = true;
21559 OBMC_HITS.with(|c| c.set(c.get() + 1));
21560 }
21561 _ => {
21562 warped_selected = true;
21563 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
21564 let mut samples = find_samples(
21565 grid,
21566 mi_row,
21567 mi_col,
21568 bw4,
21569 bh4,
21570 mi_cols as usize,
21571 mi_rows as usize,
21572 ref_frame,
21573 );
21574 if std::env::var_os("EC_WARP_DEBUG").is_some() {
21575 eprintln!(
21576 "EC_WARP_DEBUG findSamples mi_row={mi_row} mi_col={mi_col} bsize={side} num_proj_ref={}",
21577 samples.len()
21578 );
21579 for (i, s) in samples.iter().enumerate() {
21580 eprintln!("EC_WARP_DEBUG sample[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
21581 }
21582 }
21583 if samples.len() > 1 {
21584 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
21585 }
21586 warp_params = crate::warp::find_projection(
21587 &samples,
21588 // lane-rect r2: the block's TRUE dims -- a
21589 // 32x16 strip's model center is not a
21590 // 32x32's (aom av1_find_projection bw/bh).
21591 write_w as i32,
21592 write_h as i32,
21593 mv.1,
21594 mv.0,
21595 mi_row as i32,
21596 mi_col as i32,
21597 );
21598 if std::env::var_os("EC_WARP_DEBUG").is_some() {
21599 eprintln!(
21600 "EC_WARP_DEBUG projection mi_row={mi_row} mi_col={mi_col} num_proj_ref(final)={} mv=({},{}) params={:?}",
21601 samples.len(), mv.0, mv.1, warp_params
21602 );
21603 for (i, s) in samples.iter().enumerate() {
21604 eprintln!("EC_WARP_DEBUG sample_used[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
21605 }
21606 }
21607 }
21608 }
21609 } else {
21610 obmc_selected = dec.symbol(&mut cdfs.obmc[bsize_idx]) == 1;
21611 if obmc_selected {
21612 OBMC_HITS.with(|c| c.set(c.get() + 1));
21613 }
21614 }
21615 }
21616 // lane-gm r4: `allow_warp`'s `global_warp_allowed` branch
21617 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --
21618 // libaom's `av1_init_warp_params` runs for every inter
21619 // predictor build, not just a `WARPED_CAUSAL`-selected one. Only
21620 // reachable when `warp_params` is still `None` here: a block
21621 // that read (and got) local `WARPED_CAUSAL` above already has
21622 // `local_warp_allowed && !wm_params.invalid`, which `allow_warp`
21623 // checks FIRST and short-circuits on -- the global branch is an
21624 // `else if`, never layered on top. `is_global_mv_block` already
21625 // encodes `allow_warp`'s size bound (`min(bw4,bh4) >= 2`, i.e.
21626 // >=8px both dims, matching `av1_init_warp_params`'s
21627 // `block_height < 8 || block_width < 8` early return) and, via
21628 // `motion_mode_eligible`'s own suppression above, the
21629 // `force_integer_mv` case never reads a motion_mode symbol at
21630 // all -- checked again here directly since this branch fires
21631 // independent of `motion_mode_eligible`.
21632 let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
21633 if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid {
21634 warp_params = crate::warp::global_warp_params(gm_ref.params);
21635 if warp_params.is_some() && gm_ref.model == ec_av1_syntax::WarpModel::Affine {
21636 AFFINE_GM_HITS.with(|c| c.set(c.get() + 1));
21637 }
21638 }
21639 if std::env::var_os("EC_AV1_TELL").is_some() {
21640 eprintln!(
21641 "TELL mi_row={mi_row} mi_col={mi_col} label=post_motion_mode eligible={} tell={} range={}",
21642 motion_mode_eligible as u8, dec.debug_bitpos(), dec.debug_state().0
21643 );
21644 }
21645 // spec `get_ref_filter_type`: a neighbour's own filter only feeds
21646 // this block's switchable_interp context when that neighbour coded
21647 // the SAME reference frame this block is about to read -- a
21648 // different-ref neighbour reads as "no neighbour" ([3, 3], the
21649 // sentinel `Neighbours::new` already seeds unset slots with),
21650 // exactly like an intra neighbour. Without this gate, a GOLDEN_FRAME
21651 // block next to a LAST_FRAME one inherits that neighbour's filter
21652 // choice into its own context, corrupting the symbol it reads.
21653 // lane-av1idx r2: also match on the neighbour's SECOND reference
21654 // (`above_ref1`/`left_ref1`, real for a compound neighbour) --
21655 // see the 16x16 leaf's own comment above for the spec citation.
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 (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
21671 dec,
21672 cdfs,
21673 interp_fixed,
21674 enable_dual_filter,
21675 gm_nontrans || warped_selected,
21676 above_filter_ctx,
21677 left_filter_ctx,
21678 false,
21679 );
21680 block_filter = resolved_filter;
21681 globalmv_for_lf = is_globalmv;
21682 if std::env::var_os("EC_AV1_TELL").is_some() {
21683 eprintln!(
21684 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interp_filter tell={} range={}",
21685 dec.debug_bitpos(), dec.debug_state().0
21686 );
21687 }
21688 if std::env::var_os("EC_AV1_TRACE").is_some() {
21689 eprintln!(
21690 "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={}",
21691 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()
21692 );
21693 }
21694 // lane-rect r2: see the compound path's matching comment above --
21695 // `grid` must be stamped with the block's true bh4/bw4 span, not
21696 // a square `bw4`x`bw4` guess.
21697 for dr in 0..bh4 {
21698 for dc in 0..bw4 {
21699 grid.set(
21700 mi_row + dr,
21701 mi_col + dc,
21702 MiInfo {
21703 is_inter: true,
21704 ref_frame,
21705 // An interintra block records ref_frame[1] ==
21706 // INTRA_FRAME (0): warp-sample gathering
21707 // (libaom av1_findSamples, mvref_common.c:1155)
21708 // requires ref_frame[1] == NONE_FRAME, so such a
21709 // neighbour must not donate samples or count in
21710 // num_proj_ref.
21711 ref_frame1: interintra_mode.map(|_| 0),
21712 mv1: None,
21713 mv,
21714 is_new_mv,
21715 size: bw4,
21716 size_h: bh4,
21717 is_global_mv0: is_global_mv_block,
21718 is_global_mv1: false,
21719 },
21720 );
21721 }
21722 }
21723 mode_for_tx = 0;
21724 uv_predict_mode = DC_PRED;
21725
21726 // lane-superres r9: spec 7.11.3.3's x_scale_fp comes from LUMA
21727 // widths only (r8's derivation) and applies unchanged to the
21728 // chroma calls below (their x_q4 is already in the chroma
21729 // plane's own pixel units). `mc::predict_scaled` has no warp/OBMC
21730 // /interintra counterpart -- those three combinations are refused
21731 // by name instead of silently sampling a scaled reference wrong
21732 // (warp_params/obmc_selected/interintra_mode are all resolved by
21733 // this point, every symbol for this block already read).
21734 let luma_scale = mc::scale_factor(py_ref.width, frame_width);
21735 if luma_scale != mc::REF_NO_SCALE {
21736 // lane-scaledref r1: libaom `allow_warp`
21737 // (av1/common/reconinter.c:41) suppresses BOTH local and
21738 // global warp under a scaled reference and predicts
21739 // translationally instead -- that fallback is implemented
21740 // below, but the one real aomenc stream this round found
21741 // that reaches it (`--enable-warped-motion=1`,
21742 // `--superres-denominator=16`, seed 47) still mismatches
21743 // ffmpeg at frame 2 luma, so the case stays refused by name
21744 // until it has a green gate rather than shipping wrong
21745 // pixels behind a lifted refusal.
21746 if warp_params.is_some() {
21747 SCALED_WARP_FALLBACK_HITS.with(|c| c.set(c.get() + 1));
21748 return Err(unsupported(
21749 "warp prediction with a scaled reference (superres, unimplemented)",
21750 ));
21751 }
21752 if obmc_selected {
21753 SCALED_OBMC_HITS.with(|c| c.set(c.get() + 1));
21754 }
21755 if interintra_mode.is_some() {
21756 SCALED_INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
21757 }
21758 }
21759
21760 // lane-inter16ab r2: `is_sub8x8_inter`'s neighbour walk reads the
21761 // PREVIOUS strip's `mv`/`ref_frame`/`interp_filters`
21762 // (reconinter_template.inc:75-82); record them for the next 1:4
21763 // strip, which is the only reader.
21764 INTER_LAST_MC.with(|c| c.set(Some((ref_frame, mv, h_filter, v_filter))));
21765 let mut pred_y = vec![0u16; side * side];
21766 let mut pred_u = vec![0u16; chroma_side * chroma_side];
21767 let mut pred_v = vec![0u16; chroma_side * chroma_side];
21768 if luma_scale == mc::REF_NO_SCALE {
21769 mc::predict_with_filters_kern(
21770 &py_ref.data,
21771 py_ref.width,
21772 py_ref.true_width,
21773 py_ref.true_height,
21774 mv_to_q4(px, mv.1, true),
21775 mv_to_q4(py, mv.0, true),
21776 side,
21777 side,
21778 write_w,
21779 write_h,
21780 h_filter,
21781 v_filter,
21782 &mut pred_y,
21783 );
21784 mc::predict_with_filters_kern(
21785 &pu_ref.data,
21786 pu_ref.width,
21787 pu_ref.true_width,
21788 pu_ref.true_height,
21789 mv_to_q4(cpx, mv.1, false),
21790 mv_to_q4(cpy, mv.0, false),
21791 chroma_side,
21792 chroma_side,
21793 write_chroma_w,
21794 write_chroma_h,
21795 h_filter,
21796 v_filter,
21797 &mut pred_u,
21798 );
21799 mc::predict_with_filters_kern(
21800 &pv_ref.data,
21801 pv_ref.width,
21802 pv_ref.true_width,
21803 pv_ref.true_height,
21804 mv_to_q4(cpx, mv.1, false),
21805 mv_to_q4(cpy, mv.0, false),
21806 chroma_side,
21807 chroma_side,
21808 write_chroma_w,
21809 write_chroma_h,
21810 h_filter,
21811 v_filter,
21812 &mut pred_v,
21813 );
21814 } else {
21815 mc::predict_scaled_kern(
21816 &py_ref.data,
21817 py_ref.width,
21818 py_ref.true_width,
21819 py_ref.true_height,
21820 mv_to_q4(px, mv.1, true),
21821 mv_to_q4(py, mv.0, true),
21822 luma_scale,
21823 side,
21824 side,
21825 write_w,
21826 write_h,
21827 h_filter,
21828 v_filter,
21829 &mut pred_y,
21830 );
21831 mc::predict_scaled_kern(
21832 &pu_ref.data,
21833 pu_ref.width,
21834 pu_ref.true_width,
21835 pu_ref.true_height,
21836 mv_to_q4(cpx, mv.1, false),
21837 mv_to_q4(cpy, mv.0, false),
21838 luma_scale,
21839 chroma_side,
21840 chroma_side,
21841 write_chroma_w,
21842 write_chroma_h,
21843 h_filter,
21844 v_filter,
21845 &mut pred_u,
21846 );
21847 mc::predict_scaled_kern(
21848 &pv_ref.data,
21849 pv_ref.width,
21850 pv_ref.true_width,
21851 pv_ref.true_height,
21852 mv_to_q4(cpx, mv.1, false),
21853 mv_to_q4(cpy, mv.0, false),
21854 luma_scale,
21855 chroma_side,
21856 chroma_side,
21857 write_chroma_w,
21858 write_chroma_h,
21859 h_filter,
21860 v_filter,
21861 &mut pred_v,
21862 );
21863 }
21864
21865 // lane-scaledref r1: libaom `allow_warp` (av1/common/reconinter.c:41)
21866 // opens with `if (av1_is_scaled(sf)) return 0;` -- BOTH local
21867 // (`wm_params`) and global warp fall back to the translational
21868 // prediction above when the reference is scaled, even though the
21869 // motion_mode symbol was still read and warp_params still
21870 // resolved. Suppress the warp, keep every symbol read.
21871 if let Some(params) =
21872 warp_params.as_ref().filter(|_| luma_scale == mc::REF_NO_SCALE && warp_luma_ok)
21873 {
21874 crate::warp::warp_affine(
21875 params, &py_ref.data, py_ref.true_width as i32, py_ref.true_height as i32,
21876 py_ref.width as i32, &mut pred_y, px as i32, py as i32, side as i32,
21877 side as i32, side as i32, 0, 0,
21878 );
21879 // libaom `av1_init_warp_params` (reconinter.c): warp is
21880 // per PLANE and bails out at `block_width < 8 ||
21881 // block_height < 8`, so a plane whose own block is under
21882 // 8x8 keeps the translational prediction built above --
21883 // in 420 that is every chroma plane of a luma block below
21884 // 16x16 (lane-gmaffine r4: chroma-only mismatch of a few
21885 // levels on both 8x8-leaf motion gates).
21886 if warp_chroma_ok {
21887 crate::warp::warp_affine(
21888 params, &pu_ref.data, pu_ref.true_width as i32, pu_ref.true_height as i32,
21889 pu_ref.width as i32, &mut pred_u, cpx as i32, cpy as i32, chroma_side as i32,
21890 chroma_side as i32, chroma_side as i32, 1, 1,
21891 );
21892 crate::warp::warp_affine(
21893 params, &pv_ref.data, pv_ref.true_width as i32, pv_ref.true_height as i32,
21894 pv_ref.width as i32, &mut pred_v, cpx as i32, cpy as i32, chroma_side as i32,
21895 chroma_side as i32, chroma_side as i32, 1, 1,
21896 );
21897 }
21898 }
21899
21900 if obmc_selected {
21901 obmc_blend(
21902 grid,
21903 neighbours,
21904 mi_row,
21905 mi_col,
21906 bw4,
21907 bh4,
21908 mi_rows as usize,
21909 mi_cols as usize,
21910 side,
21911 write_w,
21912 write_h,
21913 chroma_side,
21914 px,
21915 py,
21916 cpx,
21917 cpy,
21918 ref_y,
21919 ref_u,
21920 ref_v,
21921 other_refs,
21922 interp_fixed,
21923 frame_width,
21924 &mut pred_y,
21925 &mut pred_u,
21926 &mut pred_v,
21927 )?;
21928 }
21929
21930 // Mutually exclusive with warp/OBMC (motion_mode is not read for
21931 // an interintra block): blend the intra predictor over the MC
21932 // result, all planes (reconinter.c av1_build_interintra_predictor
21933 // plane loop).
21934 if let Some(ii) = interintra_mode {
21935 if write_w != write_h {
21936 INTERINTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
21937 }
21938 interintra_blend(y, px, py, write_w, write_h, side, ii, wedge_mask, &mut pred_y);
21939 interintra_blend(
21940 u, cpx, cpy, write_chroma_w, write_chroma_h, chroma_side, ii, wedge_mask,
21941 &mut pred_u,
21942 );
21943 interintra_blend(
21944 v, cpx, cpy, write_chroma_w, write_chroma_h, chroma_side, ii, wedge_mask,
21945 &mut pred_v,
21946 );
21947 }
21948
21949 // lane-inter16ab r2: libaom `build_inter_predictors_sub8x8`
21950 // (reconinter_template.inc:87-160). A 4:2:0 chroma block under a
21951 // 16x4 (4x16) luma pair covers TWO luma blocks, so it is built in
21952 // `b4_w x b4_h` = 8x2 (2x8) pieces, each from its own strip's
21953 // mv/ref/filters. The bottom (right) piece is this strip's own mv
21954 // over its own rows, which the whole-block prediction above
21955 // already wrote there (MC is position-invariant for a fixed mv),
21956 // so only the FIRST piece has to be rebuilt -- and only when
21957 // `is_sub8x8_inter` holds, i.e. the previous strip was itself a
21958 // single-reference inter block (`prev`), else libaom falls
21959 // through to the ordinary whole-block predictor.
21960 if let Some(s) = strip_chroma.filter(|s| s.has_chroma)
21961 && let Some((prev_ref, prev_mv, prev_h, prev_v)) = s.prev
21962 && luma_scale == mc::REF_NO_SCALE
21963 {
21964 let (piece_w, piece_h) = if s.horz { (8usize, 2usize) } else { (2usize, 8usize) };
21965 let (_, prev_u, prev_v_plane) = ref_planes(prev_ref, ref_y, ref_u, ref_v, other_refs)?;
21966 for (src, dst) in [(prev_u, &mut pred_u), (prev_v_plane, &mut pred_v)] {
21967 let mut piece = vec![0u16; piece_w * piece_h];
21968 mc::predict_with_filters(
21969 &src.data,
21970 src.width,
21971 src.true_width,
21972 src.true_height,
21973 mv_to_q4(cpx, prev_mv.1, false),
21974 mv_to_q4(cpy, prev_mv.0, false),
21975 piece_w,
21976 piece_h,
21977 prev_h,
21978 prev_v,
21979 &mut piece,
21980 );
21981 for row in 0..piece_h {
21982 dst[row * chroma_side..row * chroma_side + piece_w]
21983 .copy_from_slice(&piece[row * piece_w..(row + 1) * piece_w]);
21984 }
21985 }
21986 INTER16_SUB8_PIECE_HITS.with(|c| c.set(c.get() + 1));
21987 }
21988
21989 // lane-inter4 r2: a rectangular strip's transform tree starts from
21990 // its own rect `max_txsize_rect_lookup` entry, not a square one.
21991 let rect_tu = (write_w, write_h) != (side, side);
21992 vartx_leaves = if rect_tu {
21993 read_block_tx_size_rect(
21994 dec,
21995 cdfs,
21996 neighbours,
21997 at_mi,
21998 (write_w, write_h),
21999 (mi_cols as usize, mi_rows as usize),
22000 skip,
22001 )?
22002 } else {
22003 read_block_tx_size(
22004 dec,
22005 cdfs,
22006 neighbours,
22007 at_mi,
22008 side,
22009 (mi_cols as usize, mi_rows as usize),
22010 true,
22011 skip,
22012 )?
22013 .1
22014 };
22015 if skip {
22016 y.reconstruct_mc_rect(
22017 px,
22018 py,
22019 side,
22020 write_w,
22021 write_h,
22022 &pred_y,
22023 &vec![0i32; side * side],
22024 );
22025 if has_chroma {
22026 u.reconstruct_mc_rect(
22027 cpx,
22028 cpy,
22029 chroma_side,
22030 write_chroma_w,
22031 write_chroma_h,
22032 &pred_u,
22033 &vec![0i32; chroma_side * chroma_side],
22034 );
22035 v.reconstruct_mc_rect(
22036 cpx,
22037 cpy,
22038 chroma_side,
22039 write_chroma_w,
22040 write_chroma_h,
22041 &pred_v,
22042 &vec![0i32; chroma_side * chroma_side],
22043 );
22044 }
22045 luma_grid = vec![0i32; side * side];
22046 u_grid = vec![0i32; chroma_side * chroma_side];
22047 v_grid = vec![0i32; chroma_side * chroma_side];
22048 } else {
22049 // lane-inter4 r2: a rect strip's coefficient context spans its
22050 // OWN width above and height left -- reading `side` cells both
22051 // ways indexes past the tile's last mi row for a bottom strip.
22052 let around = if rect_tu {
22053 neighbours.around_mi_rect(at_mi, write_w, write_h)
22054 } else {
22055 neighbours.around_mi(at, side)
22056 };
22057 // lane-inter16ab r2: the pair's chroma transform sits at the
22058 // EVEN strip's mi origin and spans both strips, so its
22059 // above/left coefficient context is the pair's, not this
22060 // strip's row.
22061 let around_c = match strip_chroma {
22062 Some(s) if s.has_chroma => neighbours.around_mi_rect(
22063 s.pair_mi,
22064 if s.horz { 16 } else { 8 },
22065 if s.horz { 8 } else { 16 },
22066 ),
22067 _ => around,
22068 };
22069 let luma_tx_type;
22070 // lane-sb128c r1: a 128x128 inter block's four chroma units
22071 // are read INSIDE the luma leaf loop (one per 64x64 mu chunk);
22072 // these collect them for the block-level neighbour write-back.
22073 let mut u_units = vec![0i32; chroma_side * chroma_side];
22074 let mut v_units = vec![0i32; chroma_side * chroma_side];
22075 if let Some(leaves) = vartx_leaves.clone() {
22076 // spec 5.11.17's transform tree, leaf by leaf in the order
22077 // `read_var_tx_size` coded it: each unit reads its own
22078 // coefficients against the neighbour magnitudes the
22079 // earlier units already wrote, and reconstructs over its
22080 // own slice of the block's motion-compensated predictor.
22081 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
22082 let mut first_tx_type = TxType::DctDct;
22083 for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() {
22084 let tu_mi = (at_mi.0 + row, at_mi.1 + col);
22085 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
22086 let (tu_grid, tu_tx_type) = if tw == th {
22087 let tx_px = tw;
22088 let mut tu_pred = Vec::with_capacity(tx_px * tx_px);
22089 for rr in 0..tx_px {
22090 let start = (row * MI + rr) * side + col * MI;
22091 tu_pred.extend_from_slice(&pred_y[start..start + tx_px]);
22092 }
22093 let scan = default_scan(tx_px.min(32));
22094 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI);
22095 read_inter_plane(
22096 dec,
22097 cdfs,
22098 inter_txbset_for(tx_px, reduced),
22099 &scan,
22100 0,
22101 neighbours.around_mi(tu_mi, tx_px)[0],
22102 mode_for_tx,
22103 y,
22104 tu_px,
22105 tu_py,
22106 tx_px,
22107 base_q_idx,
22108 &tu_pred,
22109 None,
22110 Some(tu_skip_ctx),
22111 )?
22112 } else {
22113 // lane-r14 r3: a 1:4 strip's `sub_tx_size_map`
22114 // sub-transform is RECTANGULAR (TX_64X16 ->
22115 // TX_32X16, TX_16X64 -> TX_16X32), so this leaf is
22116 // read with the rect coefficient machinery, at its
22117 // own `txb_skip_ctx`/neighbour spans -- the unit is
22118 // smaller than its block, so `get_txb_ctx_general`'s
22119 // neighbour table applies, not the lone-TU 0.
22120 vartx_rect_leaf_hit(tw, th);
22121 let tu_skip_ctx =
22122 neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI);
22123 let start = row * MI * side + col * MI;
22124 read_inter_plane_rect(
22125 dec,
22126 cdfs,
22127 rect_inter_luma_set(tw, th)?,
22128 (tw, th),
22129 side,
22130 0,
22131 neighbours.around_mi_rect(tu_mi, tw, th)[0],
22132 mode_for_tx,
22133 y,
22134 tu_px,
22135 tu_py,
22136 &pred_y[start..],
22137 None,
22138 Some(tu_skip_ctx),
22139 )?
22140 };
22141 if idx == 0 {
22142 first_tx_type = tu_tx_type;
22143 }
22144 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
22145 // lane-sb128c r1: libaom's `decode_token_recon_block`
22146 // walks 64x64 "mu" chunks (`mu_blocks_wide/high =
22147 // mi_size_wide[BLOCK_64X64]`) and codes EVERY PLANE of
22148 // a chunk before the next one, so a 128x128 block
22149 // interleaves Y,U,V per quadrant -- the same order the
22150 // intra 128 path reads (lane-sb128b r3, measured
22151 // against aomdec's `EC_TRACE_COEFF`). Below 128 a block
22152 // is a single chunk and this never fires.
22153 if side > 64 {
22154 let chunk = (row / 16, col / 16);
22155 let done = idx + 1 == leaves.len()
22156 || (leaves[idx + 1].0 / 16, leaves[idx + 1].1 / 16) != chunk;
22157 if done {
22158 let (cr, cc) = chunk;
22159 // `av1_get_max_uv_txsize(BLOCK_128X128)` =
22160 // `av1_get_adjusted_tx_size(TX_64X64)` =
22161 // TX_32X32: one 32x32 chroma unit per chunk.
22162 let cu_tx = 32usize;
22163 let luma_span = cu_tx * 2;
22164 let cu_mi = (at_mi.0 + cr * 16, at_mi.1 + cc * 16);
22165 let cu_around = neighbours.around_mi(cu_mi, luma_span);
22166 let (cu_x, cu_y) = (cpx + cc * cu_tx, cpy + cr * cu_tx);
22167 let cu_scan = default_scan(cu_tx);
22168 for plane_idx in 1..3 {
22169 let (src, buf) = if plane_idx == 1 {
22170 (&pred_u, &mut *u)
22171 } else {
22172 (&pred_v, &mut *v)
22173 };
22174 let mut cu_pred = Vec::with_capacity(cu_tx * cu_tx);
22175 for rr in 0..cu_tx {
22176 let start =
22177 (cr * cu_tx + rr) * chroma_side + cc * cu_tx;
22178 cu_pred.extend_from_slice(&src[start..start + cu_tx]);
22179 }
22180 let cu_grid = read_inter_plane(
22181 dec,
22182 cdfs,
22183 chroma_set,
22184 &cu_scan,
22185 plane_idx,
22186 cu_around[plane_idx],
22187 mode_for_tx,
22188 buf,
22189 cu_x,
22190 cu_y,
22191 cu_tx,
22192 base_q_idx,
22193 &cu_pred,
22194 Some(first_tx_type),
22195 Some(3),
22196 )?
22197 .0;
22198 // Immediately, so the NEXT chunk's unit
22199 // reads this one's coefficient context.
22200 neighbours.record_mi_chroma(
22201 cu_mi, luma_span, luma_span, plane_idx, &cu_grid,
22202 );
22203 CHROMA_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
22204 mu_chroma = true;
22205 let dst = if plane_idx == 1 {
22206 &mut u_units
22207 } else {
22208 &mut v_units
22209 };
22210 for rr in 0..cu_tx {
22211 let start =
22212 (cr * cu_tx + rr) * chroma_side + cc * cu_tx;
22213 dst[start..start + cu_tx]
22214 .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]);
22215 }
22216 }
22217 }
22218 }
22219 }
22220 // `av1_get_tx_type`'s chroma lookup scales the chroma
22221 // position back to luma, so an inter block's chroma
22222 // inherits the *first* (top-left) luma unit's coded type.
22223 luma_tx_type = first_tx_type;
22224 luma_grid = vec![0i32; side * side];
22225 } else if rect_tu {
22226 // The whole-block rectangular transform unit
22227 // (`txfm_partition` said 0 at depth 0).
22228 let (grid, tx_type) = read_inter_plane_rect(
22229 dec,
22230 cdfs,
22231 rect_inter_luma_set(write_w, write_h)?,
22232 (write_w, write_h),
22233 side,
22234 0,
22235 around[0],
22236 mode_for_tx,
22237 y,
22238 px,
22239 py,
22240 &pred_y,
22241 None,
22242 None,
22243 )?;
22244 luma_tx_type = tx_type;
22245 luma_grid = embed_rect_grid(&grid, write_w, write_h, side);
22246 } else {
22247 (luma_grid, luma_tx_type) = read_inter_plane(
22248 dec,
22249 cdfs,
22250 luma_set_inter,
22251 scan_luma,
22252 0,
22253 around[0],
22254 mode_for_tx,
22255 y,
22256 px,
22257 py,
22258 side,
22259 base_q_idx,
22260 &pred_y,
22261 None,
22262 None,
22263 )?;
22264 }
22265 if !has_chroma {
22266 // `is_chroma_reference` is false for this strip: libaom's
22267 // plane loop (decodeframe.c
22268 // `predict_and_reconstruct_intra_block`/
22269 // `reconstruct_inter_block`'s `for (plane...)` guarded by
22270 // `xd->is_chroma_ref`) codes NO chroma transform here, so
22271 // neither symbol nor context exists.
22272 u_grid = vec![0i32; chroma_side * chroma_side];
22273 v_grid = vec![0i32; chroma_side * chroma_side];
22274 } else if side > 64 {
22275 // Already read inside the mu-chunk loop above -- at the 128
22276 // root a rect (128x64/64x128) block's chroma is per mu
22277 // chunk too, so this test comes BEFORE the `rect_tu` one.
22278 u_grid = std::mem::take(&mut u_units);
22279 v_grid = std::mem::take(&mut v_units);
22280 } else if rect_tu {
22281 // `av1_get_max_uv_txsize(bsize)`: the chroma transform of a
22282 // 2:1 strip is the strip's own rect chroma size (16x8 /
22283 // 8x16), one unit for the whole block, and it codes no
22284 // `tx_type` symbol -- it inherits the luma unit's.
22285 let (uw, uh) = (write_chroma_w, write_chroma_h);
22286 u_grid = embed_rect_grid(
22287 &read_inter_plane_rect(
22288 dec,
22289 cdfs,
22290 rect_inter_chroma_set(write_chroma_w, write_chroma_h)?,
22291 (uw, uh),
22292 chroma_side,
22293 1,
22294 around_c[1],
22295 mode_for_tx,
22296 u,
22297 cpx,
22298 cpy,
22299 &pred_u,
22300 Some(luma_tx_type),
22301 None,
22302 )?
22303 .0,
22304 uw,
22305 uh,
22306 chroma_side,
22307 );
22308 v_grid = embed_rect_grid(
22309 &read_inter_plane_rect(
22310 dec,
22311 cdfs,
22312 rect_inter_chroma_set(write_chroma_w, write_chroma_h)?,
22313 (uw, uh),
22314 chroma_side,
22315 2,
22316 around_c[2],
22317 mode_for_tx,
22318 v,
22319 cpx,
22320 cpy,
22321 &pred_v,
22322 Some(luma_tx_type),
22323 None,
22324 )?
22325 .0,
22326 uw,
22327 uh,
22328 chroma_side,
22329 );
22330 } else {
22331 u_grid = read_inter_plane(
22332 dec,
22333 cdfs,
22334 chroma_set,
22335 scan_chroma,
22336 1,
22337 around[1],
22338 mode_for_tx,
22339 u,
22340 cpx,
22341 cpy,
22342 chroma_side,
22343 base_q_idx,
22344 &pred_u,
22345 Some(luma_tx_type),
22346 None,
22347 )?
22348 .0;
22349 v_grid = read_inter_plane(
22350 dec,
22351 cdfs,
22352 chroma_set,
22353 scan_chroma,
22354 2,
22355 around[2],
22356 mode_for_tx,
22357 v,
22358 cpx,
22359 cpy,
22360 chroma_side,
22361 base_q_idx,
22362 &pred_v,
22363 Some(luma_tx_type),
22364 None,
22365 )?
22366 .0;
22367 }
22368 }
22369 }
22370 } else {
22371 // lane-partitions r1: intra prediction (`PlaneBuf::reconstruct`) has
22372 // no rectangular counterpart -- an intra-coded HORZ/VERT strip needs
22373 // its own true-width/height edge/predict math, unlike the inter
22374 // skip path above (which only needed a clipped write of an
22375 // already-square-predicted buffer). Named refusal instead of a
22376 // silently wrong square-shaped intra prediction.
22377 // lane-inter16ab r2: `decode_intra_rect_in_inter` has no chroma-pair
22378 // path (it predicts and codes chroma at the strip's own halved
22379 // footprint), so an INTRA 16x4 / 4x16 strip inside a 1:4 partition is
22380 // refused by name rather than decoded with a 8x2 chroma transform
22381 // libaom never coded.
22382 // lane-intra16x4 r1: the strip DECODES through the key frame's own
22383 // per-strip body, [`decode_rect4_16_strip`].
22384 // lane-sub8x4 r3: pixel-proven, so `EC_INTRA16X4_DECODE` is gone. r1
22385 // and r2 found no witness because every firing film frame ALSO carried
22386 // a sub-8x8 intra block, which refused until r2 lifted it; on this tip
22387 // the first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode
22388 // all 33 frames pixel-exact while this arm fires 31x 16x4 + 17x 4x16
22389 // (23 of them chroma-paired). Pinned as
22390 // `fixtures/reelb_rect64_intra16x4_witness.obu` -- MEASURED WRONG, see
22391 // the lane-wit16x4 note below.
22392 // The refusal below is NARROWED, not deleted: it still stands for a
22393 // 16x4/4x16 strip with no chroma-pair record and for every other
22394 // sub-8 shape.
22395 //
22396 // lane-wit16x4 r1: RE-WIDENED to the whole shape, because r3's witness
22397 // was a PHANTOM (class `counter-from-refused-stream`): the pinned
22398 // fixture was measured while decode-order frame 33 was desynced, and
22399 // on the merged tip (lane-frame36 r2 fixed that desync) the very same
22400 // fixture decodes all 33 frames pixel-exact with `intra16x4_in_inter`
22401 // 16x4=0 4x16=0 chroma_ref=0 -- the 31/17/23 were counted out of a
22402 // wrong decode. Re-measured this round: NO stream anywhere decodes
22403 // exactly while this arm fires. Two 2 s 10-bit film cuts (3840x1608 at
22404 // 0 s: OK, 48 frames exact, 0 hits; at 300 s: 138/559 hits but frames
22405 // 1 and 2 mismatch ffmpeg by 14105680 / 12470780 bytes), four 1920x792
22406 // 128-SB cuts (hits only inside frames that refuse or are never shown
22407 // -- the 6300 s cut's key frame is exact with 0 hits and its no-show
22408 // frame 1 carries 169/445 with no display frame reachable before the
22409 // 128x64-intra-on-inter refusal), and the aomenc gate
22410 // `a_real_aomenc_inter_sequence_with_intra_16x4_strips_in_1to4_partitions_decodes_pixel_exact`
22411 // (run `--include-ignored` on this tip: FAILED, 0 pixel-exact attempts
22412 // carrying the strip, per-arm [0, 0, 0]). A lifted refusal with no
22413 // witness is a capability claim (class `refusal-lifted-without-a-gate`),
22414 // so the decode path stays behind `EC_INTRA16X4_DECODE` for the round
22415 // that finds a witness.
22416 let strip16 = strip_chroma
22417 .filter(|_| write_w.min(write_h) == 4 && write_w.max(write_h) == 16)
22418 .filter(|_| std::env::var_os("EC_INTRA16X4_DECODE").is_some())
22419 .map(|s| (s.horz, s.has_chroma));
22420 if write_w.min(write_h) < 8 && strip16.is_none() {
22421 if std::env::var_os("EC_INTRA16X4").is_some() {
22422 let (idx, hc, prev_inter) = match strip_chroma {
22423 Some(s) => (
22424 if s.horz { rmi - s.pair_mi.0 } else { cmi - s.pair_mi.1 },
22425 s.has_chroma,
22426 s.prev.is_some(),
22427 ),
22428 None => (9, true, false),
22429 };
22430 eprintln!(
22431 "EC_INTRA16X4 w={write_w} h={write_h} pair_parity={idx} has_chroma={hc} prev_single_inter={prev_inter} skip={skip} mi={rmi},{cmi} tx_select={} scr={}",
22432 TX_SELECT_INTER.with(std::cell::Cell::get),
22433 allow_screen_content_tools,
22434 );
22435 }
22436 return Err(unsupported(
22437 "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)",
22438 ));
22439 }
22440 if write_w != side || write_h != side {
22441 // lane-intrarect r1: the strip decodes through its own rect
22442 // machinery ([`decode_intra_rect_in_inter`] -> the key-frame
22443 // paths' [`decode_rect_split`]) instead of refusing. That call
22444 // already writes everything the shared tail below would for a
22445 // square block EXCEPT the inter-side bands and the mi map, so
22446 // this arm returns rather than falling through (a second
22447 // `record_rect`/`fill_lf_grid_rect` at block granularity would
22448 // overwrite the per-transform-unit records it just made).
22449 decode_intra_rect_in_inter(
22450 dec,
22451 cdfs,
22452 neighbours,
22453 at,
22454 write_w,
22455 write_h,
22456 skip,
22457 allow_screen_content_tools,
22458 strip16,
22459 y,
22460 u,
22461 v,
22462 base_q_idx,
22463 )?;
22464 // merge b51719f+lane-intrarect: `at` is in MI units on this path
22465 // (lane-inter4), so the strip's mi origin is `at` itself -- the
22466 // lane's `r * SUB_MI` re-derivation would snap a sub-SUB strip to
22467 // its enclosing 16-px cell.
22468 let (mi_r0, mi_c0) = (rmi, cmi);
22469 for dr in 0..write_h / MI {
22470 for dc in 0..write_w / MI {
22471 grid.set(
22472 mi_r0 + dr,
22473 mi_c0 + dc,
22474 MiInfo {
22475 is_inter: false,
22476 ref_frame: -1,
22477 ref_frame1: None,
22478 mv1: None,
22479 mv: (0, 0),
22480 is_new_mv: false,
22481 size: write_w / MI,
22482 size_h: write_h / MI,
22483 is_global_mv0: false,
22484 is_global_mv1: false,
22485 },
22486 );
22487 }
22488 }
22489 neighbours.record_inter_rect_mi(
22490 at,
22491 write_w / MI,
22492 write_h / MI,
22493 skip,
22494 false,
22495 0,
22496 [3, 3],
22497 skip_mode,
22498 );
22499 return Ok(());
22500 }
22501 let mode = dec.symbol(&mut cdfs.y_mode[size_group_wh(write_w, write_h)]);
22502 if std::env::var_os("EC_IIS").is_some() {
22503 eprintln!(
22504 "TRACE iis px={px} py={py} side={side} w={write_w} h={write_h} sg={} mode={mode} skip={skip}",
22505 size_group_wh(write_w, write_h)
22506 );
22507 }
22508 if mode >= 13 {
22509 return Err(unsupported(
22510 "an intra mode this decoder does not code (round 2)",
22511 ));
22512 }
22513 // lane-angleinter r1: `read_intra_angle_info` (libaom `decodemv.c`,
22514 // inside `read_intra_block_mode_info`) -- an intra block in an inter
22515 // frame reads `angle_delta_y` off the same
22516 // `angle_delta_cdf[mode - V_PRED]` row a key-frame block does, and
22517 // the delta feeds the directional predictor (and the edge
22518 // filter/upsample decision derived from the delta'd angle) unchanged.
22519 // The symbol was read and then refused before this round even though
22520 // aomenc enables `--enable-angle-delta` by default.
22521 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
22522 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
22523 } else {
22524 0
22525 };
22526 if angle_delta_y != 0 {
22527 INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.set(c.get() + 1));
22528 }
22529 // The delta'd angle decides whether the intra edge filter runs at
22530 // all, so this block needs the same luma edge-filter-type neighbour
22531 // check a key-frame block does (`get_intra_edge_filter_type`, spec
22532 // 7.11.2) -- this arm passed a hardcoded `false` while every
22533 // directional intra-in-inter block was refused above.
22534 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
22535 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
22536 // lane-sbrect10 r1 (class wrong-alphabet-same-value, second instance
22537 // after lane-sbpart r3's rect strips): `is_cfl_allowed` (libaom
22538 // `blockd.h` -- `block_size_wide[bsize] <= 32 && block_size_high[bsize]
22539 // <= 32`, spec 5.11.5) caps CFL at 32x32, so a 64x64 intra block inside
22540 // an INTER frame reads the 13-symbol `uv_mode_no_cfl` alphabet. Reading
22541 // the 14-symbol CFL one gave the same DC_PRED VALUE but narrowed the
22542 // arithmetic coder by the wrong interval, desyncing the tile from this
22543 // block on.
22544 let cfl_allowed = write_w.max(write_h) <= 32;
22545 if !cfl_allowed {
22546 NOCFL_UV_MODE_HITS.with(|c| c.set(c.get() + 1));
22547 }
22548 let uv_mode = if cfl_allowed {
22549 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
22550 } else {
22551 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
22552 };
22553 if (9..=12).contains(&uv_mode) {
22554 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
22555 }
22556 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
22557 Some(read_cfl_alphas(dec, cdfs))
22558 } else {
22559 None
22560 };
22561 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for
22562 // the angle-delta question, same as [`read_intra_mode`]'s own copy
22563 // -- `uv_mode` (13) already falls outside `V_PRED..=D67_PRED` so the
22564 // `else` branch below is exact for it either way.
22565 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
22566 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
22567 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
22568 } else {
22569 0
22570 };
22571 if angle_delta_uv != 0 {
22572 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
22573 INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|c| c.set(c.get() + 1));
22574 }
22575 uv_predict_mode = if uv_mode == UV_CFL_PRED {
22576 DC_PRED
22577 } else {
22578 uv_mode
22579 };
22580 // lane-chroma r4: same chroma edge-filter-strength neighbour check
22581 // as [`read_intra_mode`]/[`read_intra_mode_rect`] -- the CHROMA
22582 // neighbour's own `uv_mode`, not the luma one.
22583 let smooth_neighbor_uv =
22584 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
22585 // `read_palette_mode_info` (decodemv.c:567, called from
22586 // `read_intra_block_mode_info` right after `xd->cfl.store_y`, same
22587 // gating and same corner-cut as `read_intra_mode`'s own copy above
22588 // -- `palette_mode_ctx`/`palette_uv_mode_ctx` hardcoded 0, provably
22589 // safe since a nonzero neighbour `palette_size` would already have
22590 // refused the decode that produced it.
22591 // lane-inter16ab r4 (class sweep): `av1_get_palette_bsize_ctx` is keyed
22592 // by the block's TRUE footprint -- a rect strip's row is not its
22593 // enclosing square's, and a 16x4 strip (64 pixels) reads no palette
22594 // symbol at all.
22595 if allow_screen_content_tools
22596 && let Some(bsize_ctx) = palette_bsize_ctx_wh(write_w, write_h)
22597 {
22598 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][0]) != 0 {
22599 return Err(unsupported(
22600 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
22601 ));
22602 }
22603 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
22604 return Err(unsupported(
22605 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
22606 ));
22607 }
22608 }
22609 // lane-fiinter r1: `read_filter_intra_mode_info` (libaom `decodemv.c`,
22610 // the tail of `read_intra_block_mode_info`) -- an intra block inside
22611 // an INTER frame reads `use_filter_intra` in exactly the same place a
22612 // key-frame block does, right after the palette syntax. Nothing read
22613 // it here before this round, and aomenc enables filter intra by
22614 // default, so every inter frame carrying one desynced at this symbol.
22615 // `av1_filter_intra_allowed`'s `palette_size[0] == 0` term is implied:
22616 // a real palette-Y block already returned above.
22617 let mut filter_intra = None;
22618 if mode == DC_PRED
22619 && ENABLE_FILTER_INTRA_INTER.with(std::cell::Cell::get)
22620 // lane-inter16ab r4 (class sweep): `cdf::FILTER_INTRA`'s row is the
22621 // true `BLOCK_SIZES_ALL` class of this strip, not its square side's.
22622 && let Some(class) = filter_intra_size_class_rect(write_w, write_h)
22623 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
22624 {
22625 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
22626 INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
22627 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
22628 }
22629 mode_for_tx = mode;
22630 block_filter = [3, 3];
22631 ref_frame_for_lf = 0;
22632 globalmv_for_lf = false;
22633 let (mi_row, mi_col) = (rmi, cmi);
22634 for dr in 0..side / 4 {
22635 for dc in 0..side / 4 {
22636 grid.set(
22637 mi_row + dr,
22638 mi_col + dc,
22639 MiInfo {
22640 is_inter: false,
22641 ref_frame: -1,
22642 ref_frame1: None,
22643 mv1: None,
22644 mv: (0, 0),
22645 is_new_mv: false,
22646 size: side / 4,
22647 size_h: side / 4,
22648 is_global_mv0: false,
22649 is_global_mv1: false,
22650 },
22651 );
22652 }
22653 }
22654
22655 // lane-intrainter r1: an intra block in an inter frame reads the same
22656 // `tx_depth` symbol a key-frame block does, and when it splits, the
22657 // block codes one intra prediction + one coefficient set PER
22658 // transform unit (`decode_block`'s multi-TU branch), not one for the
22659 // whole block. The leaf list rides the existing `vartx_leaves` slot,
22660 // whose tail already does the split-block neighbour write-back
22661 // (`record_split_luma`) and the per-TU deblock edges.
22662 vartx_leaves = read_block_tx_size(
22663 dec,
22664 cdfs,
22665 neighbours,
22666 at_mi,
22667 side,
22668 (mi_cols as usize, mi_rows as usize),
22669 false,
22670 skip,
22671 )?
22672 .1;
22673 let reach = Reach::of(side, px, py, y.width, y.height);
22674 let split_luma = vartx_leaves.is_some();
22675 // lane-sb128c r3: a 128x128 INTRA block inside an inter frame codes
22676 // its chroma per 64x64 mu chunk, exactly as the inter half above --
22677 // `decode_token_recon_block` walks `mu_blocks_wide/high` and codes
22678 // every plane of a chunk before the next chunk's luma. These collect
22679 // the four TX_32X32 units per plane for the block-level write-back.
22680 let mut u_units = vec![0i32; chroma_side * chroma_side];
22681 let mut v_units = vec![0i32; chroma_side * chroma_side];
22682 if let Some(leaves) = vartx_leaves.clone() {
22683 let reduced = REDUCED_TX_SET_INTER.with(std::cell::Cell::get);
22684 for (idx, &(row, col, tx_px, _)) in leaves.iter().enumerate() {
22685 let tu_mi = (at_mi.0 + row, at_mi.1 + col);
22686 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
22687 // A transform unit inside a block is not a block at that
22688 // position (class from lane-palette2 r12): top-right /
22689 // bottom-left availability is the block's, narrowed by the
22690 // unit's own offset inside it.
22691 let tu_reach = Reach::of_tu(side, side, col * MI, row * MI, tx_px, tx_px, reach);
22692 let tu_grid = if skip {
22693 y.reconstruct(
22694 tu_px,
22695 tu_py,
22696 tx_px,
22697 mode,
22698 angle_delta_y,
22699 tu_reach,
22700 &vec![0i32; tx_px * tx_px],
22701 None,
22702 filter_intra,
22703 smooth_neighbor,
22704 );
22705 vec![0i32; tx_px * tx_px]
22706 } else {
22707 // The unit's bsize is smaller than the block it sits in,
22708 // so `txb_skip_ctx` is the neighbour-magnitude table, not
22709 // the lone-TU 0 (`get_txb_ctx_general`).
22710 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_px / MI);
22711 read_plane(
22712 dec,
22713 cdfs,
22714 txbset_for(tx_px, reduced),
22715 // lane-sb128c r5: a TX_64X64 unit codes only its
22716 // top-left 32x32 of frequencies (spec 5.11.40), so
22717 // the scan and `tx_side` are the CODED corner while
22718 // `side` stays the transform's true 64.
22719 &default_scan(tx_px.min(32)),
22720 0,
22721 neighbours.around_mi(tu_mi, tx_px)[0],
22722 mode,
22723 mode,
22724 angle_delta_y,
22725 tu_reach,
22726 y,
22727 tu_px,
22728 tu_py,
22729 tx_px,
22730 tx_px.min(32),
22731 base_q_idx,
22732 None,
22733 filter_intra,
22734 Some(tu_skip_ctx),
22735 smooth_neighbor,
22736 )?
22737 };
22738 neighbours.record_mi_luma(tu_mi, tx_px, &tu_grid);
22739 if side > 64 {
22740 let chunk = (row / 16, col / 16);
22741 let done = idx + 1 == leaves.len()
22742 || (leaves[idx + 1].0 / 16, leaves[idx + 1].1 / 16) != chunk;
22743 if !done {
22744 continue;
22745 }
22746 let (cr, cc) = chunk;
22747 // `av1_get_max_uv_txsize(BLOCK_128X128)` =
22748 // `av1_get_adjusted_tx_size(TX_64X64)` = TX_32X32.
22749 let cu_tx = 32usize;
22750 let luma_span = cu_tx * 2;
22751 let cu_mi = (at_mi.0 + cr * 16, at_mi.1 + cc * 16);
22752 let cu_around = neighbours.around_mi(cu_mi, luma_span);
22753 let (cu_x, cu_y) = (cpx + cc * cu_tx, cpy + cr * cu_tx);
22754 let cu_reach = crate::decode::tu_reach(
22755 side, side,
22756 cc * luma_span, cr * luma_span, luma_span,
22757 reach, px, py, y.width, y.height,
22758 );
22759 let cu_scan = default_scan(cu_tx);
22760 for plane_idx in 1..3 {
22761 let buf: &mut PlaneBuf = if plane_idx == 1 { &mut *u } else { &mut *v };
22762 let cu_grid = if skip {
22763 buf.reconstruct(
22764 cu_x,
22765 cu_y,
22766 cu_tx,
22767 uv_predict_mode,
22768 angle_delta_uv,
22769 cu_reach,
22770 &vec![0i32; cu_tx * cu_tx],
22771 None,
22772 None,
22773 smooth_neighbor_uv,
22774 );
22775 vec![0i32; cu_tx * cu_tx]
22776 } else {
22777 read_plane(
22778 dec,
22779 cdfs,
22780 chroma_set,
22781 &cu_scan,
22782 plane_idx,
22783 cu_around[plane_idx],
22784 mode,
22785 uv_predict_mode,
22786 angle_delta_uv,
22787 cu_reach,
22788 buf,
22789 cu_x,
22790 cu_y,
22791 cu_tx,
22792 cu_tx,
22793 base_q_idx,
22794 // CfL is refused above 32x32
22795 // (`is_cfl_allowed`), so never here.
22796 None,
22797 None,
22798 // The uv plane block (64x64) is larger than
22799 // the unit (32x32): `get_txb_ctx`'s offset-10
22800 // rows, +3 on the `txb_skip_chroma_32` table
22801 // (lane-sb128b r3).
22802 Some(3),
22803 smooth_neighbor_uv,
22804 )?
22805 };
22806 // Immediately, so the NEXT chunk's unit reads this
22807 // one's coefficient context.
22808 neighbours.record_mi_chroma(
22809 cu_mi, luma_span, luma_span, plane_idx, &cu_grid,
22810 );
22811 CHROMA_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
22812 let dst = if plane_idx == 1 { &mut u_units } else { &mut v_units };
22813 for rr in 0..cu_tx {
22814 let start = (cr * cu_tx + rr) * chroma_side + cc * cu_tx;
22815 dst[start..start + cu_tx]
22816 .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]);
22817 }
22818 }
22819 }
22820 }
22821 }
22822 if side > 64 {
22823 // Chroma is already coded and reconstructed per mu chunk above.
22824 luma_grid = vec![0i32; side * side];
22825 u_grid = std::mem::take(&mut u_units);
22826 v_grid = std::mem::take(&mut v_units);
22827 INTRA_128_IN_INTER_HITS.with(|c| c.set(c.get() + 1));
22828 } else if skip {
22829 if !split_luma {
22830 y.reconstruct(
22831 px,
22832 py,
22833 side,
22834 mode,
22835 angle_delta_y,
22836 reach,
22837 &vec![0i32; side * side],
22838 None,
22839 filter_intra,
22840 smooth_neighbor,
22841 );
22842 }
22843 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
22844 u.reconstruct(
22845 cpx,
22846 cpy,
22847 chroma_side,
22848 uv_predict_mode,
22849 angle_delta_uv,
22850 reach,
22851 &vec![0i32; chroma_side * chroma_side],
22852 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
22853 None,
22854 smooth_neighbor_uv,
22855 );
22856 v.reconstruct(
22857 cpx,
22858 cpy,
22859 chroma_side,
22860 uv_predict_mode,
22861 angle_delta_uv,
22862 reach,
22863 &vec![0i32; chroma_side * chroma_side],
22864 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
22865 None,
22866 smooth_neighbor_uv,
22867 );
22868 luma_grid = vec![0i32; side * side];
22869 u_grid = vec![0i32; chroma_side * chroma_side];
22870 v_grid = vec![0i32; chroma_side * chroma_side];
22871 } else {
22872 let around = neighbours.around_mi(at, side);
22873 luma_grid = if split_luma {
22874 // Already coded and reconstructed unit by unit above; the
22875 // block-level grid is only the neighbour write-back's input,
22876 // which `record_split_luma` ignores for plane 0.
22877 vec![0i32; side * side]
22878 } else {
22879 read_plane(
22880 dec,
22881 cdfs,
22882 luma_set_intra,
22883 scan_luma,
22884 0,
22885 around[0],
22886 mode,
22887 mode,
22888 angle_delta_y,
22889 reach,
22890 y,
22891 px,
22892 py,
22893 side,
22894 luma_tx,
22895 base_q_idx,
22896 None,
22897 filter_intra,
22898 None,
22899 smooth_neighbor,
22900 )?
22901 };
22902 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
22903 u_grid = read_plane(
22904 dec,
22905 cdfs,
22906 chroma_set,
22907 scan_chroma,
22908 1,
22909 around[1],
22910 mode,
22911 uv_predict_mode,
22912 angle_delta_uv,
22913 reach,
22914 u,
22915 cpx,
22916 cpy,
22917 chroma_side,
22918 chroma_tx,
22919 base_q_idx,
22920 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
22921 None,
22922 None,
22923 smooth_neighbor_uv,
22924 )?;
22925 v_grid = read_plane(
22926 dec,
22927 cdfs,
22928 chroma_set,
22929 scan_chroma,
22930 2,
22931 around[2],
22932 mode,
22933 uv_predict_mode,
22934 angle_delta_uv,
22935 reach,
22936 v,
22937 cpx,
22938 cpy,
22939 chroma_side,
22940 chroma_tx,
22941 base_q_idx,
22942 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
22943 None,
22944 None,
22945 smooth_neighbor_uv,
22946 )?;
22947 }
22948 }
22949 // lane-comppin r9: end-of-block checkpoint -- everything between
22950 // post_assign_mv and here (interintra, motion_mode, interp_filter, then
22951 // every plane's coeffs) is unproven; a range mismatch here vs aomdec's
22952 // equivalent post-content point (added at the matching call site)
22953 // narrows the ladder to this block's own tail instead of the next
22954 // block's partition read.
22955 if std::env::var_os("EC_AV1_TELL").is_some() {
22956 eprintln!(
22957 "TELL mi_row={} mi_col={} label=block_end tell={} range={}",
22958 rmi, cmi, dec.debug_bitpos(), dec.debug_state().0
22959 );
22960 }
22961 // lane-inter16ab r2: the pair's chroma coefficient context spans BOTH
22962 // strips (mirroring the intra `decode_rect4_16` path), and the even
22963 // strip's own record wrote empty chroma state over those cells -- this
22964 // rewrite is what libaom's single `av1_set_contexts` call for the 8x4
22965 // (4x8) chroma unit leaves behind.
22966 let pair_chroma = strip_chroma
22967 .filter(|s| s.has_chroma)
22968 .map(|s| (s, neighbour_state(&u_grid), neighbour_state(&v_grid)));
22969 // lane-vert46 r1: libaom stamps the chroma entropy context PER TRANSFORM
22970 // UNIT (`av1_set_entropy_contexts` inside `decode_reconstruct_tx`'s mu-chunk
22971 // loop). Above 64 a block's chroma is two or four 32x32 units, so the
22972 // whole-block re-stamp in the record below overwrote every unit's own DC
22973 // sign and level with the TOP-LEFT unit's -- the next block then read a
22974 // stale `dc_sign_ctx` (192x256 --sb-size=128 stream: the 64x128 block at
22975 // the partial right superblock read row 1 where libaom reads row 2). The
22976 // units are collected here and re-stamped after that record, in mu-chunk
22977 // order so a later unit still wins over an earlier one.
22978 let mu_chroma_units: Vec<((usize, usize), usize, Vec<i32>)> = if mu_chroma {
22979 let cu = 32usize;
22980 let mut units = Vec::new();
22981 for cr in 0..(write_h / 64).max(1) {
22982 for cc in 0..(write_w / 64).max(1) {
22983 let cu_mi = (at.0 + cr * 16, at.1 + cc * 16);
22984 for (plane, grid) in [(1usize, &u_grid), (2usize, &v_grid)] {
22985 let mut unit = Vec::with_capacity(cu * cu);
22986 for rr in 0..cu {
22987 let start = (cr * cu + rr) * chroma_side + cc * cu;
22988 unit.extend_from_slice(&grid[start..start + cu]);
22989 }
22990 units.push((cu_mi, plane, unit));
22991 }
22992 }
22993 }
22994 units
22995 } else {
22996 Vec::new()
22997 };
22998 // libaom `av1_reset_entropy_context` / `av1_set_entropy_contexts`:
22999 // `nplanes = 1 + (num_planes - 1) * xd->is_chroma_ref` -- a block that is
23000 // NOT the chroma reference of its 4:2:0 pair codes no chroma transform at
23001 // all, so it leaves its neighbours' CHROMA coefficient contexts exactly as
23002 // it found them. `record_rect_mi`/`record_split_luma_rect_mi` below write
23003 // all three planes unconditionally, and for such a strip the chroma grids
23004 // are all-zero (see the `!has_chroma` arm above) -- that wiped the real
23005 // left-neighbour chroma state, so the PAIR's own `all_zero` then read
23006 // `txb_skip_ctx` one row low (lane-t900 r3, 10-bit 1920x792 stream,
23007 // mi(40,220): base 1 where libaom gathers 2). Snapshot and restore is
23008 // equivalent to not writing them, without threading a flag through both
23009 // recorders.
23010 let saved_chroma_ctx = (!has_chroma).then(|| {
23011 let (w_mi, h_mi) = (write_w / MI, write_h / MI);
23012 let left: Vec<[Neighbour; 2]> = (0..h_mi)
23013 .filter_map(|k| neighbours.left.get(at.0 + k).map(|s| [s[1], s[2]]))
23014 .collect();
23015 let above: Vec<[Neighbour; 2]> = (0..w_mi)
23016 .filter_map(|k| neighbours.above.get(at.1 + k).map(|s| [s[1], s[2]]))
23017 .collect();
23018 (left, above)
23019 });
23020 if vartx_leaves.is_some() {
23021 // Plane 0 is already correct per transform unit
23022 // ([`Neighbours::record_mi_luma`] above); this writes everything else
23023 // [`Neighbours::record_rect`] would.
23024 //
23025 // lane-sbab r1: this used to pass `side, side` on the premise that "a
23026 // var-tx block is always square". That stopped being true the moment
23027 // the SB-level rect strips landed (lane-inter4): a 64x32 / 32x64
23028 // strip keeps `side = SB` for syntax but is NOT square, and stamping
23029 // its neighbour bands 64x64 wrote `above_side_mi = 64` where libaom's
23030 // `update_partition_context` writes `partition_context_lookup[
23031 // BLOCK_32X64]`. The next superblock row then read the partition
23032 // context one value low (ctx 2 where aomdec says 3) and desynced.
23033 // The true footprint is `write_w`/`write_h`, exactly as the
23034 // non-var-tx arm below uses.
23035 // Plane 0 is already correct per transform unit
23036 // ([`Neighbours::record_mi_luma`] above); this writes everything else
23037 // [`Neighbours::record_rect`] would. lane-vert46 r1: the block's OWN
23038 // width/height, not `side` -- var-tx is no longer square-only (the 128
23039 // root's HORZ/VERT arm decodes 128x64 / 64x128 var-tx blocks), and
23040 // `side` there stamped `above_side`/`left_side` = 128, so the NEXT
23041 // superblock's 128-root partition context read 16 where libaom reads 19.
23042 neighbours.record_split_luma_rect_mi(at, write_w, write_h, mode_for_tx, uv_predict_mode, [&u_grid, &v_grid]);
23043 } else {
23044 neighbours.record_rect_mi(
23045 at,
23046 write_w,
23047 write_h,
23048 mode_for_tx,
23049 uv_predict_mode,
23050 &[luma_grid, u_grid, v_grid],
23051 );
23052 }
23053 if let Some((left, above)) = saved_chroma_ctx {
23054 for (k, v) in left.into_iter().enumerate() {
23055 if let Some(slot) = neighbours.left.get_mut(at.0 + k) {
23056 slot[1] = v[0];
23057 slot[2] = v[1];
23058 }
23059 }
23060 for (k, v) in above.into_iter().enumerate() {
23061 if let Some(slot) = neighbours.above.get_mut(at.1 + k) {
23062 slot[1] = v[0];
23063 slot[2] = v[1];
23064 }
23065 }
23066 }
23067 if let Some((s, u_state, v_state)) = pair_chroma {
23068 let (pw, ph) = if s.horz { (16usize, 8usize) } else { (8, 16) };
23069 let round_up_even = |n: usize| n.div_ceil(2) * 2;
23070 let (bound_h, bound_w) = (
23071 round_up_even(neighbours.mi_rows),
23072 round_up_even(neighbours.mi_cols),
23073 );
23074 for cell in 0..(ph / MI) {
23075 if s.pair_mi.0 + cell < bound_h
23076 && let Some(slot) = neighbours.left.get_mut(s.pair_mi.0 + cell)
23077 {
23078 slot[1] = u_state;
23079 slot[2] = v_state;
23080 }
23081 }
23082 for cell in 0..(pw / MI) {
23083 if s.pair_mi.1 + cell < bound_w
23084 && let Some(slot) = neighbours.above.get_mut(s.pair_mi.1 + cell)
23085 {
23086 slot[1] = u_state;
23087 slot[2] = v_state;
23088 }
23089 }
23090 neighbours.record_uv_mode_mi(s.pair_mi.0, s.pair_mi.1, pw / MI, ph / MI, uv_predict_mode);
23091 INTER16_CHROMA_PAIR_HITS.with(|c| c.set(c.get() + 1));
23092 }
23093 for (cu_mi, plane, unit) in &mu_chroma_units {
23094 neighbours.record_mi_chroma(*cu_mi, 64, 64, *plane, unit);
23095 }
23096 neighbours.record_inter_rect_mi(
23097 at,
23098 write_w / MI,
23099 write_h / MI,
23100 skip,
23101 is_inter,
23102 ref_frame_for_lf,
23103 block_filter,
23104 skip_mode,
23105 );
23106 if let Some((ref1, group_idx, idx)) = compound_ctx {
23107 neighbours.record_compound_ctx_rect_mi(at, write_w / MI, write_h / MI, ref1, group_idx, idx);
23108 }
23109 neighbours.fill_skip_grid_rect(
23110 (rmi, cmi),
23111 write_w / MI,
23112 write_h / MI,
23113 skip,
23114 );
23115 neighbours.fill_lf_grid_rect(
23116 (rmi, cmi),
23117 write_w / MI,
23118 write_h / MI,
23119 // lane-rect r2: the strip's true TX_32X16/TX_16X32 dims -- the
23120 // single-scalar corner-cut deblocked the strip seam with the wrong
23121 // edge length (1-px chroma drift on rect-flake-1 f17+).
23122 write_w as u8,
23123 write_h as u8,
23124 // ref_grid's packed convention (lf_level): sign carries GLOBALMV,
23125 // whose mode_lf_lut row is 0, not the 1 every other inter mode gets.
23126 if globalmv_for_lf {
23127 -ref_frame_for_lf
23128 } else {
23129 ref_frame_for_lf
23130 },
23131 );
23132 // lane-txselect: a var-tx block's deblock edges follow its own transform
23133 // units, not the block -- for LUMA only (lane-golomb r6): the chroma
23134 // grids keep the block's own `av1_get_max_uv_txsize`, which is what
23135 // libaom's `get_transform_size` reads for `plane != AOM_PLANE_Y`.
23136 // lane-sb128c r4: libaom `set_one_param_for_line_luma` suppresses every
23137 // edge that is a TU edge but not a PU edge when
23138 // `curr_skipped = m

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