forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB2a2adbaTahinli2 months ago2117 commits

decode.rs23420 lines, 1.5 MiBHistoryRawDownload
1//! Software decoder for this crate's own key-frame tile payloads (spec 5.11),
2//! the reader half of [`crate::tile`]'s writer.
3//!
4//! `tile.rs` is another lane's territory this round (`lane-av1-rect` is
5//! touching its partition search), so nothing here imports its private
6//! helpers: the handful of `pub(crate)` items it already exposes
7//! ([`crate::tile::block_grid`], [`crate::tile::has_half`],
8//! [`crate::tile::INTRA_MODE_CTX`], [`crate::tile::write_golomb`]) are reused,
9//! and everything else (the partition/coefficient context arithmetic, the
10//! scan table) is a from-spec reimplementation kept in step with the writer by
11//! the gate tests below rather than by sharing code with it.
12//!
13//! # Scope (round 1)
14//! Key frames only, and only the shapes the encoder actually still needs to
15//! prove itself against: every coded block is `DC_PRED` (this crate's mode
16//! search names other intra modes, but a decoder for those needs the
17//! directional-prediction edge-reach plumbing [`crate::intra::predict`]
18//! already carries; wiring it up is round 2), never skipped, and every
19//! superblock is a whole number of 64x64 units (a frame whose true edge falls
20//! inside one, forcing the gathered-CDF partial-superblock path, is round 2
21//! too). Anything outside that refuses with [`Error::unsupported`] rather than
22//! silently miscoding.
23
24use ec_av1_syntax::{
25 CdefParams, DeltaParams, LoopFilterParams, LoopRestorationParams,
26 SEG_LVL_ALT_LF_Y_V, SEG_LVL_ALT_Q, SegmentationParams, TileInfo,
27};
28use ec_core::{Error, Result};
29
30/// Per-frame decode state, one instance per decoded stream (lane-thread1).
31///
32/// Every field here used to be a `thread_local!` static, which made a decode a
33/// function of the calling THREAD's history rather than of the bitstream alone
34/// -- and made frame-parallel decoding impossible, since a worker thread sees
35/// empty state. The cells keep exactly the interior mutability the statics
36/// had, so every read/write site is byte-identical; what changes is WHERE the
37/// state lives: `stream.rs` owns one `FrameCtx` and threads `&FrameCtx` down
38/// the decode call graph.
39///
40/// `Cell`/`RefCell` make this `!Sync` on purpose: a `FrameCtx` belongs to
41/// exactly one thread's decode, and is never shared between workers.
42pub(crate) struct FrameCtx {
43 pub(crate) sb128_flag: std::cell::Cell<bool>,
44 pub(crate) cdef_bits: std::cell::Cell<u8>,
45 pub(crate) bit_depth: std::cell::Cell<u8>,
46 pub(crate) superres: std::cell::Cell<(u32, u32)>,
47 pub(crate) cdef_transmitted: std::cell::Cell<bool>,
48 pub(crate) cdef_sb_cols: std::cell::Cell<usize>,
49 pub(crate) cdef_idx_grid: std::cell::RefCell<Vec<u8>>,
50 pub(crate) delta_q_present: std::cell::Cell<bool>,
51 pub(crate) delta_q_res: std::cell::Cell<i32>,
52 pub(crate) current_q_idx: std::cell::Cell<i32>,
53 pub(crate) quant_deltas: std::cell::Cell<crate::quant::QuantDeltas>,
54 pub(crate) delta_lf_present: std::cell::Cell<bool>,
55 pub(crate) delta_lf_res: std::cell::Cell<i32>,
56 pub(crate) delta_lf_multi: std::cell::Cell<bool>,
57 pub(crate) current_delta_lf: std::cell::Cell<[i32; 4]>,
58 pub(crate) seg: std::cell::RefCell<SegmentationParams>,
59 pub(crate) seg_ids: std::cell::RefCell<Vec<u8>>,
60 pub(crate) prev_seg_ids: std::cell::RefCell<Vec<u8>>,
61 pub(crate) seg_mi_dims: std::cell::Cell<(usize, usize)>,
62 pub(crate) above_seg_pred: std::cell::RefCell<Vec<u8>>,
63 pub(crate) left_seg_pred: std::cell::RefCell<Vec<u8>>,
64 pub(crate) cur_segment_id: std::cell::Cell<u8>,
65 pub(crate) seg_tile_origin: std::cell::Cell<(usize, usize)>,
66 pub(crate) tx_select_inter: std::cell::Cell<bool>,
67 pub(crate) reduced_tx_set_inter: std::cell::Cell<bool>,
68 pub(crate) enable_filter_intra_inter: std::cell::Cell<bool>,
69 pub(crate) palette_pred: std::cell::RefCell<Option<Vec<u16>>>,
70 pub(crate) intrabc_mi_grid: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>>,
71 pub(crate) intrabc_dv: std::cell::Cell<Option<(i32, i32)>>,
72 pub(crate) luma_tx_type: std::cell::Cell<TxType>,
73 pub(crate) intrabc_chroma_tx: std::cell::Cell<Option<TxType>>,
74 pub(crate) intra_in_inter_mode: std::cell::Cell<Option<(usize, bool)>>,
75 pub(crate) inter_strip_chroma: std::cell::Cell<Option<InterStripChroma>>,
76 pub(crate) inter_last_mc:
77 std::cell::Cell<Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>>,
78 pub(crate) enable_edge_filter: std::cell::Cell<bool>,
79 pub(crate) last_frame_wide_margin: std::cell::RefCell<Option<Picture>>,
80 pub(crate) reach_sb_px: std::cell::Cell<usize>,
81 pub(crate) grain_bit_depth: std::cell::Cell<u32>,
82 /// lane-wave1 step (i): this superblock's recorded pixel writes, see
83 /// [`ReconOp`]. Pushed by parse, replayed by [`flush_recon`].
84 pub(crate) recon_ops: std::cell::RefCell<Vec<ReconOp>>,
85 /// The queue buffer [`flush_recon`] just drained, kept for its capacity
86 /// so a superblock's records do not regrow the vector from nothing.
87 pub(crate) recon_spare: std::cell::RefCell<Vec<ReconOp>>,
88 /// lane-wave1 step (ii): the tile decoder's own planes, registered by
89 /// [`ReconInline`] while reconstruction runs INLINE (one recon thread).
90 /// `None` while the queue is in use (wavefront workers) and outside a
91 /// tile. See [`push_op`].
92 pub(crate) recon_planes: std::cell::Cell<Option<ReconPlanes>>,
93 /// lane-wave1 step (ii): the superblock wavefront this tile's recorded
94 /// writes are handed to, at more than one reconstruction thread.
95 pub(crate) wave: std::cell::RefCell<Option<std::sync::Arc<WaveState>>>,
96 /// lane-wave5 instrumentation only (`EC_AV1_WAVE_STATS`): when the parse
97 /// thread last handed a superblock to the wavefront.
98 pub(crate) wave_mark: std::cell::Cell<Option<std::time::Instant>>,
99}
100
101impl std::fmt::Debug for FrameCtx {
102 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103 f.write_str("FrameCtx")
104 }
105}
106
107impl FrameCtx {
108 /// A fresh context, every field at the default its thread-local
109 /// predecessor was born with.
110 pub(crate) fn new() -> Self {
111 Self {
112 sb128_flag: std::cell::Cell::new(false),
113 cdef_bits: std::cell::Cell::new(0),
114 bit_depth: std::cell::Cell::new(8),
115 superres: std::cell::Cell::new((0, 8)),
116 cdef_transmitted: std::cell::Cell::new(false),
117 cdef_sb_cols: std::cell::Cell::new(0),
118 cdef_idx_grid: std::cell::RefCell::new(Vec::new()),
119 delta_q_present: std::cell::Cell::new(false),
120 delta_q_res: std::cell::Cell::new(1),
121 current_q_idx: std::cell::Cell::new(0),
122 quant_deltas: std::cell::Cell::new(crate::quant::QuantDeltas {
123 y_dc: 0,
124 u_dc: 0,
125 u_ac: 0,
126 v_dc: 0,
127 v_ac: 0,
128 }),
129 delta_lf_present: std::cell::Cell::new(false),
130 delta_lf_res: std::cell::Cell::new(1),
131 delta_lf_multi: std::cell::Cell::new(false),
132 current_delta_lf: std::cell::Cell::new([0; 4]),
133 seg: std::cell::RefCell::new(SegmentationParams::default()),
134 seg_ids: std::cell::RefCell::new(Vec::new()),
135 prev_seg_ids: std::cell::RefCell::new(Vec::new()),
136 seg_mi_dims: std::cell::Cell::new((0, 0)),
137 above_seg_pred: std::cell::RefCell::new(Vec::new()),
138 left_seg_pred: std::cell::RefCell::new(Vec::new()),
139 cur_segment_id: std::cell::Cell::new(0),
140 seg_tile_origin: std::cell::Cell::new((0, 0)),
141 tx_select_inter: std::cell::Cell::new(false),
142 reduced_tx_set_inter: std::cell::Cell::new(true),
143 enable_filter_intra_inter: std::cell::Cell::new(false),
144 palette_pred: std::cell::RefCell::new(None),
145 intrabc_mi_grid: std::cell::RefCell::new(None),
146 intrabc_dv: std::cell::Cell::new(None),
147 luma_tx_type: std::cell::Cell::new(TxType::DctDct),
148 intrabc_chroma_tx: std::cell::Cell::new(None),
149 intra_in_inter_mode: std::cell::Cell::new(None),
150 inter_strip_chroma: std::cell::Cell::new(None),
151 inter_last_mc: std::cell::Cell::new(None),
152 enable_edge_filter: std::cell::Cell::new(false),
153 last_frame_wide_margin: std::cell::RefCell::new(None),
154 reach_sb_px: std::cell::Cell::new(crate::encode::SUPERBLOCK),
155 grain_bit_depth: std::cell::Cell::new(8),
156 recon_ops: std::cell::RefCell::new(Vec::new()),
157 recon_spare: std::cell::RefCell::new(Vec::new()),
158 recon_planes: std::cell::Cell::new(None),
159 wave: std::cell::RefCell::new(None),
160 wave_mark: std::cell::Cell::new(None),
161 }
162 }
163}
164
165/// `LocalKey::with` for a plain value: lets every former `STATIC.with(|c| ..)`
166/// site read `fctx.field.with(|c| ..)` unchanged. `LocalKey`'s own inherent
167/// `with` still wins for the scratch pools and gate counters that stay
168/// thread-local.
169pub(crate) trait WithRef {
170 fn with<R>(&self, f: impl FnOnce(&Self) -> R) -> R {
171 f(self)
172 }
173}
174impl<T: ?Sized> WithRef for T {}
175
176/// A [`FrameCtx`] copy for one of [`crate::par`]'s filter worker threads.
177///
178/// `FrameCtx` is `!Sync` on purpose (a decode's state belongs to one thread),
179/// and the post-decode filter chain reads exactly these fields: the bit depth
180/// (every kernel's clamp and threshold shift), the segmentation table
181/// (`segment_id_at`/`lf_level` in the deblocker), the frame's superres state
182/// and the film-grain bit depth. Everything else keeps [`FrameCtx::new`]'s
183/// default -- a field that turns out to be read after all shows up as a hash
184/// mismatch in
185/// `a_real_stream_filters_identically_with_one_and_four_filter_threads`.
186pub(crate) fn filter_ctx_copy(fctx: &FrameCtx) -> FrameCtx {
187 let out = FrameCtx::new();
188 out.bit_depth.set(fctx.bit_depth.get());
189 out.grain_bit_depth.set(fctx.grain_bit_depth.get());
190 out.superres.set(fctx.superres.get());
191 out.seg_mi_dims.set(fctx.seg_mi_dims.get());
192 out.seg.replace(fctx.seg.borrow().clone());
193 out.seg_ids.replace(fctx.seg_ids.borrow().clone());
194 out
195}
196
197use crate::cdf;
198use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
199use crate::encode::{Picture, Reach};
200use crate::intra::predict;
201use crate::mc;
202use crate::msac::SymbolDecoder;
203use crate::mvstack::{
204 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME,
205 MiGrid, MiInfo, NO_SIGN_BIAS, NeighbourRef, SignBiasTable, comp_reference_type_ctx,
206 find_mv_stack_with_sign_bias, reference_mode_ctx,
207 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx,
208 single_ref_p6_ctx, uni_comp_ref_p1_ctx,
209};
210use crate::tile::{INTRA_MODE_CTX, block_grid, has_half};
211use crate::transform::{TxType, dequant_and_inverse_typed_wh};
212
213const PARTITION_NONE: usize = 0;
214const PARTITION_HORZ: usize = 1;
215const PARTITION_VERT: usize = 2;
216const PARTITION_SPLIT: usize = 3;
217const PARTITION_HORZ_A: usize = 4;
218const PARTITION_HORZ_B: usize = 5;
219const PARTITION_VERT_A: usize = 6;
220const PARTITION_VERT_B: usize = 7;
221const PARTITION_HORZ_4: usize = 8;
222const PARTITION_VERT_4: usize = 9;
223const SB_MI: u32 = 16;
224const BLOCK_MI: u32 = 8;
225
226// lane-sb128 r1: this sequence's `use_128x128_superblock` (spec 5.5.1).
227// Every superblock-granular rule below (`delta_q`/`delta_lf`'s "is this the
228// superblock's own top-left mi?", the loop-restoration read's unit span, the
229// partition tree's own root level) keys off it; `SB_MI` stays the 64x64
230// *quadrant* size a 128 superblock is decoded in, which is also what the CDEF
231// grid is indexed by (libaom `read_cdef` reads one `cdef_idx` per 64x64
232// inside a 128 superblock).
233thread_local! {
234 /// lane-frame80: `EC_TRACE_COEFF_FRAME=<decode idx>` narrows the
235 /// `EC_TRACE_COEFF` rungs to a single frame in DECODE order (a 4K stream
236 /// prints gigabytes otherwise). Unset = every frame, as before.
237 static COEFF_TRACE_FRAME: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
238 static COEFF_TRACE_CUR: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
239}
240
241/// Called by [`crate::stream::decode_stream`] before each frame's tiles with
242/// that frame's DECODE-order index.
243pub fn set_coeff_trace_frame(idx: usize) {
244 COEFF_TRACE_FRAME.with(|c| {
245 if c.get().is_none() {
246 let want = match crate::envflags::var("EC_TRACE_COEFF_FRAME") {
247 Ok(v) => v.parse::<usize>().unwrap_or(usize::MAX),
248 // unset: keep tracing every frame, as before this rung existed
249 Err(_) => usize::MAX - 1,
250 };
251 c.set(Some(want));
252 }
253 });
254 COEFF_TRACE_CUR.with(|c| c.set(idx));
255 if crate::envflags::env_flag!("EC_TRACE_COEFF") {
256 eprintln!("EC_COEFF_FRAME decode_idx={idx}");
257 }
258}
259
260pub(crate) fn coeff_trace_on() -> bool {
261 if !crate::envflags::env_flag!("EC_TRACE_COEFF") {
262 return false;
263 }
264 match COEFF_TRACE_FRAME.with(|c| c.get()) {
265 // no `set_coeff_trace_frame` caller (direct tile-decode tests), or the
266 // env var unset: trace every frame.
267 None => true,
268 Some(w) if w >= usize::MAX - 1 => true,
269 Some(w) => COEFF_TRACE_CUR.with(|c| c.get()) == w,
270 }
271}
272
273
274/// Sets [`SB128`] for this thread (called once per frame from `stream.rs`).
275pub(crate) fn set_sb128(v: bool, fctx: &crate::decode::FrameCtx) {
276 fctx.sb128_flag.with(|c| c.set(v));
277 crate::encode::set_reach_superblock_px(if v { 128 } else { 64 }, fctx);
278}
279
280fn sb128(fctx: &crate::decode::FrameCtx) -> bool {
281 fctx.sb128_flag.with(|c| c.get())
282}
283
284/// This sequence's superblock size in mi units (16 = 64x64, 32 = 128x128).
285pub(crate) fn sb_mi_cur(fctx: &crate::decode::FrameCtx) -> u32 {
286 if sb128(fctx) { SB_MI * 2 } else { SB_MI }
287}
288
289// How many real 128-level partition symbols this decoder has read, and how
290// many superblocks resolved to `PARTITION_SPLIT` (coded or forced) -- the
291// gate's proof a `--sb-size=128` stream exercised the 128 partition root.
292thread_local! {
293 static PART128_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
294 static PART128_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
295 static PART128_GATHERED_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
296}
297
298/// Current value of `PART128_GATHERED_SYMBOLS`: 128 roots that read the
299/// half-out-of-frame gathered split_or_horz/split_or_vert symbol (spec
300/// 5.11.4), which this decoder used to read and throw away.
301#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
302pub(crate) fn part128_gathered_symbols() -> usize {
303 PART128_GATHERED_SYMBOLS.with(|c| c.get())
304}
305
306/// Current value of [`PART128_SYMBOLS`].
307#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
308pub(crate) fn part128_symbols() -> usize {
309 PART128_SYMBOLS.with(|c| c.get())
310}
311
312/// Current value of [`PART128_SPLIT_HITS`].
313#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
314pub(crate) fn part128_split_hits() -> usize {
315 PART128_SPLIT_HITS.with(|c| c.get())
316}
317
318/// [`gather`] over an alphabet of any length -- the 128-level partition CDF
319/// has 8 symbols (no `PARTITION_HORZ_4`/`_VERT_4` at `BLOCK_128X128`, spec
320/// `partition_cdf_length`), so its forced-split gather sums 5 elements where
321/// the 64/32 levels sum 6.
322fn gather_of(cdf: &[u16], elements: &[usize]) -> [u16; 3] {
323 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
324 [32768 - split, 32768, 0]
325}
326
327/// [`VERT_ALIKE`]/[`HORZ_ALIKE`] without the 1:4 arms, for the 128 root.
328const VERT_ALIKE128: [usize; 5] = [2, PARTITION_SPLIT, 4, 6, 7];
329const HORZ_ALIKE128: [usize; 5] = [1, PARTITION_SPLIT, 4, 5, 6];
330
331// How many `use_filter_intra` symbols this decoder has read as `1`, across
332// every call on the current thread -- the cheap counter [`filter_intra_hits`] gate
333// tests read (before/after, not the absolute value) to prove a stream
334// actually exercised the filter-intra predictor rather than silently
335// skipping it.
336thread_local! {
337 static FILTER_INTRA_HITS: std::cell::Cell<usize> =
338 const { std::cell::Cell::new(0) };
339}
340
341/// Current value of [`FILTER_INTRA_HITS`].
342#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
343pub(crate) fn filter_intra_hits() -> usize {
344 FILTER_INTRA_HITS.with(|c| c.get())
345}
346
347// lane-fiinter r1: how many of those `use_filter_intra == 1` symbols belonged
348// to an INTRA block inside an INTER frame (`read_intra_block_mode_info`'s own
349// `read_filter_intra_mode_info` call), which no gate exercised before this
350// round -- every inter gate recipe passed `--enable-filter-intra=0`.
351thread_local! {
352 static INTRA_IN_INTER_FILTER_INTRA_HITS: std::cell::Cell<usize> =
353 const { std::cell::Cell::new(0) };
354}
355
356/// Current value of [`INTRA_IN_INTER_FILTER_INTRA_HITS`].
357#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
358pub(crate) fn intra_in_inter_filter_intra_hits() -> usize {
359 INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.get())
360}
361
362// lane-angleinter r1: how many INTRA blocks inside an INTER frame carried a
363// nonzero `angle_delta_y` / `angle_delta_uv` (`read_intra_angle_info`). Both
364// arms refused a nonzero luma delta before this round, and no inter gate
365// enabled `--enable-angle-delta` (aomenc's own default is 1).
366thread_local! {
367 static INTRA_IN_INTER_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> =
368 const { std::cell::Cell::new(0) };
369 static INTRA_IN_INTER_ANGLE_DELTA_UV_HITS: std::cell::Cell<usize> =
370 const { std::cell::Cell::new(0) };
371}
372
373/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_Y_HITS`].
374#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
375pub(crate) fn intra_in_inter_angle_delta_y_hits() -> usize {
376 INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.get())
377}
378
379/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_UV_HITS`].
380#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
381pub(crate) fn intra_in_inter_angle_delta_uv_hits() -> usize {
382 INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|c| c.get())
383}
384
385// lane-uv8 r1: the three non-DC chroma mode classes an INTRA 8x8 leaf inside
386// an INTER frame ([`decode_inter_block8`]'s intra arm) can carry -- the arm
387// read `uv_mode` and then refused everything but `DC_PRED`. Counted here and
388// nowhere else so the gate's assert cannot be satisfied by a >=16x16 block.
389thread_local! {
390 static INTRA_IN_INTER8_UV_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
391 static INTRA_IN_INTER8_UV_SMOOTH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
392 static INTRA_IN_INTER8_UV_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
393}
394
395thread_local! {
396 static INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
397}
398
399/// Nonzero luma angle deltas coded by an intra 8x8 leaf inside an inter frame
400/// (lane-leaf8tx r1) -- counted only in [`decode_inter_block8`]'s intra arm.
401#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
402pub(crate) fn intra_in_inter8_angle_delta_y_hits() -> usize {
403 INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS.with(|c| c.get())
404}
405
406/// `(directional, smooth/paeth, CfL)` chroma modes coded by an intra 8x8 leaf
407/// inside an inter frame -- see [`INTRA_IN_INTER8_UV_DIR_HITS`].
408#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
409pub(crate) fn intra_in_inter8_uv_hits() -> (usize, usize, usize) {
410 (
411 INTRA_IN_INTER8_UV_DIR_HITS.with(|c| c.get()),
412 INTRA_IN_INTER8_UV_SMOOTH_HITS.with(|c| c.get()),
413 INTRA_IN_INTER8_UV_CFL_HITS.with(|c| c.get()),
414 )
415}
416
417// lane-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into
418// [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a
419// frame-level flag through the recursive block decode -- `0` (the default)
420// makes every call a true no-op, matching every existing gate stream's
421// `cdef_bits == 0` behaviour exactly.
422// lane-realworld r8: the sequence header's `color_config.bit_depth`, set
423// once per `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs`
424// call the same way `CDEF_BITS` is above. `stream.rs`'s own refusal still
425// blocks every non-8-bit stream from reaching a decode call, so this is `8`
426// on every path that runs today -- threading it now (rather than the literal
427// `8`) is stage 1 of widening past that refusal without re-deriving every
428// clamp bound later. `PlaneBuf`'s sample storage stays `u16` regardless of
429// depth (this decoder's own internal choice, matches dav1d/libaom).
430/// `(1 << bit_depth) - 1` — the reconstruction clamp bound for the current
431/// stream's [`BIT_DEPTH`], replacing the crate-wide literal `255`.
432pub(crate) fn sample_max(fctx: &crate::decode::FrameCtx) -> i32 {
433 (1i32 << fctx.bit_depth.with(std::cell::Cell::get)) - 1
434}
435/// The current stream's bit depth, for callers (e.g. dequant) that need the
436/// raw value rather than the derived clamp bound.
437pub(crate) fn bit_depth(fctx: &crate::decode::FrameCtx) -> u8 {
438 fctx.bit_depth.with(std::cell::Cell::get)
439}
440/// Sets [`BIT_DEPTH`] for the current thread, called once per frame from
441/// [`crate::stream`]'s decode loop.
442pub(crate) fn set_bit_depth(bit_depth: u8, fctx: &crate::decode::FrameCtx) {
443 fctx.bit_depth.with(|c| c.set(bit_depth));
444}
445
446 /// This frame's superres state: `(upscaled_width, superres_denom)`, or
447 /// `(0, 8)` when the frame is not scaled. Spec 7.16's upscale runs
448 /// between CDEF and loop restoration, so LOOP RESTORATION -- unit grid,
449 /// `read_lr`'s unit corners and the pixel filters themselves -- works in
450 /// UPSCALED coordinates while deblock and CDEF work in downscaled ones
451 /// (libaom `av1_superres_upscale` in `decodeframe.c`, and
452 /// `av1_loop_restoration_corners_in_sb`'s own `mi_to_num_x`/`denom_x`
453 /// superres arms). Set once per frame from [`crate::stream`]'s decode
454 /// loop, like [`BIT_DEPTH`], and reset to `(0, 8)` on an unscaled frame
455 /// so a later frame never inherits it.
456
457/// Sets [`SUPERRES`] for the current thread. `upscaled_width` is 0 (and
458/// `denom` 8) for a frame that is not superres-scaled.
459pub(crate) fn set_superres(upscaled_width: u32, denom: u32, fctx: &crate::decode::FrameCtx) {
460 fctx.superres.with(|c| c.set((upscaled_width, denom)));
461}
462
463/// `(upscaled_width, superres_denom)` when this frame is superres-scaled
464/// (libaom `av1_superres_scaled`), else `None`.
465pub(crate) fn superres(fctx: &crate::decode::FrameCtx) -> Option<(u32, u32)> {
466 let (w, d) = fctx.superres.with(std::cell::Cell::get);
467 (w > 0 && d != 8).then_some((w, d))
468}
469// Whether this superblock's single CDEF unit (this decoder has no 128x128
470// SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal
471// read -- reset to `false` at the top of each superblock in the two tile
472// loops, spec `read_cdef`'s `cdef_transmitted[index]`.
473// Number of superblock columns in the current tile's grid, so
474// [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into
475// [`CDEF_IDX_GRID`].
476// One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select
477// which of the header's `1 << cdef.bits` strength pairs applies to that
478// superblock's samples.
479// How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`]
480// has read, across every call on the current thread -- the gate's proof that a
481// `cdef_bits > 0` stream actually reached the new reader rather than every
482// superblock coincidentally being all-skip.
483thread_local! {
484 static CDEF_IDX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
485}
486
487// How many times a warp was suppressed for one PLANE because that plane's own
488// block is narrower or shorter than 8 (`av1_init_warp_params`'s own bail-out,
489// reconinter.c) -- the gate's proof that a stream really carries the shape,
490// since the square `side`/`chroma_side` can be 8 or more while the plane's
491// true block is 4 wide (an 8x16 luma block's 4x8 chroma).
492thread_local! {
493 static WARP_PLANE_SUPPRESS_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
494}
495
496/// Current value of [`WARP_PLANE_SUPPRESS_HITS`].
497#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
498pub(crate) fn warp_plane_suppress_hits() -> usize {
499 WARP_PLANE_SUPPRESS_HITS.with(|c| c.get())
500}
501
502/// `av1_init_warp_params` (libaom reconinter.c): warp is decided per PLANE and
503/// bails out at `block_width < 8 || block_height < 8`, so the plane's OWN
504/// block dimensions decide it -- never the square `side`/`chroma_side`, which
505/// for a rectangular luma block (8x16, 16x8) or a PARTITION_HORZ/VERT strip is
506/// bigger than the real block in one axis.
507fn warp_plane_allowed(w: usize, h: usize) -> bool {
508 if w >= 8 && h >= 8 {
509 return true;
510 }
511 WARP_PLANE_SUPPRESS_HITS.with(|c| c.set(c.get() + 1));
512 false
513}
514
515/// Current value of [`CDEF_IDX_HITS`].
516#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
517pub(crate) fn cdef_idx_hits() -> usize {
518 CDEF_IDX_HITS.with(|c| c.get())
519}
520
521// lane-t900 r6: gate proof for the three r2-r4 root causes that shipped with no
522// counter -- the in-inter tx-depth context (`tx_size_context_txfm_rect`), the
523// non-chroma-reference block that must LEAVE its neighbours' chroma coefficient
524// contexts alone, and the intra-edge filter neighbour pair taken mi-exact
525// instead of from the coarse 16x16 cell.
526thread_local! {
527 static INTRA_IN_INTER_TXCTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
528 static NON_CHROMA_REF_CTX_SKIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
529 static EDGE_FILTER_MI_FIX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
530}
531
532/// Current value of [`INTRA_IN_INTER_TXCTX_HITS`].
533#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
534pub(crate) fn intra_in_inter_txctx_hits() -> usize {
535 INTRA_IN_INTER_TXCTX_HITS.with(|c| c.get())
536}
537
538/// Current value of [`NON_CHROMA_REF_CTX_SKIP_HITS`].
539#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
540pub(crate) fn non_chroma_ref_ctx_skip_hits() -> usize {
541 NON_CHROMA_REF_CTX_SKIP_HITS.with(|c| c.get())
542}
543
544/// Current value of [`EDGE_FILTER_MI_FIX_HITS`].
545#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
546pub(crate) fn edge_filter_mi_fix_hits() -> usize {
547 EDGE_FILTER_MI_FIX_HITS.with(|c| c.get())
548}
549
550// lane-realworld r4: this frame's `delta.q_present` (spec 5.9.17) and its
551// actual step (`1 << delta.q_res`, already the real multiplier, not the raw
552// 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a
553// true no-op, matching every existing gate stream's `delta_q_present == 0`
554// behaviour exactly, the same corner-cut [`CDEF_BITS`] takes above.
555// The running quantizer index (spec `CurrentQIndex`, libaom
556// `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the
557// top of every tile (spec `decode_tile`), carried across superblocks within
558// that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the
559// dequantization call sites instead of the frame-constant `base_q_idx`.
560// This frame's own per-plane DC/AC quantizer-index deltas (lane-sbpart r11,
561// spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- frame-constant (not
562// per-superblock like [`CURRENT_Q_IDX`]), set once per frame decode and read
563// back at every dequantization call site keyed on which plane it is doing.
564// How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has
565// read, across every call on the current thread -- the gate's proof that a
566// `delta_q_present` stream actually reached the new reader.
567thread_local! {
568 static DELTA_Q_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
569}
570
571/// Current value of [`DELTA_Q_HITS`].
572#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
573pub(crate) fn delta_q_hits() -> usize {
574 DELTA_Q_HITS.with(|c| c.get())
575}
576
577/// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 =
578/// Y, 1 = U, 2 = V) -- luma has no coded `ac` delta (spec 5.9.12 never reads
579/// one), so it is always `0` here.
580fn plane_q_delta(plane_idx: usize, fctx: &crate::decode::FrameCtx) -> (i32, i32) {
581 let d = fctx.quant_deltas.with(|c| c.get());
582 match plane_idx {
583 0 => (d.y_dc, 0),
584 1 => (d.u_dc, d.u_ac),
585 _ => (d.v_dc, d.v_ac),
586 }
587}
588
589/// `read_delta_qindex`/`read_delta_q_params` (spec 5.11.10, libaom
590/// `decodemv.c:85-146,735-770`), called right after [`maybe_read_cdef_idx`]
591/// at every block-decode call site (spec order `skip -> cdef -> delta_q`).
592/// A no-op when `delta_q_present` is unset, or when this block is not at the
593/// superblock's own top-left MI position (`b_row == 0 && b_col == 0` in
594/// libaom, collapsed here to a position check since a partition tree's
595/// top-left leaf is the only block that can ever land there), or when that
596/// leaf both *is* the whole superblock and is `skip` (the one case libaom
597/// itself skips the read, state carrying over unchanged).
598fn maybe_read_delta_q(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool, fctx: &crate::decode::FrameCtx) {
599 if !fctx.delta_q_present.with(|c| c.get()) {
600 return;
601 }
602 let sb_mi = sb_mi_cur(fctx) as usize;
603 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
604 return;
605 }
606 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
607 // computed against the sequence's own superblock size (lane-sb128b r1:
608 // it used to be hardcoded against 64 and disabled under `sb128`, which a
609 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
610 // wrong).
611 if is_whole_sb && skip {
612 return;
613 }
614 let mut abs = dec.symbol(&mut cdfs.delta_q) as i32;
615 const DELTA_Q_SMALL: i32 = 3;
616 if abs >= DELTA_Q_SMALL {
617 let rem_bits = dec.literal(3) + 1;
618 let thr = (1i32 << rem_bits) + 1;
619 abs = dec.literal(rem_bits) as i32 + thr;
620 }
621 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
622 let reduced = if sign_negative { -abs } else { abs };
623 DELTA_Q_HITS.with(|c| c.set(c.get() + 1));
624 let res = fctx.delta_q_res.with(|c| c.get());
625 fctx.current_q_idx.with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));
626}
627
628// lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi`
629// (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`.
630// The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`,
631// `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile,
632// mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever
633// updates index 0 and every reader treats that as the value for all 4
634// indices (spec `read_delta_lf_params`'s own single-cdf branch).
635// How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has
636// read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`].
637thread_local! {
638 static DELTA_LF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
639}
640
641/// Current value of [`DELTA_LF_HITS`].
642#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
643pub(crate) fn delta_lf_hits() -> usize {
644 DELTA_LF_HITS.with(|c| c.get())
645}
646
647/// `read_delta_lflevel`/`read_delta_lf_params` (spec 5.11.11, libaom
648/// `decodemv.c:99-146,735-770`) -- same shape and same call-site gating as
649/// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over
650/// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or
651/// read once into index 0 otherwise.
652fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool, fctx: &crate::decode::FrameCtx) {
653 if !fctx.delta_lf_present.with(|c| c.get()) {
654 return;
655 }
656 let sb_mi = sb_mi_cur(fctx) as usize;
657 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
658 return;
659 }
660 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
661 // computed against the sequence's own superblock size (lane-sb128b r1:
662 // it used to be hardcoded against 64 and disabled under `sb128`, which a
663 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
664 // wrong).
665 if is_whole_sb && skip {
666 return;
667 }
668 let multi = fctx.delta_lf_multi.with(|c| c.get());
669 let res = fctx.delta_lf_res.with(|c| c.get());
670 let count = if multi { 4 } else { 1 };
671 let mut cur = fctx.current_delta_lf.with(|c| c.get());
672 for i in 0..count {
673 let mut abs = if multi {
674 dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32
675 } else {
676 dec.symbol(&mut cdfs.delta_lf) as i32
677 };
678 const DELTA_LF_SMALL: i32 = 3;
679 if abs >= DELTA_LF_SMALL {
680 let rem_bits = dec.literal(3) + 1;
681 let thr = (1i32 << rem_bits) + 1;
682 abs = dec.literal(rem_bits) as i32 + thr;
683 }
684 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
685 let reduced = if sign_negative { -abs } else { abs };
686 cur[i] = (cur[i] + reduced * res).clamp(-63, 63);
687 DELTA_LF_HITS.with(|c| c.set(c.get() + 1));
688 }
689 fctx.current_delta_lf.with(|c| c.set(cur));
690}
691
692/// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
693/// after `skip` is known at every block-decode call site. A no-op at
694/// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and
695/// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
696/// `allow_intrabc`, so neither needs a separate check here. Reads once per
697/// superblock, at the first non-skip block.
698fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: bool, fctx: &crate::decode::FrameCtx) {
699 let bits = fctx.cdef_bits.with(|c| c.get());
700 if bits == 0 || skip || fctx.cdef_transmitted.with(|c| c.get()) {
701 return;
702 }
703 let idx = dec.literal(u32::from(bits)) as u8;
704 fctx.cdef_transmitted.with(|c| c.set(true));
705 CDEF_IDX_HITS.with(|c| c.set(c.get() + 1));
706 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
707 let sb_cols = fctx.cdef_sb_cols.with(|c| c.get());
708 if sb_cols > 0 {
709 fctx.cdef_idx_grid.with(|g| {
710 let mut g = g.borrow_mut();
711 let i = sb_r * sb_cols + sb_c;
712 if i < g.len() {
713 g[i] = idx;
714 }
715 });
716 }
717}
718
719// ---------------------------------------------------------------------------
720// lane-seg: segmentation. Header (spec 5.9.14) is parsed by `ec-av1-syntax`;
721// this block is the per-block `segment_id` reader (spec 5.11.7-5.11.9) plus
722// the two consumers a real stream exercises: the per-segment quantizer index
723// (spec 7.12.2 `get_qindex`) and the per-segment loop-filter level
724// (spec 7.14.4). Shapes follow libaom `decodemv.c:read_segment_id`/
725// `read_intra_segment_id`/`read_inter_segment_id` and
726// `pred_common.h:av1_get_spatial_seg_pred` -- note libaom returns the SPATIAL
727// PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which
728// is what the oracle every gate here compares against actually does.
729thread_local! {
730 /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries
731 /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride).
732 /// `PrevSegmentIds`: the primary reference frame's saved map, empty when
733 /// this frame has no primary reference (spec `load_previous_segment_ids`).
734 /// `(mi_rows, mi_cols)` for both maps above.
735 /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi
736 /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which
737 /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead.
738 /// The block currently being decoded -- read back by [`block_q_idx`].
739 /// The tile's own top-left mi position, for `AvailU`/`AvailL`.
740 /// How many real `segment_id` symbols were read, and the set of segment
741 /// ids any block ended up with -- the gate's proof the feature fired.
742 static SEG_ID_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
743 static SEG_IDS_SEEN: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
744 /// How many `seg_id_predicted` symbols were read (temporal update).
745 static SEG_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
746}
747
748/// Installs this frame's segmentation parameters and allocates its map, with
749/// `prev` the primary reference frame's saved map (spec
750/// `load_previous_segment_ids`; `None` for `PRIMARY_REF_NONE` or an empty
751/// slot). Called once per frame, whether or not segmentation is enabled.
752pub(crate) fn set_segmentation(
753 seg: SegmentationParams,
754 mi_rows: usize,
755 mi_cols: usize,
756 prev: Option<&[u8]>, fctx: &crate::decode::FrameCtx,
757) {
758 fctx.seg.with(|s| *s.borrow_mut() = seg);
759 fctx.seg_mi_dims.with(|c| c.set((mi_rows, mi_cols)));
760 fctx.seg_ids.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]);
761 fctx.prev_seg_ids.with(|m| {
762 let mut m = m.borrow_mut();
763 m.clear();
764 if let Some(p) = prev {
765 if p.len() == mi_rows * mi_cols {
766 m.extend_from_slice(p);
767 }
768 }
769 });
770 fctx.above_seg_pred.with(|m| *m.borrow_mut() = vec![0u8; mi_cols]);
771 fctx.left_seg_pred.with(|m| *m.borrow_mut() = vec![0u8; mi_rows]);
772 fctx.cur_segment_id.with(|c| c.set(0));
773}
774
775/// This frame's decoded segment map, to be stored into whichever reference
776/// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`).
777pub(crate) fn take_segment_ids(fctx: &crate::decode::FrameCtx) -> Vec<u8> {
778 fctx.seg_ids.with(|m| m.borrow().clone())
779}
780
781/// How many `segment_id` symbols have been read (never reset per frame).
782#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
783pub(crate) fn segment_id_hits() -> usize {
784 SEG_ID_HITS.with(|c| c.get())
785}
786
787/// How many distinct segment ids any decoded block has carried.
788#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
789pub(crate) fn segment_ids_seen() -> usize {
790 SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize)
791}
792
793/// How many `seg_id_predicted` symbols have been read (temporal update).
794#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
795pub(crate) fn segment_pred_hits() -> usize {
796 SEG_PRED_HITS.with(|c| c.get())
797}
798
799/// Resets the segmentation hit counters (gate setup).
800#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
801pub(crate) fn reset_segment_hits() {
802 SEG_ID_HITS.with(|c| c.set(0));
803 SEG_IDS_SEEN.with(|c| c.set(0));
804 SEG_PRED_HITS.with(|c| c.set(0));
805}
806
807/// `seg_feature_active_idx(segment_id, feature)` for the frame currently
808/// being decoded, with its `FeatureData` value.
809fn seg_feature(segment_id: usize, feature: usize, fctx: &crate::decode::FrameCtx) -> Option<i32> {
810 fctx.seg.with(|s| {
811 let s = s.borrow();
812 s.feature_active(segment_id, feature)
813 .then(|| i32::from(s.feature_data[segment_id][feature]))
814 })
815}
816
817/// `get_qindex(ignoreDeltaQ = 0, segment_id)` (spec 7.12.2, libaom
818/// `av1_get_qindex`) for the block currently being decoded: the running
819/// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data.
820/// Every dequant call site reads the block's quantizer through here.
821fn block_q_idx(fctx: &crate::decode::FrameCtx) -> i32 {
822 let base = fctx.current_q_idx.with(|c| c.get());
823 let seg_id = fctx.cur_segment_id.with(|c| c.get()) as usize;
824 match seg_feature(seg_id, SEG_LVL_ALT_Q, fctx) {
825 Some(data) => (base + data).clamp(0, 255),
826 None => base,
827 }
828}
829
830/// The segment id recorded for one mi cell of the current frame's map.
831fn segment_id_at(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> u8 {
832 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
833 if mi_r >= mi_rows || mi_c >= mi_cols {
834 return 0;
835 }
836 fctx.seg_ids.with(|m| m.borrow()[mi_r * mi_cols + mi_c])
837}
838
839/// `set_segment_id`: stamps `id` over every mi cell this block covers.
840fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8, fctx: &crate::decode::FrameCtx) {
841 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
842 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
843 fctx.seg_ids.with(|m| {
844 let mut m = m.borrow_mut();
845 for y in 0..y_mis {
846 for x in 0..x_mis {
847 m[(mi_r + y) * mi_cols + mi_c + x] = id;
848 }
849 }
850 });
851 fctx.cur_segment_id.with(|c| c.set(id));
852 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
853}
854
855/// `get_predicted_segment_id` (libaom `dec_get_segment_id` over
856/// `last_frame_seg_map`): the minimum previous-frame segment id over the
857/// block's own mi footprint. `0` when there is no previous map.
858fn predicted_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, fctx: &crate::decode::FrameCtx) -> u8 {
859 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
860 fctx.prev_seg_ids.with(|m| {
861 let m = m.borrow();
862 if m.is_empty() {
863 return 0;
864 }
865 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
866 let mut id = u8::MAX;
867 for y in 0..y_mis {
868 for x in 0..x_mis {
869 id = id.min(m[(mi_r + y) * mi_cols + mi_c + x]);
870 }
871 }
872 if id == u8::MAX { 0 } else { id }
873 })
874}
875
876/// `av1_neg_deinterleave` (libaom `decodemv.c:258`).
877fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 {
878 if reference == 0 {
879 return diff;
880 }
881 if reference >= max - 1 {
882 return max - diff - 1;
883 }
884 let half = if 2 * reference < max {
885 diff <= 2 * reference
886 } else {
887 diff <= 2 * (max - reference - 1)
888 };
889 if half {
890 return if diff & 1 != 0 {
891 reference + ((diff + 1) >> 1)
892 } else {
893 reference - (diff >> 1)
894 };
895 }
896 if 2 * reference < max { diff } else { max - (diff + 1) }
897}
898
899/// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current
900/// frame's already-decoded above/left/above-left neighbours.
901fn spatial_seg_pred(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> (i32, usize) {
902 let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
903 let (avail_u, avail_l) = (mi_r > row0, mi_c > col0);
904 let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1, fctx)));
905 let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c, fctx)));
906 let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1, fctx)));
907 let ctx = match prev_ul {
908 None => 0,
909 Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2,
910 Some(ul) if Some(ul) == prev_u || Some(ul) == prev_l || prev_u == prev_l => 1,
911 Some(_) => 0,
912 };
913 let pred = match (prev_u, prev_l) {
914 (None, l) => l.unwrap_or(0),
915 (Some(u), None) => u,
916 (Some(u), Some(l)) => {
917 if prev_ul == Some(u) {
918 u
919 } else {
920 l
921 }
922 }
923 };
924 (pred, ctx)
925}
926
927/// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id
928/// when `skip`, otherwise one `segment_id` symbol de-interleaved against
929/// that prediction. Does NOT write the map -- callers do.
930fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, skip: bool, fctx: &crate::decode::FrameCtx) -> u8 {
931 let (pred, ctx) = spatial_seg_pred(mi_r, mi_c, fctx);
932 if skip {
933 return pred as u8;
934 }
935 let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32;
936 SEG_ID_HITS.with(|c| c.set(c.get() + 1));
937 let last_active = fctx.seg.with(|s| i32::from(s.borrow().last_active_seg_id));
938 neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active) as u8
939}
940
941/// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block
942/// -- once before `skip` when `SegIdPreSkip`, once after it otherwise (the
943/// caller decides which by passing `pre_skip`).
944fn intra_segment_id(
945 dec: &mut SymbolDecoder,
946 cdfs: &mut Cdfs,
947 mi_r: usize,
948 mi_c: usize,
949 w_mi: usize,
950 h_mi: usize,
951 skip: bool, fctx: &crate::decode::FrameCtx,
952) {
953 if !fctx.seg.with(|s| s.borrow().enabled) {
954 return;
955 }
956 let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip, fctx);
957 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
958}
959
960/// Whether this frame's intra blocks read their `segment_id` before `skip`
961/// (`SegIdPreSkip`); `false` also when segmentation is off.
962fn seg_id_pre_skip(fctx: &crate::decode::FrameCtx) -> bool {
963 fctx.seg.with(|s| {
964 let s = s.borrow();
965 s.enabled && s.seg_id_pre_skip
966 })
967}
968
969/// `read_inter_segment_id(preskip)` (spec 5.11.9, libaom `decodemv.c:352`).
970/// Called at both spec positions of an inter frame's block: `pre_skip = true`
971/// before `skip_mode`/`skip`, and `pre_skip = false` after them.
972fn inter_segment_id(
973 dec: &mut SymbolDecoder,
974 cdfs: &mut Cdfs,
975 mi_r: usize,
976 mi_c: usize,
977 w_mi: usize,
978 h_mi: usize,
979 skip: bool,
980 pre_skip: bool, fctx: &crate::decode::FrameCtx,
981) {
982 let (enabled, update_map, temporal_update, pre_skip_frame) = fctx.seg.with(|s| {
983 let s = s.borrow();
984 (s.enabled, s.update_map, s.temporal_update, s.seg_id_pre_skip)
985 });
986 if !enabled {
987 return;
988 }
989 if !update_map {
990 // The map is inherited wholesale from the previous frame.
991 let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx);
992 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
993 return;
994 }
995 if pre_skip && !pre_skip_frame {
996 return;
997 }
998 if !pre_skip && skip {
999 // libaom: a skipped block never codes `seg_id_predicted`, and its
1000 // segment id is the spatial prediction.
1001 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0, fctx);
1002 let id = read_segment_id(dec, cdfs, mi_r, mi_c, true, fctx);
1003 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1004 return;
1005 }
1006 let id = if temporal_update {
1007 let ctx = seg_pred_ctx(mi_r, mi_c, fctx);
1008 let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0;
1009 SEG_PRED_HITS.with(|c| c.set(c.get() + 1));
1010 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted), fctx);
1011 if predicted {
1012 predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx)
1013 } else {
1014 read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
1015 }
1016 } else {
1017 read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
1018 };
1019 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1020}
1021
1022/// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags.
1023fn seg_pred_ctx(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> usize {
1024 // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and
1025 // so contribute 0) outside the tile -- the availability check here is
1026 // what keeps a previous tile's stamps out of this tile's context.
1027 let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
1028 let above = if mi_r > row0 {
1029 fctx.above_seg_pred.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))
1030 } else {
1031 0
1032 };
1033 let left = if mi_c > col0 {
1034 fctx.left_seg_pred.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))
1035 } else {
1036 0
1037 };
1038 usize::from(above + left)
1039}
1040
1041/// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update.
1042fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8, fctx: &crate::decode::FrameCtx) {
1043 fctx.above_seg_pred.with(|m| {
1044 let mut m = m.borrow_mut();
1045 for i in 0..w_mi {
1046 if let Some(cell) = m.get_mut(mi_c + i) {
1047 *cell = value;
1048 }
1049 }
1050 });
1051 fctx.left_seg_pred.with(|m| {
1052 let mut m = m.borrow_mut();
1053 for i in 0..h_mi {
1054 if let Some(cell) = m.get_mut(mi_r + i) {
1055 *cell = value;
1056 }
1057 }
1058 });
1059}
1060
1061// How many key-frame luma blocks resolved `smooth_neighbor` (spec
1062// `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after
1063// counter, proving a stream actually put a directional block next to a
1064// smooth-predicted neighbour rather than every block reading the (previously
1065// hardcoded `false`) edge-filter strength bucket unchanged.
1066thread_local! {
1067 static SMOOTH_LUMA_HITS: std::cell::Cell<usize> =
1068 const { std::cell::Cell::new(0) };
1069}
1070
1071/// Current value of [`SMOOTH_LUMA_HITS`].
1072#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1073pub(crate) fn smooth_luma_hits() -> usize {
1074 SMOOTH_LUMA_HITS.with(|c| c.get())
1075}
1076
1077thread_local! {
1078 /// lane-band46 r1: how many split-transform units answered their intra
1079 /// reach DIFFERENTLY under libaom's per-unit rules ([`Reach::of_tu`], the
1080 /// palette2 r12 fix) than the standalone-block lookup this decoder used to
1081 /// apply to them (class reach-is-per-transform-unit). Every hit is a
1082 /// transform unit whose above-right / below-left reference samples would
1083 /// be wrong without that fix.
1084 static SPLIT_TU_REACH_FIX_HITS: std::cell::Cell<usize> =
1085 const { std::cell::Cell::new(0) };
1086}
1087
1088/// Current value of [`SPLIT_TU_REACH_FIX_HITS`].
1089#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1090pub(crate) fn split_tu_reach_fix_hits() -> usize {
1091 SPLIT_TU_REACH_FIX_HITS.with(|c| c.get())
1092}
1093
1094/// [`Reach::of_tu`] for one transform unit, counting how often that per-unit
1095/// answer differs from the standalone-block answer the call sites used before
1096/// lane-palette2 r12 -- the counter a gate asserts on to prove a stream really
1097/// exercised the fix. `col_off`/`row_off` are in SAMPLES from the parent
1098/// block's top-left `(px, py)`.
1099#[allow(clippy::too_many_arguments)]
1100fn tu_reach(
1101 bw: usize,
1102 bh: usize,
1103 col_off: usize,
1104 row_off: usize,
1105 tx: usize,
1106 block: Reach,
1107 px: usize,
1108 py: usize,
1109 width: usize,
1110 height: usize, fctx: &crate::decode::FrameCtx,
1111) -> Reach {
1112 let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block);
1113 let standalone = Reach::of(tx, px + col_off, py + row_off, width, height, fctx);
1114 if fixed != standalone {
1115 SPLIT_TU_REACH_FIX_HITS.with(|c| c.set(c.get() + 1));
1116 }
1117 fixed
1118}
1119
1120// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12),
1121// across every call on the current thread -- lane-chroma r3's own before/after
1122// counter, proving a stream actually exercised chroma's smooth/paeth
1123// predictor (the previously-refused round-2 gap) rather than every block
1124// landing on DC/CFL/directional.
1125thread_local! {
1126 static SMOOTH_UV_HITS: std::cell::Cell<usize> =
1127 const { std::cell::Cell::new(0) };
1128}
1129
1130/// Current value of [`SMOOTH_UV_HITS`].
1131#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1132pub(crate) fn smooth_uv_hits() -> usize {
1133 SMOOTH_UV_HITS.with(|c| c.get())
1134}
1135
1136// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a
1137// full superblock walk over, across every call on the current thread --
1138// lane-tiles r2's own gate-blind-to-feature guard: a gate over a
1139// multi-tile stream must prove more than one tile actually fired, not just
1140// that the stream carried tile_info.cols > 1.
1141thread_local! {
1142 static TILE_HITS: std::cell::Cell<usize> =
1143 const { std::cell::Cell::new(0) };
1144}
1145/// Current value of [`TILE_HITS`].
1146#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1147pub(crate) fn tile_hits() -> usize {
1148 TILE_HITS.with(|c| c.get())
1149}
1150
1151// How many 4-pixel deblocking edge groups [`edge_params`] has actually
1152// selected for filtering, across every call on the current thread -- the same
1153// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1154// exercised `apply_deblock` rather than every edge landing on level 0.
1155thread_local! {
1156 static DEBLOCK_HITS: std::cell::Cell<usize> =
1157 const { std::cell::Cell::new(0) };
1158}
1159/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
1160/// mirroring stream.rs's `pictures_decoded` so the two dumps index
1161/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
1162static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize =
1163 std::sync::atomic::AtomicUsize::new(0);
1164
1165/// Current value of [`DEBLOCK_HITS`].
1166#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1167pub(crate) fn deblock_hits() -> usize {
1168 DEBLOCK_HITS.with(|c| c.get())
1169}
1170
1171// lane-defon r1: how many COMPOUND_REFERENCE blocks read a
1172// `UNIDIR_COMP_REFERENCE` pair (both references on the same temporal side,
1173// spec 5.11.25 `comp_reference_type == 0`) -- the gate's proof that a
1174// stream built with `--enable-onesided-comp=1` really exercised the
1175// `uni_comp_ref` alphabet rather than only bidirectional pairs.
1176thread_local! {
1177 static UNI_COMP_HITS: std::cell::Cell<usize> =
1178 const { std::cell::Cell::new(0) };
1179}
1180
1181/// Current value of [`UNI_COMP_HITS`].
1182#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1183pub(crate) fn uni_comp_hits() -> usize {
1184 UNI_COMP_HITS.with(|c| c.get())
1185}
1186
1187// lane-defon r1: how many blocks blended through a `COMPOUND_DIFFWTD` mask
1188// (`mc::diffwtd_mask`) -- the narrower half of `MASKED_COMPOUND_HITS`, the
1189// gate's proof that `--enable-diff-wtd-comp=1` reached the difference-weighted
1190// blend and not only the wedge arm.
1191thread_local! {
1192 static DIFFWTD_HITS: std::cell::Cell<usize> =
1193 const { std::cell::Cell::new(0) };
1194}
1195
1196/// Current value of [`DIFFWTD_HITS`].
1197#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1198pub(crate) fn diffwtd_hits() -> usize {
1199 DIFFWTD_HITS.with(|c| c.get())
1200}
1201
1202// lane-mcomp64 r1: how many blocks took the INFERRED `COMPOUND_DIFFWTD` arm --
1203// a block size where `av1_is_wedge_used` is false (64x64 is the only such size
1204// this decoder's square inter path reaches), so no `compound_type` symbol is
1205// coded at all. Strictly narrower than `DIFFWTD_HITS`, which also counts the
1206// coded-symbol DIFFWTD blocks at 8x8/16x16/32x32.
1207thread_local! {
1208 static DIFFWTD_INFERRED_HITS: std::cell::Cell<usize> =
1209 const { std::cell::Cell::new(0) };
1210}
1211
1212/// Current value of [`DIFFWTD_INFERRED_HITS`].
1213#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1214pub(crate) fn diffwtd_inferred_hits() -> usize {
1215 DIFFWTD_INFERRED_HITS.with(|c| c.get())
1216}
1217
1218// lane-defon r1: how many FORWARD KEYFRAMES were decoded -- a KEY frame coded
1219// with `show_frame == 0`, output later by a `show_existing_frame` header
1220// (aomenc `--enable-fwd-kf=1 --fwd-kf-dist=N`). Counted from
1221// `stream::decode_stream`, which is where the frame header is consumed; the
1222// gate's proof that the on-value really reached the bitstream rather than
1223// being dropped by the rate control.
1224thread_local! {
1225 static FWD_KF_HITS: std::cell::Cell<usize> =
1226 const { std::cell::Cell::new(0) };
1227}
1228
1229/// Current value of [`FWD_KF_HITS`].
1230#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1231pub(crate) fn fwd_kf_hits() -> usize {
1232 FWD_KF_HITS.with(|c| c.get())
1233}
1234
1235/// Records one decoded forward keyframe (see [`FWD_KF_HITS`]).
1236pub(crate) fn note_fwd_kf() {
1237 FWD_KF_HITS.with(|c| c.set(c.get() + 1));
1238}
1239
1240// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
1241// the block's own side, across every call on the current thread -- the same
1242// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1243// actually exercised a *split* transform under `TxMode::Select` rather than
1244// every block coincidentally resolving `depth=0` (indistinguishable from
1245// `TxMode::Largest` pixel-wise).
1246thread_local! {
1247 static TX_DEPTH_HITS: std::cell::Cell<usize> =
1248 const { std::cell::Cell::new(0) };
1249}
1250
1251// How many plain SQUARE intra blocks (lane-sqchroma r1) resolved a luma
1252// transform smaller than their own side (`tx_depth != 0`) while coding a
1253// chroma prediction other than `DC_PRED` -- the pair the square path's chroma
1254// only exercises with aomenc's tx-size search left ON (its default), which
1255// every older recipe in this file pins off. Counted at the block, so a stream
1256// where RD happened to give every split-transform block a DC chroma mode
1257// reads as zero rather than silently passing for free.
1258thread_local! {
1259 static SQ_CHROMA_TX_HITS: std::cell::Cell<usize> =
1260 const { std::cell::Cell::new(0) };
1261}
1262
1263/// Current value of [`SQ_CHROMA_TX_HITS`].
1264#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1265pub(crate) fn sq_chroma_tx_hits() -> usize {
1266 SQ_CHROMA_TX_HITS.with(|c| c.get())
1267}
1268
1269/// Current value of [`TX_DEPTH_HITS`].
1270#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1271pub(crate) fn tx_depth_hits() -> usize {
1272 TX_DEPTH_HITS.with(|c| c.get())
1273}
1274
1275// lane-txselect: how many `txfm_split` symbols an inter frame's var-tx tree
1276// read, and how many of those actually took the split, on the current thread
1277// -- the same before/after counter pattern as [`TX_DEPTH_HITS`], proving a
1278// stream exercised spec 5.11.17's `read_var_tx_size` rather than every block
1279// coincidentally coding one whole-block transform.
1280thread_local! {
1281 static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1282 static TXFM_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1283 // lane-inter4 r2: rectangular INTER residual coding -- how many rect
1284 // strips coded one whole-block rect transform unit, and how many split
1285 // their rect max transform into square sub-transforms.
1286 static RECT_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1287 static RECT_INTER_TXSPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1288 // lane-r14 r2: luma transform units of an inter strip with a 64-px axis
1289 // (64x32/32x64/64x16/16x64), whose coefficients are coded as the
1290 // truncated low-32 corner.
1291 static RECT64_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1292 // lane-rectres r1: whole-block luma transform units of a 32x32-level 1:4
1293 // inter strip, `[32x8, 8x32]`.
1294 static RECT32X8_INTER_TU_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1295 // lane-r14 r3: rectangular var-tx LEAVES, [32x16, 16x32].
1296 static VARTX_RECT_LEAF_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1297 // lane-inter16ab r4: rectangular var-tx leaves with a 4-px axis, [8x4, 4x8]
1298 // -- the `sub_tx_size_map[TX_16X4]` split leaves of a 16x16-level 1:4 strip.
1299 static VARTX_RECT_LEAF4_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1300 // lane-inter4 r3: 16x16-level PARTITION_HORZ / PARTITION_VERT on an inter
1301 // frame -- 16x8 and 8x16 inter leaves.
1302 static INTER_LEAF16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1303 static INTER_LEAF16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1304 // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits,
1305 // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] --
1306 // `decode_inter_block` already carries forty parameters and both are
1307 // frame-constant.
1308 // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit,
1309 // frame-constant like the two above and stashed the same way -- an intra
1310 // block inside an inter frame reads `use_filter_intra` under it.
1311}
1312
1313/// Current value of [`TXFM_SPLIT_READS`].
1314#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1315pub(crate) fn txfm_split_reads() -> usize {
1316 TXFM_SPLIT_READS.with(|c| c.get())
1317}
1318
1319/// Current value of [`TXFM_SPLIT_HITS`].
1320#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1321pub(crate) fn txfm_split_hits() -> usize {
1322 TXFM_SPLIT_HITS.with(|c| c.get())
1323}
1324
1325/// Current value of [`INTER_LEAF16_HORZ_HITS`] (lane-inter4 r3).
1326#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1327pub(crate) fn inter_leaf16_horz_hits() -> usize {
1328 INTER_LEAF16_HORZ_HITS.with(|c| c.get())
1329}
1330
1331/// Current value of [`INTER_LEAF16_VERT_HITS`] (lane-inter4 r3).
1332#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1333pub(crate) fn inter_leaf16_vert_hits() -> usize {
1334 INTER_LEAF16_VERT_HITS.with(|c| c.get())
1335}
1336
1337/// Current value of [`RECT_INTER_TU_HITS`] (lane-inter4 r2).
1338pub(crate) fn rect_inter_tu_hits() -> usize {
1339 RECT_INTER_TU_HITS.with(|c| c.get())
1340}
1341
1342/// Current value of [`RECT_INTER_TXSPLIT_HITS`] (lane-inter4 r2).
1343pub(crate) fn rect_inter_txsplit_hits() -> usize {
1344 RECT_INTER_TXSPLIT_HITS.with(|c| c.get())
1345}
1346
1347/// Current value of [`RECT64_INTER_TU_HITS`] (lane-r14 r2).
1348pub(crate) fn rect64_inter_tu_hits() -> usize {
1349 RECT64_INTER_TU_HITS.with(|c| c.get())
1350}
1351
1352/// Current value of [`RECT32X8_INTER_TU_HITS`] (lane-rectres r1): `[32x8, 8x32]`
1353/// whole-block luma units of a 32x32-level 1:4 inter strip.
1354pub(crate) fn rect32x8_inter_tu_hits() -> [usize; 2] {
1355 RECT32X8_INTER_TU_HITS.with(|c| c.get())
1356}
1357
1358/// Current value of [`VARTX_RECT_LEAF_HITS`] (lane-r14 r3): how many
1359/// rectangular var-tx leaf transform units were coded, `[32x16, 16x32]`.
1360pub(crate) fn vartx_rect_leaf_hits() -> [usize; 2] {
1361 VARTX_RECT_LEAF_HITS.with(|c| c.get())
1362}
1363
1364/// Current value of [`VARTX_RECT_LEAF4_HITS`] (lane-inter16ab r4): 8x4/4x8
1365/// split leaves of a 16x4/4x16 strip, `[8x4, 4x8]`.
1366pub(crate) fn vartx_rect_leaf4_hits() -> [usize; 2] {
1367 VARTX_RECT_LEAF4_HITS.with(|c| c.get())
1368}
1369
1370/// Records one rectangular var-tx leaf.
1371fn vartx_rect_leaf_hit(tw: usize, th: usize) {
1372 if crate::envflags::env_flag!("EC_VARTXLEAF") {
1373 eprintln!("EC_VARTXLEAF tw={tw} th={th}");
1374 }
1375 let cell = if tw.min(th) == 4 { &VARTX_RECT_LEAF4_HITS } else { &VARTX_RECT_LEAF_HITS };
1376 cell.with(|c| {
1377 let mut h = c.get();
1378 h[usize::from(th > tw)] += 1;
1379 c.set(h);
1380 });
1381}
1382
1383/// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/
1384/// [`ENABLE_FILTER_INTRA_INTER`].
1385pub(crate) fn set_inter_tx_mode(
1386 tx_select: bool,
1387 reduced_tx_set: bool,
1388 enable_filter_intra: bool, fctx: &crate::decode::FrameCtx,
1389) {
1390 fctx.tx_select_inter.with(|c| c.set(tx_select));
1391 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
1392 fctx.enable_filter_intra_inter.with(|c| c.set(enable_filter_intra));
1393}
1394
1395// How many `partition_w16` reads (a 16x16 block's own partition symbol, key
1396// intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a
1397// plain default-settings aomenc run over lavfi mandelbrot hits this arm on
1398// frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not
1399// the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real
1400// `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`,
1401// chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8
1402// path above).
1403thread_local! {
1404 static VERT_B_INTRA_HITS: std::cell::Cell<usize> =
1405 const { std::cell::Cell::new(0) };
1406}
1407
1408/// Current value of [`VERT_B_INTRA_HITS`].
1409#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1410pub(crate) fn vert_b_intra_hits() -> usize {
1411 VERT_B_INTRA_HITS.with(|c| c.get())
1412}
1413
1414// lane-ab16 r1: how many 16x16-level AB partitions fired, per arm, in
1415// `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order. Each arm is two
1416// 8x8 squares (`decode_leaf8`) plus one 16x8/8x16 strip (`decode_leaf_rect`,
1417// the non-skip coefficient path lane-rectx proved); the gate hard-asserts
1418// every arm separately so a run where aomenc's RD only picked one cannot
1419// pass as proof of four.
1420thread_local! {
1421 static AB16_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
1422}
1423
1424// [`AB16_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16).
1425thread_local! {
1426 /// 4x4 transform units decoded inside an 8x8 square of a
1427 /// `PARTITION_VERT_A`/`_B` -- the exact call that panicked before
1428 /// [`crate::encode::Reach::of_tu`] (lane-ab16 r2), so the gate can prove
1429 /// a real `--enable-tx-size-search=1` stream reaches it.
1430 static VERT_AB_TX4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1431}
1432
1433#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1434pub(crate) fn vert_ab_tx4_hits() -> usize {
1435 VERT_AB_TX4_HITS.with(std::cell::Cell::get)
1436}
1437
1438#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1439pub(crate) fn ab16_hits_by_arm() -> [usize; 4] {
1440 AB16_HITS.with(std::cell::Cell::get)
1441}
1442
1443fn bump_ab16(arm: usize) {
1444 AB16_HITS.with(|c| {
1445 let mut v = c.get();
1446 v[arm] += 1;
1447 c.set(v);
1448 });
1449}
1450
1451// How many `partition_w16` reads resolved to a plain `PARTITION_HORZ`/
1452// `PARTITION_VERT` (lane-rect16 r2): re-measuring after the VERT_B fix above
1453// showed mandelbrot's real first-hit blocker is this plain arm at mi=(0,7),
1454// not VERT_B (`refusal-names-a-correlate`; the VERT_B write-up's "frame 0's
1455// very first non-NONE/SPLIT symbol" claim was about decode ORDER within one
1456// superblock's z-order recursion, not raster mi position).
1457thread_local! {
1458 static HORZ_VERT_INTRA_HITS: std::cell::Cell<usize> =
1459 const { std::cell::Cell::new(0) };
1460}
1461
1462/// Current value of [`HORZ_VERT_INTRA_HITS`].
1463#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1464pub(crate) fn horz_vert_intra_hits() -> usize {
1465 HORZ_VERT_INTRA_HITS.with(|c| c.get())
1466}
1467
1468// How many blocks were decoded as a frame-edge rect strip -- the single
1469// coded half of a `PARTITION_HORZ`/`PARTITION_VERT` at the true frame edge
1470// (lane-oddh r1), i.e. a block living inside the 8px band of a frame whose
1471// height or width is 8 mod 16 (the user's 3840x1608 film). Intra and inter
1472// paths share the counter.
1473thread_local! {
1474 static EDGE_RECT_STRIP_HITS: std::cell::Cell<usize> =
1475 const { std::cell::Cell::new(0) };
1476}
1477
1478/// Current value of [`EDGE_RECT_STRIP_HITS`].
1479#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
1480pub(crate) fn edge_rect_strip_hits() -> usize {
1481 EDGE_RECT_STRIP_HITS.with(|c| c.get())
1482}
1483
1484// lane-interedge r1: frame-edge half strips on the INTER path, per partition
1485// level (64/32/16) x axis (HORZ at a bottom edge, VERT at a right edge). The
1486// index is `level_idx * 2 + axis` with `level_idx` 0=64, 1=32, 2=16 and
1487// `axis` 0=HORZ (`!has_rows`), 1=VERT (`!has_cols`). Both of the user's films
1488// are height mod 16 == 8, so every inter frame crosses these nodes.
1489thread_local! {
1490 static INTER_EDGE_STRIP_HITS: std::cell::Cell<[usize; 6]> =
1491 const { std::cell::Cell::new([0; 6]) };
1492}
1493
1494/// Bumps one bucket of [`INTER_EDGE_STRIP_HITS`].
1495pub(crate) fn bump_inter_edge_strip(idx: usize) {
1496 INTER_EDGE_STRIP_HITS.with(|c| {
1497 let mut v = c.get();
1498 v[idx] += 1;
1499 c.set(v);
1500 });
1501}
1502
1503// lane-edgeboth r1: how many partition nodes were coded as the BOTH-AXES-CUT
1504// forced split -- libaom `decode_partition` (decodeframe.c):
1505// `else if (!has_rows && !has_cols) partition = PARTITION_SPLIT;`, the one
1506// straddle case that reads NO symbol at all. Indexed by level:
1507// 0 = 16x16, 1 = 32x32, 2 = 64x64, 3 = 128x128; intra and inter share it.
1508thread_local! {
1509 static EDGE_BOTH_CUT_HITS: std::cell::Cell<[usize; 4]> =
1510 const { std::cell::Cell::new([0; 4]) };
1511}
1512
1513fn bump_edge_both_cut(level: usize) {
1514 EDGE_BOTH_CUT_HITS.with(|c| {
1515 let mut v = c.get();
1516 v[level] += 1;
1517 c.set(v);
1518 });
1519}
1520
1521/// Current value of [`INTER_EDGE_STRIP_HITS`] (`[h64, v64, h32, v32, h16, v16]`).
1522pub fn inter_edge_strip_hits() -> [usize; 6] {
1523 INTER_EDGE_STRIP_HITS.with(|c| c.get())
1524}
1525
1526/// Resets [`INTER_EDGE_STRIP_HITS`] -- a refused attempt must not carry hits
1527/// into the next one (class `counter-from-refused-stream`).
1528pub fn reset_inter_edge_strip_hits() {
1529 INTER_EDGE_STRIP_HITS.with(|c| c.set([0; 6]));
1530}
1531
1532/// Current value of [`EDGE_BOTH_CUT_HITS`] (`[16, 32, 64, 128]` levels).
1533#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1534pub(crate) fn edge_both_cut_hits() -> [usize; 4] {
1535 EDGE_BOTH_CUT_HITS.with(|c| c.get())
1536}
1537
1538/// Zeroes [`EDGE_BOTH_CUT_HITS`] so a gate can measure a per-attempt delta.
1539#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1540pub(crate) fn reset_edge_both_cut_hits() {
1541 EDGE_BOTH_CUT_HITS.with(|c| c.set([0; 4]));
1542}
1543
1544// How many HORZ/VERT intra strips resolved a SPLIT luma transform
1545// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) --
1546// the case every rect path here refused by name before, and the first
1547// refusal the user's ReelB extract (600s in) stops at.
1548thread_local! {
1549 static RECT_SPLIT_TX_HITS: std::cell::Cell<usize> =
1550 const { std::cell::Cell::new(0) };
1551}
1552
1553/// Current value of [`RECT_SPLIT_TX_HITS`].
1554#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1555pub(crate) fn rect_split_tx_hits() -> usize {
1556 RECT_SPLIT_TX_HITS.with(|c| c.get())
1557}
1558
1559// The subset of [`RECT_SPLIT_TX_HITS`] that is BOTH superblock-level (one
1560// side 64) AND split past the first depth, i.e. tiled more than one unit in
1561// each axis -- the only shape with a transform unit that has neighbours on
1562// two sides inside its own strip (`row_off > 0 && col_off > 0`), and the one
1563// no gate fired before lane-rectsplit r2 (the shared counter above also
1564// counts 32x32-level and depth-1 strips, so it cannot prove this case).
1565thread_local! {
1566 static RECT_SPLIT_SB_INTERIOR_TU_HITS: std::cell::Cell<usize> =
1567 const { std::cell::Cell::new(0) };
1568}
1569
1570/// Current value of [`RECT_SPLIT_SB_INTERIOR_TU_HITS`].
1571#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1572pub(crate) fn rect_split_sb_interior_tu_hits() -> usize {
1573 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.get())
1574}
1575
1576// Per-shape hit counts for the rect chroma transforms lane-rectchroma r1
1577// wired into [`decode_rect_split`] -- the shapes a split-transform strip's
1578// chroma half takes that had no coefficient tables before (index order:
1579// 32x8, 8x32, 8x4, 4x8). One counter per shape because a gate that only
1580// proves the pair it happens to hit cannot catch a transposed scan/context
1581// table (class scan-weights-cross-axis).
1582thread_local! {
1583 static RECT_SPLIT_CHROMA_SHAPE_HITS: std::cell::Cell<[usize; 4]> =
1584 const { std::cell::Cell::new([0; 4]) };
1585}
1586
1587/// Current value of [`RECT_SPLIT_CHROMA_SHAPE_HITS`] (32x8, 8x32, 8x4, 4x8).
1588#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1589pub(crate) fn rect_split_chroma_shape_hits() -> [usize; 4] {
1590 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| c.get())
1591}
1592
1593// How many HORZ/VERT intra strips actually predicted with filter intra
1594// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name
1595// ("this decoder predicts square-only") until `predict_filter_intra` took
1596// `bw`x`bh`.
1597thread_local! {
1598 static FILTER_INTRA_RECT_HITS: std::cell::Cell<usize> =
1599 const { std::cell::Cell::new(0) };
1600}
1601
1602/// Current value of [`FILTER_INTRA_RECT_HITS`].
1603#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1604pub(crate) fn filter_intra_rect_hits() -> usize {
1605 FILTER_INTRA_RECT_HITS.with(|c| c.get())
1606}
1607
1608// As [`FILTER_INTRA_RECT_HITS`], counting only the 32x32-level 1:4 strips
1609// (32x8/8x32, lane-fi32x8 r1) -- the shapes whose `use_filter_intra` symbol
1610// was never read at all before that round, so a gate needs to prove the flag
1611// fired at THAT shape and not at a 16x8 one somewhere else in the frame.
1612// Split by ORIENTATION: rows 8 (32x8) and 9 (8x32) of `cdf::FILTER_INTRA`
1613// carry different probabilities (18101 vs 20229), so a transposed pair is
1614// only caught by a gate that sees the flag fire on BOTH shapes (class
1615// scan-weights-cross-axis).
1616thread_local! {
1617 static FILTER_INTRA_RECT4_HORZ_HITS: std::cell::Cell<usize> =
1618 const { std::cell::Cell::new(0) };
1619 static FILTER_INTRA_RECT4_VERT_HITS: std::cell::Cell<usize> =
1620 const { std::cell::Cell::new(0) };
1621}
1622
1623/// Current value of [`FILTER_INTRA_RECT4_HORZ_HITS`] (32x8 strips).
1624#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1625pub(crate) fn filter_intra_rect4_horz_hits() -> usize {
1626 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.get())
1627}
1628
1629/// Current value of [`FILTER_INTRA_RECT4_VERT_HITS`] (8x32 strips).
1630#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1631pub(crate) fn filter_intra_rect4_vert_hits() -> usize {
1632 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.get())
1633}
1634
1635// How many rectangular transform units actually coded coefficients through
1636// [`read_coeffs_rect`] (`all_zero == 0`) -- lane-rect1d's measure that a gate
1637// exercised the rect coefficient reader at all rather than passing on
1638// all-skip blocks.
1639thread_local! {
1640 static RECT_COEFF_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1641 static RECT_CLASS1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1642}
1643
1644/// Current value of [`RECT_COEFF_TU_HITS`].
1645#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1646pub(crate) fn rect_coeff_tu_hits() -> usize {
1647 RECT_COEFF_TU_HITS.with(|c| c.get())
1648}
1649
1650/// Rectangular transform units whose resolved `tx_type` is a 1D class
1651/// (`V_DCT`/`H_DCT`) -- [`TX_CLASS1_HITS`]'s rect-only half, so a gate can
1652/// pin that the 1D-class-on-a-RECT-transform path fired rather than settling
1653/// for the square reader's own 1D types.
1654#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1655pub(crate) fn rect_class1_hits() -> usize {
1656 RECT_CLASS1_HITS.with(|c| c.get())
1657}
1658
1659// As [`FILTER_INTRA_RECT_HITS`], counting only the strips BELOW 16x16
1660// (8x16/16x8 leaves of a 16x16 HORZ/VERT partition, lane-fistrip r1) -- the
1661// shapes whose `use_filter_intra` symbol had no CDF class before this round.
1662// A gate asserting the wider counter would be satisfied by a 32x16 strip and
1663// prove nothing about the new shapes.
1664thread_local! {
1665 static FILTER_INTRA_RECT_SUB16_HITS: std::cell::Cell<usize> =
1666 const { std::cell::Cell::new(0) };
1667}
1668
1669/// Current value of [`FILTER_INTRA_RECT_SUB16_HITS`].
1670#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1671pub(crate) fn filter_intra_rect_sub16_hits() -> usize {
1672 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.get())
1673}
1674
1675// As [`FILTER_INTRA_RECT_SUB16_HITS`], one partition level further down:
1676// 4x8/8x4 leaves of an 8x8 HORZ/VERT (lane-fi8 r1). A gate on the sub16
1677// counter would be satisfied by a 16x8 strip and prove nothing here.
1678thread_local! {
1679 static FILTER_INTRA_RECT_SUB8_HITS: std::cell::Cell<usize> =
1680 const { std::cell::Cell::new(0) };
1681}
1682
1683/// Current value of [`FILTER_INTRA_RECT_SUB8_HITS`].
1684#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1685pub(crate) fn filter_intra_rect_sub8_hits() -> usize {
1686 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.get())
1687}
1688
1689// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
1690// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
1691// call on the current thread -- the same before/after counter pattern as
1692// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
1693// `eob_pt`/1D-neighbour context path rather than every block coincidentally
1694// landing on `DCT_DCT`.
1695thread_local! {
1696 static TX_CLASS1_HITS: std::cell::Cell<usize> =
1697 const { std::cell::Cell::new(0) };
1698}
1699
1700// How many `uv_mode` reads resolved to a directional chroma mode (neither
1701// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
1702// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1703// actually exercised chroma's own directional predictor.
1704thread_local! {
1705 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
1706 const { std::cell::Cell::new(0) };
1707}
1708
1709/// Current value of [`DIRECTIONAL_UV_HITS`].
1710#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1711pub(crate) fn directional_uv_hits() -> usize {
1712 DIRECTIONAL_UV_HITS.with(|c| c.get())
1713}
1714
1715// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
1716// something other than [`ANGLE_DELTA_ZERO`], across every call in the
1717// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
1718// proving a stream actually exercised a nonzero angle delta.
1719thread_local! {
1720 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
1721 const { std::cell::Cell::new(0) };
1722}
1723
1724// How many [`read_single_ref`] reads resolved to a reference other than
1725// `LAST_FRAME`, across every call on the current thread -- the same before/after
1726// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1727// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
1728// only other supported one so far) rather than every block coincidentally
1729// resolving `LAST_FRAME`.
1730thread_local! {
1731 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
1732 const { std::cell::Cell::new(0) };
1733}
1734
1735/// Current value of [`NON_LAST_REF_HITS`].
1736#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1737pub(crate) fn non_last_ref_hits() -> usize {
1738 NON_LAST_REF_HITS.with(|c| c.get())
1739}
1740
1741// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
1742// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
1743// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
1744// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
1745// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
1746// `GOLDEN_FRAME` draw it did not ask for.
1747thread_local! {
1748 static LAST2_HITS: std::cell::Cell<usize> =
1749 const { std::cell::Cell::new(0) };
1750}
1751thread_local! {
1752 static LAST3_HITS: std::cell::Cell<usize> =
1753 const { std::cell::Cell::new(0) };
1754}
1755thread_local! {
1756 static GOLDEN_HITS: std::cell::Cell<usize> =
1757 const { std::cell::Cell::new(0) };
1758}
1759thread_local! {
1760 static BWDREF_HITS: std::cell::Cell<usize> =
1761 const { std::cell::Cell::new(0) };
1762}
1763thread_local! {
1764 static ALTREF2_HITS: std::cell::Cell<usize> =
1765 const { std::cell::Cell::new(0) };
1766}
1767thread_local! {
1768 static ALTREF_HITS: std::cell::Cell<usize> =
1769 const { std::cell::Cell::new(0) };
1770}
1771
1772// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
1773// -- proves a `reference_select` stream actually reached a block that picked
1774// compound, not just that the header bit was set. Every such block is
1775// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
1776// so this only ever counts attempted reads, never a completed decode.
1777thread_local! {
1778 static COMP_MODE_HITS: std::cell::Cell<usize> =
1779 const { std::cell::Cell::new(0) };
1780}
1781
1782/// Current value of [`COMP_MODE_HITS`].
1783#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1784pub(crate) fn comp_mode_hits() -> usize {
1785 COMP_MODE_HITS.with(|c| c.get())
1786}
1787
1788// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
1789// use for, across every call on the current thread -- the same before/after
1790// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1791// exercised palette reconstruction rather than only reading and refusing the
1792// `palette_y_mode` symbol.
1793thread_local! {
1794 static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1795}
1796
1797/// Current value of [`PALETTE_HITS`].
1798#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1799pub(crate) fn palette_hits() -> usize {
1800 PALETTE_HITS.with(|c| c.get())
1801}
1802
1803// lane-tiles r12: of those, how many sat at their own TILE's left column --
1804// exactly the blocks whose palette cache/ctx must NOT see the previous tile's
1805// colours (`av1_get_palette_cache`'s `xd->left_mbmi == NULL`). A multi-tile
1806// palette gate that never hits one proves nothing about the tile guard.
1807thread_local! {
1808 static PALETTE_TILE_LEFT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1809}
1810
1811/// Current value of [`PALETTE_TILE_LEFT_HITS`].
1812#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1813pub(crate) fn palette_tile_left_hits() -> usize {
1814 PALETTE_TILE_LEFT_HITS.with(|c| c.get())
1815}
1816
1817// lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma
1818// palette use -- proves a stream actually reconstructed UV palette pixels,
1819// not just read and refused the `palette_uv_mode` symbol.
1820thread_local! {
1821 static PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1822}
1823
1824/// Current value of [`PALETTE_UV_HITS`].
1825#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1826pub(crate) fn palette_uv_hits() -> usize {
1827 PALETTE_UV_HITS.with(|c| c.get())
1828}
1829
1830// lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`])
1831// decoded a real palette-Y use -- proves the rect strip's own palette syntax
1832// (not just the square path's) actually fired.
1833thread_local! {
1834 static PALETTE_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1835}
1836
1837/// Current value of [`PALETTE_RECT_HITS`].
1838#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1839pub(crate) fn palette_rect_hits() -> usize {
1840 PALETTE_RECT_HITS.with(|c| c.get())
1841}
1842
1843// lane-palette2 r6: how many HORZ/VERT rect intra strips ran the
1844// [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] --
1845// i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in
1846// range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per
1847// RD, almost always refused-on-use because the block doesn't end up USING a
1848// palette -- see r5's report). This is the site the removed refusal
1849// ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it
1850// fired here whether or not the block picked a palette, so this is the
1851// counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost
1852// never observes.
1853thread_local! {
1854 static RECT_SCREEN_CONTENT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1855}
1856
1857/// Current value of [`RECT_SCREEN_CONTENT_HITS`].
1858#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1859pub(crate) fn rect_screen_content_hits() -> usize {
1860 RECT_SCREEN_CONTENT_HITS.with(|c| c.get())
1861}
1862
1863// lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a
1864// split luma transform (`logical_tx != side`) -- proves the per-TU index-map
1865// windowing actually ran, not just that the whole-block path stayed exact.
1866// Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16);
1867// first actually incremented in r7, when the refusal it guarded was lifted.
1868thread_local! {
1869 static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1870}
1871
1872thread_local! {
1873 /// lane-kf900 r4: rect intra strips that ACTUALLY use a palette -- the
1874 /// 1:4 shapes (32x8/8x32, 16x4/4x16) and the sub-16x16 2:1 leaves
1875 /// (16x8/8x16), the two shapes the lifted refusals named.
1876 static RECT4_PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1877}
1878
1879/// Current value of [`RECT4_PALETTE_HITS`].
1880#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1881pub(crate) fn rect4_palette_hits() -> usize {
1882 RECT4_PALETTE_HITS.with(|c| c.get())
1883}
1884
1885/// Current value of [`PALETTE_SPLIT_TX_HITS`].
1886#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1887pub(crate) fn palette_split_tx_hits() -> usize {
1888 PALETTE_SPLIT_TX_HITS.with(|c| c.get())
1889}
1890
1891thread_local! {
1892 /// lane-pal8 r1: square 8x8 LEAVES ([`decode_leaf8`]) that actually use a
1893 /// palette (Y or UV) -- the shape every 8-bit `--tune-content=screen`
1894 /// stream stopped on, since aomenc palettes square blocks at 8 bit and
1895 /// `--min-partition-size=8` puts them on this leaf path.
1896 static PALETTE_LEAF8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1897}
1898
1899/// Current value of [`PALETTE_LEAF8_HITS`].
1900#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1901pub(crate) fn palette_leaf8_hits() -> usize {
1902 PALETTE_LEAF8_HITS.with(|c| c.get())
1903}
1904
1905/// Zeroes [`PALETTE_LEAF8_HITS`] (per-attempt gate counting).
1906#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1907pub(crate) fn reset_palette_leaf8_hits() {
1908 PALETTE_LEAF8_HITS.with(|c| c.set(0));
1909}
1910
1911thread_local! {
1912 /// lane-pal8 r1: NON-SKIP palette blocks on a superblock-level (64-level)
1913 /// HORZ/VERT or 1:4 strip ([`decode_block_rect64`]) -- i.e. a palette
1914 /// block that also carries a real, corner-cropped luma transform.
1915 static PALETTE_SB_STRIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1916}
1917
1918/// Current value of [`PALETTE_SB_STRIP_HITS`].
1919#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1920pub(crate) fn palette_sb_strip_hits() -> usize {
1921 PALETTE_SB_STRIP_HITS.with(|c| c.get())
1922}
1923
1924/// Zeroes [`PALETTE_SB_STRIP_HITS`] (per-attempt gate counting).
1925#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1926pub(crate) fn reset_palette_sb_strip_hits() {
1927 PALETTE_SB_STRIP_HITS.with(|c| c.set(0));
1928}
1929
1930// lane-t900 r22: palette blocks reconstructed inside an INTER frame (the
1931// intra-in-inter path, `decode_inter_block`/`decode_inter_block8`) -- counted
1932// apart from [`PALETTE_HITS`] so a witness gate can prove the INTER-frame
1933// capability rather than the key frame's, which every screen stream also
1934// carries.
1935thread_local! {
1936 static INTRA_IN_INTER_PALETTE_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1937 static INTRA_IN_INTER_PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1938}
1939
1940// lane-t900 r23: as [`INTRA_IN_INTER_PALETTE_Y_HITS`], narrowed to the 8x8
1941// LEAF site ([`decode_inter_block8`]'s intra arm) -- the >=16 site fires the
1942// shared counter too, so only this one proves a gate really reached the leaf
1943// where the refusal used to sit.
1944thread_local! {
1945 static INTER8_PALETTE_HITS: std::cell::Cell<(usize, usize)> =
1946 const { std::cell::Cell::new((0, 0)) };
1947}
1948
1949/// Current values of the 8x8-leaf intra-in-inter palette counters, `(y, uv)`.
1950pub(crate) fn inter8_palette_hits() -> (usize, usize) {
1951 INTER8_PALETTE_HITS.with(std::cell::Cell::get)
1952}
1953
1954/// Current values of the two intra-in-inter palette counters, `(y, uv)`.
1955pub(crate) fn intra_in_inter_palette_hits() -> (usize, usize) {
1956 (
1957 INTRA_IN_INTER_PALETTE_Y_HITS.with(|c| c.get()),
1958 INTRA_IN_INTER_PALETTE_UV_HITS.with(|c| c.get()),
1959 )
1960}
1961
1962// lane-hgkf r2: SKIPPED intra blocks whose `tx_depth` split the luma transform
1963// and which are therefore predicted one transform unit at a time (a skipped
1964// block codes no coefficients, so nothing else in the stream witnesses this
1965// path -- only the pixels do).
1966thread_local! {
1967 static SKIP_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1968}
1969
1970/// Current value of [`SKIP_SPLIT_TX_HITS`] (blocks, not units).
1971pub fn skip_split_tx_hits() -> usize {
1972 SKIP_SPLIT_TX_HITS.with(|c| c.get())
1973}
1974
1975/// Zeroes [`SKIP_SPLIT_TX_HITS`] before a gate's own decode attempt.
1976pub fn reset_skip_split_tx_hits() {
1977 SKIP_SPLIT_TX_HITS.with(|c| c.set(0));
1978}
1979
1980// lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth`
1981// symbol split their luma transform, bucketed by block side (8, 16, 32, 64) --
1982// the gate's proof that the lifted path actually ran, per size.
1983thread_local! {
1984 static INTRA_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 4]> =
1985 const { std::cell::Cell::new([0; 4]) };
1986}
1987
1988/// Current value of [`INTRA_IN_INTER_SPLIT_TX_HITS`], indexed 8/16/32/64.
1989#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1990pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] {
1991 INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
1992}
1993
1994 /// A just-decoded palette-Y block's own predicted pixels
1995 /// (`side*side`, row-major, `colors[map[i]]`), consumed by
1996 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
1997 /// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
1998 /// per-block override through `read_plane`'s two dozen call sites is the
1999 /// alternative this avoids). Always empty again once that call consumes
2000 /// it (`.take()`), so a non-palette block's own `reconstruct` call never
2001 /// sees stale state.
2002
2003
2004/// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
2005/// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a
2006/// site whose reconstruct never runs would be picked up by the NEXT block's
2007/// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
2008/// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
2009#[track_caller]
2010fn set_palette_pred(buf: Vec<u16>, fctx: &crate::decode::FrameCtx) {
2011 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
2012 let stale = fctx.palette_pred.with(|c| c.borrow().is_some());
2013 eprintln!(
2014 "PALSET len={} stale={stale} at {}",
2015 buf.len(),
2016 std::panic::Location::caller()
2017 );
2018 }
2019 fctx.palette_pred.with(|c| *c.borrow_mut() = Some(buf));
2020}
2021
2022#[track_caller]
2023fn take_palette_pred(fctx: &crate::decode::FrameCtx) -> Option<Vec<u16>> {
2024 let got = fctx.palette_pred.with(|c| c.borrow_mut().take());
2025 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
2026 eprintln!(
2027 "PALTAKE len={:?} at {}",
2028 got.as_ref().map(Vec::len),
2029 std::panic::Location::caller()
2030 );
2031 }
2032 got
2033}
2034
2035/// The luma window a `UV_CFL_PRED` chroma block averages its AC signal over
2036/// (lane-wave1 step (i)). Parse records the window; [`flush_recon`] reads the
2037/// pixels, because at parse time this block's own luma is still queued.
2038#[derive(Clone, Copy, Debug)]
2039pub(crate) struct CflSrc {
2040 px: usize,
2041 py: usize,
2042 bw: usize,
2043 bh: usize,
2044 /// Which averager the parse site asked for -- [`cfl_ac_q3_rect`] and
2045 /// [`cfl_ac_q3`] are not the same function at `bw == bh`.
2046 rect: bool,
2047}
2048
2049fn cfl_src(px: usize, py: usize, side: usize) -> CflSrc {
2050 CflSrc { px, py, bw: side, bh: side, rect: false }
2051}
2052
2053fn cfl_src_rect(px: usize, py: usize, bw: usize, bh: usize) -> CflSrc {
2054 CflSrc { px, py, bw, bh, rect: true }
2055}
2056
2057/// lane-wave1 step (i): the pixel-writing half of block decoding, recorded
2058/// instead of executed. Each variant is the resolved argument tuple of the
2059/// `PlaneBuf::reconstruct*` call it replaces, so replaying the queue in push
2060/// order performs exactly the same writes in exactly the same order --
2061/// entropy parsing no longer touches the frame's own planes (except the two
2062/// sites named in [`flush_recon`]'s doc), which is what lets step (ii) run
2063/// the replay on a superblock-row wavefront worker.
2064/// The dequantization + inverse transform of one transform unit, kept as its
2065/// INPUTS so that a recorded write carries the work instead of its result
2066/// (lane-wave3): at `EC_AV1_RECON_THREADS > 1` the transform then runs on the
2067/// recon worker, not on the parsing thread. `stride == 0` means the dense
2068/// `w x h` residual; otherwise it is re-laid into the `stride x stride` grid
2069/// `reconstruct_mc_rect` reads both of its buffers at.
2070#[derive(Clone, Copy)]
2071pub(crate) struct TxParams {
2072 pub(crate) w: usize,
2073 pub(crate) h: usize,
2074 pub(crate) bit_depth: u8,
2075 pub(crate) q_idx: i32,
2076 pub(crate) dc_delta: i32,
2077 pub(crate) ac_delta: i32,
2078 pub(crate) tx_type: TxType,
2079 pub(crate) stride: usize,
2080}
2081
2082impl TxParams {
2083 /// The one copy of the produce-the-residual code: the inline path calls it
2084 /// on the parse thread, the wavefront worker calls it on its own, so both
2085 /// are the same function on the same inputs and byte-identical.
2086 fn run(self, grid: &[i32]) -> Vec<i32> {
2087 let residual = dequant_and_inverse_typed_wh(
2088 grid, self.w, self.h, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta,
2089 self.tx_type,
2090 );
2091 if self.stride == 0 {
2092 return residual;
2093 }
2094 let mut strided = vec![0i32; self.stride * self.stride];
2095 for row in 0..self.h {
2096 strided[row * self.stride..][..self.w]
2097 .copy_from_slice(&residual[row * self.w..][..self.w]);
2098 }
2099 strided
2100 }
2101}
2102
2103/// A recorded write's residual: already transformed, or the coefficients and
2104/// [`TxParams`] the worker transforms itself.
2105pub(crate) enum Residual {
2106 Done(Vec<i32>),
2107 Coeffs(TxParams, Vec<i32>),
2108}
2109
2110impl Residual {
2111 fn resolve(self) -> Vec<i32> {
2112 match self {
2113 Self::Done(v) => v,
2114 Self::Coeffs(p, grid) => p.run(&grid),
2115 }
2116 }
2117}
2118
2119/// Where a recorded motion-compensated write reads its prediction from.
2120///
2121/// lane-wave4: a block's whole-block prediction (mc + warp + interintra) is
2122/// the parse thread's single biggest reconstruction cost, so at
2123/// `EC_AV1_RECON_THREADS > 1` it is not built at parse at all: the block
2124/// pushes a [`ReconOp::Pred`] carrying the build as a closure, the worker
2125/// runs it into its own three-plane slot, and every transform unit of that
2126/// block then reads its window out of that slot ([`Pred::Cur`]).
2127#[derive(Clone, Copy)]
2128pub(crate) enum Pred<'a> {
2129 /// A prediction the parse thread already built. `stride == 0` means "the
2130 /// reader's own `stride` argument", which is every pre-lane-wave4 site.
2131 Inline(&'a [u16], usize),
2132 /// The current block's deferred prediction: plane, its stride, and this
2133 /// unit's offset into it.
2134 Cur { plane: usize, stride: usize, off: usize },
2135}
2136
2137impl<'a> Pred<'a> {
2138 fn dense(buf: &'a [u16]) -> Self {
2139 Self::Inline(buf, 0)
2140 }
2141 /// The same prediction read at an explicit stride.
2142 fn view(self, stride: usize) -> Self {
2143 match self {
2144 Self::Inline(b, _) => Self::Inline(b, stride),
2145 Self::Cur { plane, off, .. } => Self::Cur { plane, stride, off },
2146 }
2147 }
2148 /// The materialised buffer and the stride to read it at (`stride` is the
2149 /// reader's own when this prediction was built dense); `None` for a
2150 /// deferred prediction, which only a recorded op can carry.
2151 fn inline(self, stride: usize) -> Option<(&'a [u16], usize)> {
2152 match self {
2153 Self::Inline(b, s) => Some((b, if s == 0 { stride } else { s })),
2154 Self::Cur { .. } => None,
2155 }
2156 }
2157 /// This prediction's window starting `n` samples in.
2158 fn offset(self, n: usize) -> Self {
2159 match self {
2160 Self::Inline(b, s) => Self::Inline(&b[n..], s),
2161 Self::Cur { plane, stride, off } => Self::Cur { plane, stride, off: off + n },
2162 }
2163 }
2164}
2165
2166/// [`Pred`], resolved into what a recorded op carries.
2167pub(crate) enum PredSrc {
2168 Owned(Vec<u16>),
2169 /// A window of the block prediction: its plane, its offset, and the
2170 /// stride it is read at -- which is the block's, not necessarily the
2171 /// op's (a transform unit's residual stays dense, so the worker takes
2172 /// its window out of the block prediction itself).
2173 Cur { plane: usize, off: usize, src: usize },
2174}
2175
2176/// One block's whole-block prediction build, deferred to a recon worker.
2177///
2178/// The closure borrows the tile's reference pictures and its own frame-level
2179/// tables; [`WaveGuard`] joins every worker before the tile decoder returns,
2180/// so those borrows outlive it -- the [`ReconPlanes`] trade-off, stated once
2181/// here for the closure's `'static`/`Send` laundering in [`push_pred`].
2182pub(crate) struct PredBuild(
2183 Box<
2184 dyn FnOnce(
2185 &mut PlaneBuf<'static>,
2186 &mut PlaneBuf<'static>,
2187 &mut PlaneBuf<'static>,
2188 &crate::decode::FrameCtx,
2189 ) -> [Vec<u16>; 3],
2190 >,
2191);
2192
2193// SAFETY: see [`PredBuild`] -- the captured borrows are read-only reference
2194// pictures and frame tables, and the closure runs on exactly one worker.
2195#[allow(unsafe_code)]
2196unsafe impl Send for PredBuild {}
2197
2198/// `true` when this tile's writes are recorded for the wavefront instead of
2199/// performed at the push site, i.e. when a prediction may be deferred.
2200fn recon_deferred(fctx: &crate::decode::FrameCtx) -> bool {
2201 fctx.recon_planes.with(std::cell::Cell::get).is_none()
2202}
2203
2204/// Records one block's prediction build for the worker that reconstructs it.
2205#[allow(unsafe_code)]
2206fn push_pred<'a>(
2207 fctx: &crate::decode::FrameCtx,
2208 f: impl FnOnce(
2209 &mut PlaneBuf<'static>,
2210 &mut PlaneBuf<'static>,
2211 &mut PlaneBuf<'static>,
2212 &crate::decode::FrameCtx,
2213 ) -> [Vec<u16>; 3]
2214 + 'a,
2215) {
2216 type Built = [Vec<u16>; 3];
2217 type Dyn<'x> = dyn FnOnce(
2218 &mut PlaneBuf<'static>,
2219 &mut PlaneBuf<'static>,
2220 &mut PlaneBuf<'static>,
2221 &crate::decode::FrameCtx,
2222 ) -> Built
2223 + 'x;
2224 let boxed: Box<Dyn<'a>> = Box::new(f);
2225 // SAFETY: see [`PredBuild`] -- every worker is joined by [`WaveGuard`]
2226 // before the borrows the closure holds go out of scope.
2227 let boxed: Box<Dyn<'static>> = unsafe { std::mem::transmute(boxed) };
2228 push_op(fctx, ReconOp::Pred(PredBuild(boxed)));
2229}
2230
2231pub(crate) enum ReconOp {
2232 /// lane-wave4: build this block's prediction into the worker's slot.
2233 Pred(PredBuild),
2234 Intra {
2235 plane: usize,
2236 x: usize,
2237 y: usize,
2238 bw: usize,
2239 bh: usize,
2240 /// `true` when the parse site called `reconstruct_rect` (whose
2241 /// `edges_rect` differs from `edges` even at `bw == bh`).
2242 rect: bool,
2243 mode: usize,
2244 angle_delta: i32,
2245 reach: Reach,
2246 residual: Residual,
2247 cfl: Option<(i32, CflSrc)>,
2248 filter_intra: Option<usize>,
2249 smooth_neighbor: bool,
2250 /// The palette/intrabc prediction override, taken off
2251 /// [`FrameCtx::palette_pred`] at PUSH time (parse order), never read
2252 /// from that slot by the replay.
2253 pred: Option<Vec<u16>>,
2254 },
2255 Mc {
2256 plane: usize,
2257 x: usize,
2258 y: usize,
2259 stride: usize,
2260 w: usize,
2261 h: usize,
2262 prediction: PredSrc,
2263 residual: Residual,
2264 },
2265}
2266
2267/// The three planes of the tile currently being decoded, as raw pointers.
2268///
2269/// corner-cut: at one reconstruction thread a recorded write must cost
2270/// nothing -- deferring it to the end of the superblock is +1.2%
2271/// instructions and +4.5% wall on 4K, because the residual is written at
2272/// parse and read back cache-cold at replay. So the recorded op is performed
2273/// at the push site instead, through the pointers the tile decoder registers
2274/// once ([`ReconInline`]), which is the same thread, the same order and the
2275/// same writes as before lane-wave1 -- but the `&mut PlaneBuf` the parse
2276/// stack still holds aliases them, exactly the [`crate::par::Shared`]
2277/// trade-off (Miri's stacked borrows would flag both). The upgrade path is
2278/// threading the three planes down every `read_plane`/`read_inter_plane`
2279/// call site (~40) so the push site owns the borrow it writes through.
2280#[derive(Clone, Copy)]
2281pub(crate) struct ReconPlanes(
2282 *mut PlaneBuf<'static>,
2283 *mut PlaneBuf<'static>,
2284 *mut PlaneBuf<'static>,
2285);
2286
2287// SAFETY: a `FrameCtx` sent to another thread (a frame worker, or
2288// [`filter_ctx_copy`]) is always one whose guard is not installed, so the
2289// value travelling is `None`; the pointers never leave the tile decoder's
2290// own thread.
2291#[allow(unsafe_code)]
2292unsafe impl Send for ReconPlanes {}
2293// SAFETY: the wavefront's workers share one `ReconPlanes` and write provably
2294// disjoint superblocks of it (see [`WaveState`]) -- the [`crate::par::Shared`]
2295// contract, one superblock per band instead of one row band.
2296#[allow(unsafe_code)]
2297unsafe impl Sync for ReconPlanes {}
2298
2299/// Registers the tile's planes for inline reconstruction and unregisters them
2300/// on every exit from the tile decoder, including the `?` ones -- a stale
2301/// pointer here would outlive the planes, since [`FrameCtx`] outlives the
2302/// tile.
2303pub(crate) struct ReconInline<'a>(&'a crate::decode::FrameCtx);
2304
2305#[allow(unsafe_code)]
2306impl<'a> ReconInline<'a> {
2307 /// Installs the guard for this tile when reconstruction is inline
2308 /// (`EC_AV1_RECON_THREADS == 1`, the default); `None` hands every write
2309 /// to the queue instead, for the wavefront workers to replay.
2310 fn install(
2311 fctx: &'a crate::decode::FrameCtx,
2312 y: &mut PlaneBuf<'static>,
2313 u: &mut PlaneBuf<'static>,
2314 v: &mut PlaneBuf<'static>,
2315 ) -> Option<Self> {
2316 if crate::par::recon_threads() != 1 {
2317 return None;
2318 }
2319 // SAFETY: the planes are locals of the tile decoder and outlive the
2320 // guard, which is dropped on every exit from it (including `?`); see
2321 // [`ReconPlanes`] for the aliasing trade-off.
2322 let planes = ReconPlanes(
2323 std::ptr::from_mut(y),
2324 std::ptr::from_mut(u),
2325 std::ptr::from_mut(v),
2326 );
2327 fctx.recon_planes.with(|c| c.set(Some(planes)));
2328 Some(Self(fctx))
2329 }
2330}
2331
2332impl Drop for ReconInline<'_> {
2333 fn drop(&mut self) {
2334 self.0.recon_planes.with(|c| c.set(None));
2335 }
2336}
2337
2338#[allow(unsafe_code)]
2339fn push_op(fctx: &crate::decode::FrameCtx, op: ReconOp) {
2340 if let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) {
2341 // SAFETY: see [`ReconPlanes`] -- one thread, and the write is the one
2342 // the parse site would have performed itself before lane-wave1.
2343 unsafe { exec_op(op, &mut *y, &mut *u, &mut *v, &mut Default::default(), fctx) };
2344 return;
2345 }
2346 fctx.recon_ops.with(|c| c.borrow_mut().push(op));
2347}
2348
2349/// lane-wave1 step (ii): the superblock-row wavefront a tile's recorded
2350/// writes are reconstructed on when `EC_AV1_RECON_THREADS > 1`.
2351///
2352/// The parser keeps parsing and never touches the planes; each superblock's
2353/// drained `Vec<ReconOp>` becomes one job, keyed by the superblock's own
2354/// `(row, column)` inside the tile (128x128 superblocks are one job for all
2355/// four of their 64x64 visits, since a 128 block writes across quadrants).
2356/// A worker may start job `(r, c)` once `(r - 1, min(c + 1, last_col))` and
2357/// `(r, c - 1)` are complete -- the classic wavefront rule, which covers
2358/// every pixel an intra predictor can read (its edges reach one block right
2359/// along the row above and one block down the column to the left, both
2360/// inside those two neighbours) and every CfL AC read (this block's own
2361/// luma, written by this same job). Jobs are handed out in raster order, so
2362/// the oldest outstanding one always has its dependencies met: no deadlock.
2363///
2364/// Gate counters incremented inside `reconstruct*`/`intra`/`mc` are
2365/// `thread_local!` and miss every worker, which is why the default is 1.
2366pub(crate) struct WaveState {
2367 q: std::sync::Mutex<WaveQueue>,
2368 cv: std::sync::Condvar,
2369 planes: ReconPlanes,
2370 /// The two [`FrameCtx`] fields reconstruction reads (`sample_max` is
2371 /// `bit_depth`'s; everything else a `reconstruct*` needs is in the op).
2372 bit_depth: u8,
2373 enable_edge_filter: bool,
2374 last_col: usize,
2375}
2376
2377struct WaveQueue {
2378 /// Queued jobs per superblock ROW, in column order (lane-wave5). Only a
2379 /// row's front job can ever be runnable -- a job waits on its own left
2380 /// neighbour -- so a worker takes the lowest row whose front job's
2381 /// dependencies are met. Popping the raster-oldest job instead (what
2382 /// this replaced) put every worker on the SAME row, where the wavefront
2383 /// rule serialises them, which is why 4 workers ran the tile at 1.2x.
2384 rows: Vec<std::collections::VecDeque<(usize, Vec<ReconOp>)>>,
2385 /// Jobs sitting in `rows`, so a worker knows the queue is empty without
2386 /// walking it.
2387 queued: usize,
2388 /// Per superblock row, the last column reconstructed (-1 = none yet).
2389 done: Vec<isize>,
2390 /// Jobs popped but not finished -- what [`wave_barrier`] waits out.
2391 active: usize,
2392 closed: bool,
2393}
2394
2395impl WaveQueue {
2396 /// The lowest-row queued job whose wavefront dependencies are satisfied,
2397 /// or `None` (with the blocking condition counted when instrumented).
2398 fn take_runnable(&mut self, last_col: usize, stats: bool) -> Option<(usize, usize, Vec<ReconOp>)> {
2399 let mut blocked: Option<bool> = None;
2400 for r in 0..self.rows.len() {
2401 let Some(front) = self.rows[r].front() else {
2402 continue;
2403 };
2404 let c = front.0;
2405 let above = r == 0 || self.done[r - 1] >= (c + 1).min(last_col) as isize;
2406 let left = c == 0 || self.done[r] >= c as isize - 1;
2407 if above && left {
2408 let (c, ops) = self.rows[r].pop_front().expect("front checked above");
2409 self.queued -= 1;
2410 return Some((r, c, ops));
2411 }
2412 if blocked.is_none() {
2413 blocked = Some(above);
2414 }
2415 }
2416 if stats {
2417 match blocked {
2418 Some(true) => WS_BLOCK_LEFT.fetch_add(1, Relaxed),
2419 Some(false) => WS_BLOCK_ABOVE.fetch_add(1, Relaxed),
2420 None => 0,
2421 };
2422 }
2423 None
2424 }
2425}
2426
2427/// lane-wave5 instrumentation, on `EC_AV1_WAVE_STATS=1`: where a recon
2428/// worker's time goes (busy replaying, waiting for a dependency, idle on an
2429/// empty queue), how far ahead the parse thread is, and how often the two
2430/// parse-time pixel reads barrier the wavefront. Cumulative for the process,
2431/// dumped by every [`WaveGuard`] drop, so the LAST line of a decode is the
2432/// whole run.
2433const WS_SLOTS: usize = 16;
2434use std::sync::atomic::AtomicU64;
2435use std::sync::atomic::Ordering::Relaxed;
2436static WS_JOBS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2437static WS_OPS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2438static WS_BUSY: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2439static WS_WAIT: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2440static WS_BLOCK_ABOVE: AtomicU64 = AtomicU64::new(0);
2441static WS_BLOCK_LEFT: AtomicU64 = AtomicU64::new(0);
2442/// Parse-thread time between two submits, i.e. everything parse still does
2443/// itself (symbol decode plus the predictions not deferred).
2444static WS_PARSE: AtomicU64 = AtomicU64::new(0);
2445/// Parse-thread time spent waiting for the wavefront: at [`wave_barrier`]
2446/// (the intrabc/interintra reads) and at the tile's end.
2447static WS_BARRIER: AtomicU64 = AtomicU64::new(0);
2448static WS_BARRIERS: AtomicU64 = AtomicU64::new(0);
2449static WS_DRAIN: AtomicU64 = AtomicU64::new(0);
2450static WS_TILES: AtomicU64 = AtomicU64::new(0);
2451
2452fn wave_stats() -> bool {
2453 static ON: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
2454 match ON.load(Relaxed) {
2455 0 => {
2456 let on = crate::envflags::var("EC_AV1_WAVE_STATS")
2457 .map(|v| v.trim() == "1")
2458 .unwrap_or(false);
2459 ON.store(1 + u8::from(on), Relaxed);
2460 on
2461 }
2462 n => n == 2,
2463 }
2464}
2465
2466fn wave_stats_dump() {
2467 let ms = |n: u64| n as f64 / 1e6;
2468 let mut s = format!("wave_stats tiles={}", WS_TILES.load(Relaxed));
2469 for i in 0..WS_SLOTS {
2470 let jobs = WS_JOBS[i].load(Relaxed);
2471 if jobs == 0 {
2472 continue;
2473 }
2474 s += &format!(
2475 " | w{i} jobs={jobs} ops/job={:.1} busy={:.0}ms wait={:.0}ms wait/job={:.0}us",
2476 WS_OPS[i].load(Relaxed) as f64 / jobs as f64,
2477 ms(WS_BUSY[i].load(Relaxed)),
2478 ms(WS_WAIT[i].load(Relaxed)),
2479 WS_WAIT[i].load(Relaxed) as f64 / jobs as f64 / 1e3,
2480 );
2481 }
2482 s += &format!(
2483 " | parse={:.0}ms barrier={:.0}ms/{} drain={:.0}ms block_above={} block_left={}",
2484 ms(WS_PARSE.load(Relaxed)),
2485 ms(WS_BARRIER.load(Relaxed)),
2486 WS_BARRIERS.load(Relaxed),
2487 ms(WS_DRAIN.load(Relaxed)),
2488 WS_BLOCK_ABOVE.load(Relaxed),
2489 WS_BLOCK_LEFT.load(Relaxed),
2490 );
2491 eprintln!("{s}");
2492}
2493
2494#[allow(unsafe_code)]
2495fn wave_worker(st: &WaveState, idx: usize) {
2496 let fctx = FrameCtx::new();
2497 fctx.bit_depth.set(st.bit_depth);
2498 fctx.enable_edge_filter.set(st.enable_edge_filter);
2499 let stats = wave_stats();
2500 let slot = idx.min(WS_SLOTS - 1);
2501 loop {
2502 let t0 = std::time::Instant::now();
2503 let mut q = st.q.lock().unwrap();
2504 let (r, c, ops) = loop {
2505 if let Some(job) = q.take_runnable(st.last_col, stats) {
2506 break job;
2507 }
2508 if q.closed && q.queued == 0 {
2509 return;
2510 }
2511 q = st.cv.wait(q).unwrap();
2512 };
2513 q.active += 1;
2514 drop(q);
2515 if stats {
2516 WS_WAIT[slot].fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
2517 WS_JOBS[slot].fetch_add(1, Relaxed);
2518 WS_OPS[slot].fetch_add(ops.len() as u64, Relaxed);
2519 }
2520 let t1 = std::time::Instant::now();
2521 let ReconPlanes(y, u, v) = st.planes;
2522 // SAFETY: this job writes only superblock (r, c)'s own pixels, and
2523 // every superblock that could have written or be reading them is
2524 // complete by the wavefront rule above.
2525 let mut cur: [Vec<u16>; 3] = Default::default();
2526 unsafe {
2527 for op in ops {
2528 exec_op(op, &mut *y, &mut *u, &mut *v, &mut cur, &fctx);
2529 }
2530 }
2531 if stats {
2532 WS_BUSY[slot].fetch_add(t1.elapsed().as_nanos() as u64, Relaxed);
2533 }
2534 let mut q = st.q.lock().unwrap();
2535 q.done[r] = c as isize;
2536 q.active -= 1;
2537 st.cv.notify_all();
2538 }
2539}
2540
2541/// Installs the wavefront for one tile and joins its workers on every exit
2542/// from the tile decoder, including the `?` ones -- the jobs hold raw
2543/// pointers into the tile's planes, so no worker may outlive them.
2544/// (lane-pool1: the workers come from this thread's persistent pool, so a
2545/// tile costs a batch submit rather than `EC_AV1_RECON_THREADS` fresh threads
2546/// with fresh scratch.)
2547pub(crate) struct WaveGuard<'a>(
2548 &'a crate::decode::FrameCtx,
2549 Option<crate::par::Batch<'static>>,
2550);
2551
2552#[allow(unsafe_code)]
2553impl<'a> WaveGuard<'a> {
2554 fn install(
2555 fctx: &'a crate::decode::FrameCtx,
2556 y: &mut PlaneBuf<'static>,
2557 u: &mut PlaneBuf<'static>,
2558 v: &mut PlaneBuf<'static>,
2559 rows: usize,
2560 cols: usize,
2561 ) -> Option<Self> {
2562 let threads = crate::par::recon_threads();
2563 if threads == 1 || rows == 0 || cols == 0 {
2564 return None;
2565 }
2566 let st = std::sync::Arc::new(WaveState {
2567 q: std::sync::Mutex::new(WaveQueue {
2568 rows: (0..rows).map(|_| std::collections::VecDeque::new()).collect(),
2569 queued: 0,
2570 done: vec![-1; rows],
2571 active: 0,
2572 closed: false,
2573 }),
2574 cv: std::sync::Condvar::new(),
2575 // SAFETY: the planes are locals of the tile decoder and outlive
2576 // this guard, which joins every worker in `drop`.
2577 planes: ReconPlanes(
2578 std::ptr::from_mut(y),
2579 std::ptr::from_mut(u),
2580 std::ptr::from_mut(v),
2581 ),
2582 bit_depth: fctx.bit_depth.with(std::cell::Cell::get),
2583 enable_edge_filter: fctx.enable_edge_filter.with(std::cell::Cell::get),
2584 last_col: cols - 1,
2585 });
2586 let batch = crate::par::Batch::new("ec-av1-recon");
2587 for idx in 0..threads {
2588 let st = std::sync::Arc::clone(&st);
2589 batch.submit(move || wave_worker(&st, idx));
2590 }
2591 fctx.wave.with(|w| *w.borrow_mut() = Some(st));
2592 fctx.wave_mark.with(|c| c.set(Some(std::time::Instant::now())));
2593 Some(Self(fctx, Some(batch)))
2594 }
2595}
2596
2597impl Drop for WaveGuard<'_> {
2598 fn drop(&mut self) {
2599 let st = self.0.wave.with(|w| w.borrow_mut().take());
2600 if let Some(st) = st {
2601 st.q.lock().unwrap().closed = true;
2602 st.cv.notify_all();
2603 }
2604 let t0 = std::time::Instant::now();
2605 // Dropping the batch waits every worker out, as the joins did.
2606 drop(self.1.take());
2607 if wave_stats() {
2608 WS_DRAIN.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
2609 WS_TILES.fetch_add(1, Relaxed);
2610 wave_stats_dump();
2611 }
2612 }
2613}
2614
2615/// Hands superblock `(r, c)`'s recorded writes to the wavefront. `false`
2616/// when there is no wavefront (one reconstruction thread), in which case the
2617/// caller replays them itself.
2618fn wave_submit(fctx: &crate::decode::FrameCtx, r: usize, c: usize) -> bool {
2619 let st = fctx.wave.with(|w| w.borrow().clone());
2620 let Some(st) = st else { return false };
2621 let ops = fctx.recon_ops.with(|c| std::mem::take(&mut *c.borrow_mut()));
2622 if !ops.is_empty() {
2623 let mut q = st.q.lock().unwrap();
2624 q.rows[r].push_back((c, ops));
2625 q.queued += 1;
2626 drop(q);
2627 st.cv.notify_all();
2628 }
2629 if wave_stats() {
2630 let now = std::time::Instant::now();
2631 if let Some(t) = fctx.wave_mark.with(|c| c.replace(Some(now))) {
2632 WS_PARSE.fetch_add((now - t).as_nanos() as u64, Relaxed);
2633 }
2634 }
2635 true
2636}
2637
2638/// Waits until every submitted job is reconstructed, so the parser may read
2639/// the planes itself (the intrabc source fetch and the interintra intra
2640/// predictor -- see [`flush_recon`]).
2641fn wave_barrier(fctx: &crate::decode::FrameCtx) {
2642 let st = fctx.wave.with(|w| w.borrow().clone());
2643 let Some(st) = st else { return };
2644 let stats = wave_stats();
2645 let t0 = std::time::Instant::now();
2646 let mut q = st.q.lock().unwrap();
2647 while q.queued > 0 || q.active > 0 {
2648 q = st.cv.wait(q).unwrap();
2649 }
2650 drop(q);
2651 if stats {
2652 WS_BARRIER.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
2653 WS_BARRIERS.fetch_add(1, Relaxed);
2654 }
2655}
2656
2657/// Performs an intra write at its push site when the tile registered its
2658/// planes for inline reconstruction ([`ReconPlanes`]); `false` when the
2659/// caller must record it for the wavefront workers instead.
2660#[allow(unsafe_code)]
2661#[allow(clippy::too_many_arguments)]
2662fn inline_intra(
2663 plane: usize,
2664 x: usize,
2665 oy: usize,
2666 bw: usize,
2667 bh: usize,
2668 rect: bool,
2669 mode: usize,
2670 angle_delta: i32,
2671 reach: Reach,
2672 residual: &[i32],
2673 cfl: Option<(i32, CflSrc)>,
2674 filter_intra: Option<usize>,
2675 smooth_neighbor: bool,
2676 fctx: &crate::decode::FrameCtx,
2677) -> bool {
2678 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
2679 return false;
2680 };
2681 let pred = take_palette_pred(fctx);
2682 // SAFETY: see [`ReconPlanes`].
2683 unsafe {
2684 exec_intra(
2685 &mut *y, &mut *u, &mut *v, plane, x, oy, bw, bh, rect, mode, angle_delta, reach,
2686 residual, cfl, filter_intra, smooth_neighbor, pred, fctx,
2687 );
2688 }
2689 true
2690}
2691
2692/// [`inline_intra`] for a motion-compensated write.
2693#[allow(unsafe_code)]
2694#[allow(clippy::too_many_arguments)]
2695fn inline_mc(
2696 plane: usize,
2697 x: usize,
2698 oy: usize,
2699 stride: usize,
2700 w: usize,
2701 h: usize,
2702 prediction: &[u16],
2703 residual: &[i32],
2704 fctx: &crate::decode::FrameCtx,
2705) -> bool {
2706 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
2707 return false;
2708 };
2709 // SAFETY: see [`ReconPlanes`].
2710 unsafe {
2711 exec_mc(&mut *y, &mut *u, &mut *v, plane, x, oy, stride, w, h, prediction, residual, fctx);
2712 }
2713 true
2714}
2715
2716/// [`PlaneBuf::reconstruct`], recorded (lane-wave1 step (i)).
2717#[allow(clippy::too_many_arguments)]
2718fn push_intra(
2719 plane: usize,
2720 x: usize,
2721 y: usize,
2722 side: usize,
2723 mode: usize,
2724 angle_delta: i32,
2725 reach: Reach,
2726 residual: &[i32],
2727 cfl: Option<(i32, CflSrc)>,
2728 filter_intra: Option<usize>,
2729 smooth_neighbor: bool, fctx: &crate::decode::FrameCtx,
2730) {
2731 if inline_intra(
2732 plane, x, y, side, side, false, mode, angle_delta, reach, residual, cfl, filter_intra,
2733 smooth_neighbor, fctx,
2734 ) {
2735 return;
2736 }
2737 let pred = take_palette_pred(fctx);
2738 push_op(fctx, ReconOp::Intra {
2739 plane, x, y, bw: side, bh: side, rect: false, mode, angle_delta, reach,
2740 residual: Residual::Done(residual.to_vec()), cfl, filter_intra, smooth_neighbor, pred,
2741 });
2742}
2743
2744/// [`PlaneBuf::reconstruct_rect`], recorded (lane-wave1 step (i)).
2745#[allow(clippy::too_many_arguments)]
2746fn push_intra_rect(
2747 plane: usize,
2748 x: usize,
2749 y: usize,
2750 bw: usize,
2751 bh: usize,
2752 mode: usize,
2753 angle_delta: i32,
2754 reach: Reach,
2755 residual: &[i32],
2756 cfl: Option<(i32, CflSrc)>,
2757 filter_intra: Option<usize>,
2758 smooth_neighbor: bool, fctx: &crate::decode::FrameCtx,
2759) {
2760 if inline_intra(
2761 plane, x, y, bw, bh, true, mode, angle_delta, reach, residual, cfl, filter_intra,
2762 smooth_neighbor, fctx,
2763 ) {
2764 return;
2765 }
2766 let pred = take_palette_pred(fctx);
2767 push_op(fctx, ReconOp::Intra {
2768 plane, x, y, bw, bh, rect: true, mode, angle_delta, reach,
2769 residual: Residual::Done(residual.to_vec()), cfl, filter_intra, smooth_neighbor, pred,
2770 });
2771}
2772
2773/// [`PlaneBuf::reconstruct_mc_rect`] at `stride == w == h == side`, recorded.
2774fn push_mc(
2775 plane: usize,
2776 x: usize,
2777 y: usize,
2778 side: usize,
2779 prediction: Pred<'_>,
2780 residual: &[i32], fctx: &crate::decode::FrameCtx,
2781) {
2782 push_mc_rect(plane, x, y, side, side, side, prediction, residual, fctx);
2783}
2784
2785/// [`PlaneBuf::reconstruct_mc_rect`], recorded (lane-wave1 step (i)).
2786#[allow(clippy::too_many_arguments)]
2787fn push_mc_rect(
2788 plane: usize,
2789 x: usize,
2790 y: usize,
2791 stride: usize,
2792 w: usize,
2793 h: usize,
2794 prediction: Pred<'_>,
2795 residual: &[i32], fctx: &crate::decode::FrameCtx,
2796) {
2797 let (src, stride) = match prediction.inline(stride) {
2798 Some(v) => v,
2799 None => {
2800 let Pred::Cur { plane: sp, stride: ss, off } = prediction else { unreachable!() };
2801 push_op(fctx, ReconOp::Mc {
2802 plane, x, y, stride: ss, w, h,
2803 prediction: PredSrc::Cur { plane: sp, off, src: ss },
2804 residual: Residual::Done(residual.to_vec()),
2805 });
2806 return;
2807 }
2808 };
2809 if inline_mc(plane, x, y, stride, w, h, src, residual, fctx) {
2810 return;
2811 }
2812 push_op(fctx, ReconOp::Mc {
2813 plane, x, y, stride, w, h,
2814 prediction: PredSrc::Owned(src.to_vec()), residual: Residual::Done(residual.to_vec()),
2815 });
2816}
2817
2818/// [`push_intra_rect`] carrying the transform's INPUTS: at one reconstruction
2819/// thread the transform runs here, exactly as before; on the wavefront it
2820/// travels with the op and runs on the worker (lane-wave3).
2821#[allow(clippy::too_many_arguments)]
2822fn push_intra_tx(
2823 plane: usize,
2824 x: usize,
2825 y: usize,
2826 bw: usize,
2827 bh: usize,
2828 rect: bool,
2829 mode: usize,
2830 angle_delta: i32,
2831 reach: Reach,
2832 tx: TxParams,
2833 grid: &[i32],
2834 cfl: Option<(i32, CflSrc)>,
2835 filter_intra: Option<usize>,
2836 smooth_neighbor: bool,
2837 fctx: &crate::decode::FrameCtx,
2838) {
2839 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
2840 inline_intra(
2841 plane, x, y, bw, bh, rect, mode, angle_delta, reach, &tx.run(grid), cfl, filter_intra,
2842 smooth_neighbor, fctx,
2843 );
2844 return;
2845 }
2846 let pred = take_palette_pred(fctx);
2847 push_op(fctx, ReconOp::Intra {
2848 plane, x, y, bw, bh, rect, mode, angle_delta, reach,
2849 residual: Residual::Coeffs(tx, grid.to_vec()), cfl, filter_intra, smooth_neighbor, pred,
2850 });
2851}
2852
2853/// [`push_mc_rect`] carrying the transform's inputs -- see [`push_intra_tx`].
2854#[allow(clippy::too_many_arguments)]
2855fn push_mc_rect_tx(
2856 plane: usize,
2857 x: usize,
2858 y: usize,
2859 stride: usize,
2860 w: usize,
2861 h: usize,
2862 prediction: Pred<'_>,
2863 tx: TxParams,
2864 grid: &[i32],
2865 fctx: &crate::decode::FrameCtx,
2866) {
2867 // lane-wave4: a deferred prediction is not there to be windowed -- the
2868 // op carries its offset into the block's prediction instead, and the
2869 // residual is laid out at that same stride (`reconstruct_mc_rect` reads
2870 // both buffers at one stride).
2871 let (prediction, stride) = match prediction.inline(stride) {
2872 Some(v) => v,
2873 None => {
2874 let Pred::Cur { plane: sp, stride: ss, off } = prediction else { unreachable!() };
2875 let mut tx = tx;
2876 tx.stride = 0;
2877 push_op(fctx, ReconOp::Mc {
2878 plane, x, y, stride: w, w, h,
2879 prediction: PredSrc::Cur { plane: sp, off, src: ss },
2880 residual: Residual::Coeffs(tx, grid.to_vec()),
2881 });
2882 return;
2883 }
2884 };
2885 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
2886 // `reconstruct_mc_rect` reads the prediction and the residual at ONE
2887 // stride, so a prediction handed over at the block's stride (a var-tx
2888 // unit's window, lane-wave4) has to be densified for a dense residual
2889 // -- which is exactly what the recorded path below does.
2890 let residual = tx.run(grid);
2891 let res_stride = if tx.stride == 0 { w } else { tx.stride };
2892 let window;
2893 let prediction = if stride == res_stride {
2894 prediction
2895 } else {
2896 debug_assert_eq!(res_stride, w);
2897 let mut win = Vec::with_capacity(w * h);
2898 for row in 0..h {
2899 win.extend_from_slice(&prediction[row * stride..][..w]);
2900 }
2901 window = win;
2902 &window[..]
2903 };
2904 inline_mc(plane, x, y, res_stride, w, h, prediction, &residual, fctx);
2905 return;
2906 }
2907 // `reconstruct_mc_rect` reads exactly rows `0..h`, columns `0..w` of the
2908 // two buffers at `stride`, so the record carries that window densely
2909 // rather than the whole block's prediction: a 4x4 unit of a 64x64 block
2910 // copied 64*64 samples on the PARSING thread before. The residual is then
2911 // produced dense too (`TxParams::stride = 0`), which is the same numbers
2912 // in the same places at stride `w`.
2913 let mut window = Vec::with_capacity(w * h);
2914 for row in 0..h {
2915 window.extend_from_slice(&prediction[row * stride..][..w]);
2916 }
2917 let mut tx = tx;
2918 tx.stride = 0;
2919 push_op(fctx, ReconOp::Mc {
2920 plane, x, y, stride: w, w, h, prediction: PredSrc::Owned(window),
2921 residual: Residual::Coeffs(tx, grid.to_vec()),
2922 });
2923}
2924
2925/// Replays every recorded [`ReconOp`] into the frame's planes, in push order,
2926/// and empties the queue (lane-wave1 step (i)).
2927///
2928/// Called at the top of each superblock visit and at the end of each tile, so
2929/// a whole superblock's parsing runs with no plane access at all; the two
2930/// parse-time pixel READS that survive -- the intrabc source fetch and the
2931/// interintra intra predictor -- flush ahead of themselves instead, which
2932/// keeps them byte-exact and names exactly what step (ii) still has to move.
2933fn flush_recon(
2934 fctx: &crate::decode::FrameCtx,
2935 y: &mut PlaneBuf<'static>,
2936 u: &mut PlaneBuf<'static>,
2937 v: &mut PlaneBuf<'static>,
2938) {
2939 // lane-wave1 step (ii): a parse-time pixel READ needs every worker's
2940 // writes in place, not just this superblock's queue.
2941 wave_barrier(fctx);
2942 let mut ops = fctx.recon_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));
2943 fctx.recon_ops.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut ops));
2944 let mut cur: [Vec<u16>; 3] = Default::default();
2945 for op in ops.drain(..) {
2946 exec_op(op, y, u, v, &mut cur, fctx);
2947 }
2948 fctx.recon_spare.with(|c| *c.borrow_mut() = ops);
2949}
2950
2951/// Performs one recorded write: the body [`flush_recon`] replays, and the
2952/// body [`push_op`] runs immediately when reconstruction is inline.
2953fn exec_op(
2954 op: ReconOp,
2955 y: &mut PlaneBuf<'static>,
2956 u: &mut PlaneBuf<'static>,
2957 v: &mut PlaneBuf<'static>,
2958 cur: &mut [Vec<u16>; 3],
2959 fctx: &crate::decode::FrameCtx,
2960) {
2961 match op {
2962 ReconOp::Pred(b) => *cur = (b.0)(y, u, v, fctx),
2963 ReconOp::Intra {
2964 plane, x, y: oy, bw, bh, rect, mode, angle_delta, reach, residual, cfl,
2965 filter_intra, smooth_neighbor, pred,
2966 } => exec_intra(
2967 y, u, v, plane, x, oy, bw, bh, rect, mode, angle_delta, reach, &residual.resolve(),
2968 cfl, filter_intra, smooth_neighbor, pred, fctx,
2969 ),
2970 ReconOp::Mc { plane, x, y: oy, stride, w, h, prediction, residual } => {
2971 let residual = residual.resolve();
2972 match prediction {
2973 PredSrc::Owned(p) => {
2974 exec_mc(y, u, v, plane, x, oy, stride, w, h, &p, &residual, fctx);
2975 }
2976 PredSrc::Cur { plane: sp, off, src } => {
2977 let block = std::mem::take(&mut cur[sp]);
2978 if src == stride {
2979 exec_mc(y, u, v, plane, x, oy, stride, w, h, &block[off..], &residual, fctx);
2980 } else {
2981 // A transform unit's residual is dense, so its window
2982 // of the block prediction is taken out dense too --
2983 // the copy the parsing thread used to make, made here.
2984 let mut window = Vec::with_capacity(w * h);
2985 for row in 0..h {
2986 window.extend_from_slice(&block[off + row * src..][..w]);
2987 }
2988 exec_mc(y, u, v, plane, x, oy, stride, w, h, &window, &residual, fctx);
2989 }
2990 cur[sp] = block;
2991 }
2992 }
2993 }
2994 }
2995}
2996
2997/// [`ReconOp::Intra`] performed. Its arguments are borrowed, so the inline
2998/// path ([`push_op`]'s registered planes) reaches it without ever building
2999/// the record -- which is what keeps one reconstruction thread at the cost of
3000/// the pre-lane-wave1 decoder.
3001#[allow(clippy::too_many_arguments)]
3002fn exec_intra(
3003 y: &mut PlaneBuf<'static>,
3004 u: &mut PlaneBuf<'static>,
3005 v: &mut PlaneBuf<'static>,
3006 plane: usize,
3007 x: usize,
3008 oy: usize,
3009 bw: usize,
3010 bh: usize,
3011 rect: bool,
3012 mode: usize,
3013 angle_delta: i32,
3014 reach: Reach,
3015 residual: &[i32],
3016 cfl: Option<(i32, CflSrc)>,
3017 filter_intra: Option<usize>,
3018 smooth_neighbor: bool,
3019 pred: Option<Vec<u16>>,
3020 fctx: &crate::decode::FrameCtx,
3021) {
3022 // The CfL AC signal is read HERE, off the luma that has already been
3023 // written for this block -- at parse time it would have been the previous
3024 // frame's samples.
3025 let ac = cfl.map(|(alpha, src)| {
3026 let sig = if src.rect {
3027 cfl_ac_q3_rect(&*y, src.px, src.py, src.bw, src.bh)
3028 } else {
3029 cfl_ac_q3(&*y, src.px, src.py, src.bw)
3030 };
3031 (alpha, sig)
3032 });
3033 let cfl = ac.as_ref().map(|(a, sig)| (*a, sig.as_slice()));
3034 let target: &mut PlaneBuf<'static> = match plane { 0 => &mut *y, 1 => &mut *u, _ => &mut *v };
3035 if rect {
3036 target.reconstruct_rect(
3037 x, oy, bw, bh, mode, angle_delta, reach, residual, cfl, filter_intra,
3038 smooth_neighbor, pred, fctx,
3039 );
3040 } else {
3041 target.reconstruct(
3042 x, oy, bw, mode, angle_delta, reach, residual, cfl, filter_intra,
3043 smooth_neighbor, pred, fctx,
3044 );
3045 }
3046}
3047
3048/// [`ReconOp::Mc`] performed -- see [`exec_intra`].
3049#[allow(clippy::too_many_arguments)]
3050fn exec_mc(
3051 y: &mut PlaneBuf<'static>,
3052 u: &mut PlaneBuf<'static>,
3053 v: &mut PlaneBuf<'static>,
3054 plane: usize,
3055 x: usize,
3056 oy: usize,
3057 stride: usize,
3058 w: usize,
3059 h: usize,
3060 prediction: &[u16],
3061 residual: &[i32],
3062 fctx: &crate::decode::FrameCtx,
3063) {
3064 let target: &mut PlaneBuf<'static> = match plane { 0 => &mut *y, 1 => &mut *u, _ => &mut *v };
3065 target.reconstruct_mc_rect(x, oy, stride, w, h, prediction, residual, fctx);
3066}
3067
3068thread_local! {
3069 /// The current frame's `mi` grid, kept only while a frame header set
3070 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
3071 /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
3072 /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
3073 /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
3074 /// does not allow intrabc (so nothing is paid for it).
3075 ///
3076 /// corner-cut: only [`decode_block`] (the square path) records into it,
3077 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
3078 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
3079 /// be wrong there; upgrade = record from the rect/leaf paths too.
3080 /// The block vector [`read_intra_mode`] just decoded, handed to
3081 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
3082 /// which the alternative -- a tenth tuple member through every caller --
3083 /// already avoids). Always `.take()`n by the block that reads it.
3084 /// How many blocks decoded `use_intrabc == 1` -- the gate's hit counter.
3085 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3086}
3087 // The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so
3088 // an intrabc block's chroma reads can inherit it (see
3089 // [`INTRABC_CHROMA_TX`]). Written on every luma read; only ever read
3090 // through that one arming site.
3091 // libaom `av1_get_tx_type` (`blockd.h:1350`): for `PLANE_TYPE_UV` it
3092 // branches on `is_inter_block(mbmi)` -- which `is_intrabc_block` also
3093 // satisfies (`blockd.h:373`) -- and takes the *colocated luma
3094 // transform's coded* `tx_type` (`mbmi->txk_type[...]`), never
3095 // `intra_mode_to_tx_type` of the chroma mode. `Some` only across an
3096 // intrabc block's two chroma [`read_plane`] calls; the type decides the
3097 // `TX_CLASS`, hence the scan order, `eob_multi_ctx` and every nz context
3098 // -- getting it wrong desyncs the chroma coefficients, it is not a
3099 // reconstruction-only detail.
3100
3101/// Whether this frame's header set `allow_intrabc` -- [`INTRABC_MI_GRID`] is
3102/// `Some` exactly then (set once per frame in `decode_frame`), so the flag
3103/// needs no separate plumbing to reach the rect-strip mode reader.
3104fn allow_intrabc_frame(fctx: &crate::decode::FrameCtx) -> bool {
3105 fctx.intrabc_mi_grid.with(|g| g.borrow().is_some())
3106}
3107
3108thread_local! {
3109 /// How many rect intra strips READ the `use_intrabc` symbol (i.e. how many
3110 /// times the fix below was exercised) -- the rect-strip gate's hit counter,
3111 /// distinct from [`INTRABC_HITS`] which counts blocks that USE intrabc.
3112 static RECT_INTRABC_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3113}
3114
3115/// Current value of [`RECT_INTRABC_READS`].
3116pub(crate) fn rect_intrabc_reads() -> usize {
3117 RECT_INTRABC_READS.with(|c| c.get())
3118}
3119
3120/// Zeroes [`RECT_INTRABC_READS`] (gate tests call this before a decode).
3121#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3122pub(crate) fn reset_rect_intrabc_reads() {
3123 RECT_INTRABC_READS.with(|c| c.set(0));
3124}
3125
3126thread_local! {
3127 /// Blocks that USED intrabc at an 8x8 LEAF (`decode_leaf8`) specifically
3128 /// -- the shape lane-kf900 r7 fixed; [`INTRABC_HITS`] counts every shape.
3129 static LEAF8_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3130}
3131
3132/// Current value of [`LEAF8_INTRABC_HITS`].
3133pub(crate) fn leaf8_intrabc_hits() -> usize {
3134 LEAF8_INTRABC_HITS.with(|c| c.get())
3135}
3136
3137/// Zeroes [`LEAF8_INTRABC_HITS`] (gate tests call this before a decode).
3138#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3139pub(crate) fn reset_leaf8_intrabc_hits() {
3140 LEAF8_INTRABC_HITS.with(|c| c.set(0));
3141}
3142
3143/// Current value of [`INTRABC_HITS`].
3144#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3145pub(crate) fn intrabc_hits() -> usize {
3146 INTRABC_HITS.with(|c| c.get())
3147}
3148
3149/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
3150#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3151pub(crate) fn reset_intrabc_hits() {
3152 INTRABC_HITS.with(|c| c.set(0));
3153}
3154
3155thread_local! {
3156 /// lane-t900 r32: intrabc blocks whose transform size came off the INTER
3157 /// var-tx partition tree (unskipped, `TX_MODE_SELECT`) -- the capability
3158 /// that replaced the refusal "an intrabc block under TxMode::Select".
3159 static INTRABC_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3160}
3161
3162/// Current value of [`INTRABC_VARTX_HITS`].
3163#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3164pub(crate) fn intrabc_vartx_hits() -> usize {
3165 INTRABC_VARTX_HITS.with(|c| c.get())
3166}
3167
3168/// Zeroes [`INTRABC_VARTX_HITS`] (gate tests call this before a decode).
3169#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3170pub(crate) fn reset_intrabc_vartx_hits() {
3171 INTRABC_VARTX_HITS.with(|c| c.set(0));
3172}
3173
3174/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
3175/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
3176/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
3177/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
3178fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>, fctx: &crate::decode::FrameCtx) {
3179 fctx.intrabc_mi_grid.with(|g| {
3180 let mut g = g.borrow_mut();
3181 let Some((grid, _, _)) = g.as_mut() else {
3182 return;
3183 };
3184 let info = crate::mvstack::MiInfo {
3185 is_inter: dv.is_some(),
3186 ref_frame: 0,
3187 ref_frame1: None,
3188 mv: dv.unwrap_or((0, 0)),
3189 mv1: None,
3190 is_new_mv: dv.is_some(),
3191 is_global_mv0: false,
3192 is_global_mv1: false,
3193 size: n4 as u8,
3194 size_h: n4 as u8,
3195 };
3196 for r in mi_r..mi_r + n4 {
3197 for c in mi_c..mi_c + n4 {
3198 grid.set(r, c, info);
3199 }
3200 }
3201 });
3202}
3203
3204// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
3205// proves a real `skip_mode_present` stream actually reached a block that
3206// picked it, not just that the frame header bit was set.
3207thread_local! {
3208 static SKIP_MODE_HITS: std::cell::Cell<usize> =
3209 const { std::cell::Cell::new(0) };
3210}
3211
3212/// Current value of [`SKIP_MODE_HITS`].
3213#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3214pub(crate) fn skip_mode_hits() -> usize {
3215 SKIP_MODE_HITS.with(|c| c.get())
3216}
3217
3218// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
3219// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
3220// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
3221// reached [`obmc_blend`], not just the header bit.
3222thread_local! {
3223 static OBMC_HITS: std::cell::Cell<usize> =
3224 const { std::cell::Cell::new(0) };
3225}
3226
3227// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the
3228// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled
3229// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while
3230// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have
3231// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this
3232// decoder used to read with the wrong alphabet, so a gate that asserts this
3233// counter advanced proves the fixed path fired (class
3234// `gate-blind-to-feature`).
3235thread_local! {
3236 static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3237}
3238
3239/// Current value of [`FIMV_ALPHABET_HITS`].
3240pub fn fimv_alphabet_hits() -> usize {
3241 FIMV_ALPHABET_HITS.with(|c| c.get())
3242}
3243
3244// lane-fimv r1: how many frame headers this decoder has decoded with
3245// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate
3246// prove the encoder really produced the header state under test rather than
3247// assume it.
3248thread_local! {
3249 static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3250}
3251
3252/// Current value of [`FIMV_FRAME_HITS`].
3253pub fn fimv_frame_hits() -> usize {
3254 FIMV_FRAME_HITS.with(|c| c.get())
3255}
3256
3257/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
3258/// `force_integer_mv` bit is set.
3259pub fn note_force_integer_mv_frame() {
3260 FIMV_FRAME_HITS.with(|c| c.set(c.get() + 1));
3261}
3262
3263/// Current value of [`OBMC_HITS`].
3264#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3265pub(crate) fn obmc_hits() -> usize {
3266 OBMC_HITS.with(|c| c.get())
3267}
3268
3269// lane-t900 r27: OBMC blends that actually READ a recorded switchable filter
3270// off the neighbour band -- the positive half of the proof for "an OBMC
3271// neighbour whose switchable interp filter was never recorded". A
3272// fixed-filter frame returns before this point (its neighbours legitimately
3273// carry the `[3, 3]` sentinel), so every bump is a neighbour whose own
3274// `interp_filter` symbols were published by `record_inter_rect_mi`.
3275thread_local! {
3276 static OBMC_FILTER_BAND_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3277}
3278
3279/// Current value of [`OBMC_FILTER_BAND_READS`].
3280#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3281pub(crate) fn obmc_filter_band_reads() -> usize {
3282 OBMC_FILTER_BAND_READS.with(|c| c.get())
3283}
3284
3285// lane-scaledref r1: per-case firing counts for the scaled-reference gate
3286// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED
3287// reference would pass just as well and prove nothing, so the gate
3288// hard-asserts each combination this round lifts actually occurred:
3289// a compound block with a scaled tap, a warp block whose warp libaom
3290// suppresses because the reference is scaled, an OBMC block, an interintra
3291// block, and an 8x8 leaf.
3292thread_local! {
3293 static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3294 static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3295 static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3296 static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3297 static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3298 static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3299 static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3300}
3301
3302/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one
3303/// scaled and one unscaled tap.
3304#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3305pub(crate) fn mixed_scale_compound_hits() -> usize {
3306 MIXED_SCALE_COMPOUND_HITS.with(|c| c.get())
3307}
3308
3309/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have
3310/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf`
3311/// instead because their reference is scaled (libaom `motion_mode_allowed`,
3312/// `blockd.h:1484`).
3313#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3314pub(crate) fn scaled_warp_suppressed_hits() -> usize {
3315 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get())
3316}
3317
3318/// Current value of [`SCALED_COMPOUND_HITS`].
3319#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3320pub(crate) fn scaled_compound_hits() -> usize {
3321 SCALED_COMPOUND_HITS.with(|c| c.get())
3322}
3323
3324/// Current value of [`SCALED_WARP_FALLBACK_HITS`].
3325pub fn scaled_warp_fallback_hits() -> usize {
3326 SCALED_WARP_FALLBACK_HITS.with(|c| c.get())
3327}
3328
3329/// Current value of [`SCALED_OBMC_HITS`].
3330#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3331pub(crate) fn scaled_obmc_hits() -> usize {
3332 SCALED_OBMC_HITS.with(|c| c.get())
3333}
3334
3335/// Current value of [`SCALED_INTERINTRA_HITS`].
3336#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3337pub(crate) fn scaled_interintra_hits() -> usize {
3338 SCALED_INTERINTRA_HITS.with(|c| c.get())
3339}
3340
3341/// Current value of [`SCALED_BLOCK8_HITS`].
3342#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3343pub(crate) fn scaled_block8_hits() -> usize {
3344 SCALED_BLOCK8_HITS.with(|c| c.get())
3345}
3346
3347// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
3348// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
3349// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
3350// 8x8-leaf OBMC block apart from a 16x16+ one.
3351thread_local! {
3352 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3353}
3354
3355// lane-interp3 r1: how many inter blocks read a SWITCHABLE `interp_filter`
3356// pair whose two directions differ (`enable_dual_filter` only -- with dual
3357// filter off both directions take the single symbol, so this can never fire).
3358// A gate asserting it proves the stream really carries dual-filter blocks.
3359thread_local! {
3360 static DUAL_FILTER_DIFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3361}
3362
3363// lane-interp3 r1: how many COMPOUND 8x8 leaves read their own
3364// `read_mb_interp_filter` symbol(s) -- the read this round added (the leaf
3365// used to skip it entirely, losing a symbol and stamping the `[3, 3]`
3366// no-filter sentinel that made a neighbouring OBMC block panic).
3367thread_local! {
3368 static COMPOUND8_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3369}
3370
3371/// Current value of [`DUAL_FILTER_DIFF_HITS`].
3372#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3373pub(crate) fn dual_filter_diff_hits() -> usize {
3374 DUAL_FILTER_DIFF_HITS.with(|c| c.get())
3375}
3376
3377/// Current value of [`COMPOUND8_FILTER_HITS`].
3378#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3379pub(crate) fn compound8_filter_hits() -> usize {
3380 COMPOUND8_FILTER_HITS.with(|c| c.get())
3381}
3382
3383// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
3384// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
3385// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
3386// -- the gate's proof that a fixture really exercises the alphabet this
3387// round changed, even though the block itself still refuses (warp
3388// estimation/filter not ported).
3389thread_local! {
3390 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
3391 const { std::cell::Cell::new(0) };
3392}
3393
3394/// Current value of [`WARP_SELECTED_HITS`].
3395#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3396pub(crate) fn warp_selected_hits() -> usize {
3397 WARP_SELECTED_HITS.with(|c| c.get())
3398}
3399
3400// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one
3401// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane`
3402// into the compound intermediate) rather than translationally -- the
3403// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model
3404// really reached [`crate::warp::warp_affine_compound`].
3405thread_local! {
3406 static COMPOUND_WARP_HITS: std::cell::Cell<usize> =
3407 const { std::cell::Cell::new(0) };
3408}
3409
3410/// Current value of [`COMPOUND_WARP_HITS`].
3411#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3412pub(crate) fn compound_warp_hits() -> usize {
3413 COMPOUND_WARP_HITS.with(|c| c.get())
3414}
3415
3416// lane-interp3 r3: the same proof narrowed to the 8x8 LEAF's own compound
3417// arm ([`decode_inter_block8`]) -- that arm predicted both taps
3418// translationally until r3, so a gate needs to tell a warped 8x8 compound
3419// leaf apart from a warped 16x16+ one (both bump [`COMPOUND_WARP_HITS`]).
3420thread_local! {
3421 static COMPOUND_WARP_HITS_8: std::cell::Cell<usize> =
3422 const { std::cell::Cell::new(0) };
3423}
3424
3425/// Current value of [`COMPOUND_WARP_HITS_8`].
3426#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3427pub(crate) fn compound_warp_hits_8() -> usize {
3428 COMPOUND_WARP_HITS_8.with(|c| c.get())
3429}
3430
3431// lane-gmaffine r1: how many blocks built their prediction from a
3432// SIX-parameter (`AFFINE`) global-motion model through
3433// `crate::warp::global_warp_params` -- the gate's proof that a stream really
3434// carried an AFFINE `global_motion_params` AND that a block was predicted
3435// with it, not merely that the header parsed one.
3436thread_local! {
3437 static AFFINE_GM_HITS: std::cell::Cell<usize> =
3438 const { std::cell::Cell::new(0) };
3439}
3440
3441/// Current value of [`AFFINE_GM_HITS`].
3442#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3443pub(crate) fn affine_gm_hits() -> usize {
3444 AFFINE_GM_HITS.with(|c| c.get())
3445}
3446
3447// lane-t900 r9: rect blocks whose warp-sample top-right probe answers
3448// differently at the block's WIDTH than at libaom's
3449// `AOMMAX(xd->width, xd->height)` -- each one is a `num_proj_ref` that could
3450// pick the wrong motion_mode alphabet.
3451thread_local! {
3452 static TR_REACH_LONGER_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3453}
3454
3455/// Current value of [`TR_REACH_LONGER_SIDE_HITS`].
3456pub fn tr_reach_longer_side_hits() -> usize {
3457 TR_REACH_LONGER_SIDE_HITS.with(std::cell::Cell::get)
3458}
3459
3460// lane-t900 r9: libaom `is_nontrans_global_motion` (mvref_common.h) returns 0
3461// for `AOMMIN(mi_size_wide[bsize], mi_size_high[bsize]) < 2`, i.e. any block
3462// with a 4-px side is NEVER "non-translational global" and therefore ALWAYS
3463// reads its interp-filter symbol. Counts the blocks where that guard flips
3464// our answer -- a GLOBALMV/GLOBAL_GLOBALMV block with a non-TRANSLATION model
3465// and a 4-px side, which we used to suppress the interp read on (a pre-mode
3466// entropy desync one symbol wide).
3467thread_local! {
3468 static GM_NONTRANS_SMALL_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3469}
3470
3471/// Current value of [`GM_NONTRANS_SMALL_SIDE_HITS`].
3472pub fn gm_nontrans_small_side_hits() -> usize {
3473 GM_NONTRANS_SMALL_SIDE_HITS.with(std::cell::Cell::get)
3474}
3475
3476// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves
3477// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real
3478// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented
3479// only once `find_projection` returned a usable model, unlike
3480// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates'
3481// proof that the leaf path itself fired, not the 16x16+ one.
3482thread_local! {
3483 static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3484 static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3485}
3486
3487/// Current value of [`GLOBALMV_HITS_8`].
3488#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3489pub(crate) fn globalmv_hits_8() -> usize {
3490 GLOBALMV_HITS_8.with(|c| c.get())
3491}
3492
3493/// Current value of [`WARP_HITS_8`].
3494#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3495pub(crate) fn warp_hits_8() -> usize {
3496 WARP_HITS_8.with(|c| c.get())
3497}
3498
3499// How many blocks decoded `interintra == 1` with the non-wedge blended
3500// prediction applied (lane-interintra r1) -- the gate's proof that a
3501// stream actually exercised interintra.
3502thread_local! {
3503 static INTERINTRA_HITS: std::cell::Cell<usize> =
3504 const { std::cell::Cell::new(0) };
3505}
3506
3507/// Current value of [`INTERINTRA_HITS`].
3508#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3509pub(crate) fn interintra_hits() -> usize {
3510 INTERINTRA_HITS.with(|c| c.get())
3511}
3512
3513// lane-midcut r1: of those, how many were RECTANGULAR (`write_w != write_h`)
3514// -- the shape `interintra_blend` used to build a square `side x side` intra
3515// predictor for, with `ii_size_scales`/`edges` taken at the square. Every
3516// pre-existing interintra gate passed with that bug, so the rect arm needs
3517// its own counter to stop being vacuous.
3518thread_local! {
3519 static INTERINTRA_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3520}
3521
3522/// Current value of [`INTERINTRA_RECT_HITS`].
3523pub fn interintra_rect_hits() -> usize {
3524 INTERINTRA_RECT_HITS.with(|c| c.get())
3525}
3526
3527// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
3528// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
3529// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
3530// gate fixture actually exercises this alphabet, even though the block
3531// still refuses (the mask blend itself is unported).
3532thread_local! {
3533 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
3534 const { std::cell::Cell::new(0) };
3535}
3536
3537/// Current value of [`MASKED_COMPOUND_HITS`].
3538#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3539pub(crate) fn masked_compound_hits() -> usize {
3540 MASKED_COMPOUND_HITS.with(|c| c.get())
3541}
3542
3543// lane-intersub8 r4/r5: the NON-SQUARE half of `MASKED_COMPOUND_HITS` -- a
3544// masked-compound block whose true footprint is rectangular, i.e. the case
3545// whose `compound_type`/`wedge_idx` CDF row r4 fixed (it used to read the
3546// square envelope's `BLOCK_SIZES_ALL` index). Square blocks cannot show that
3547// defect, so a gate asserting `masked_compound_hits` alone stays vacuous for it.
3548thread_local! {
3549 static RECT_MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
3550 const { std::cell::Cell::new(0) };
3551}
3552
3553/// Current value of [`RECT_MASKED_COMPOUND_HITS`].
3554#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3555pub(crate) fn rect_masked_compound_hits() -> usize {
3556 RECT_MASKED_COMPOUND_HITS.with(|c| c.get())
3557}
3558
3559// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
3560// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
3561// actually exercised the wedge blend, not just the DIFFWTD half of
3562// `MASKED_COMPOUND_HITS`.
3563thread_local! {
3564 static WEDGE_HITS: std::cell::Cell<usize> =
3565 const { std::cell::Cell::new(0) };
3566}
3567
3568/// Current value of [`WEDGE_HITS`].
3569#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3570pub(crate) fn wedge_hits() -> usize {
3571 WEDGE_HITS.with(|c| c.get())
3572}
3573
3574// How many blocks decoded a real wedge-INTERINTRA block
3575// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
3576// a gate fixture exercised the wedge blend (fixed sign 0), not just the
3577// smooth arm counted by `INTERINTRA_HITS`.
3578thread_local! {
3579 static WII_HITS: std::cell::Cell<usize> =
3580 const { std::cell::Cell::new(0) };
3581}
3582
3583/// Current value of [`WII_HITS`].
3584#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3585pub(crate) fn wii_hits() -> usize {
3586 WII_HITS.with(|c| c.get())
3587}
3588
3589// lane-sbrect10 r1: how many INTRA blocks read `uv_mode` off the 13-symbol
3590// NO-CFL alphabet *because their size excludes CFL* (libaom `is_cfl_allowed`:
3591// wide <= 32 && high <= 32). The witness that a gate stream really carries a
3592// 64-axis intra block -- the shape whose 14-symbol read desynced every inter
3593// frame carrying one.
3594thread_local! {
3595 static NOCFL_UV_MODE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3596}
3597
3598/// Current value of [`NOCFL_UV_MODE_HITS`].
3599#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3600pub(crate) fn nocfl_uv_mode_hits() -> usize {
3601 NOCFL_UV_MODE_HITS.with(|c| c.get())
3602}
3603
3604/// lane-inter16ab r5: the six RECTANGULAR wedge shapes, in this order --
3605/// the counter slots of [`RECT_WEDGE_HITS`]/[`RECT_WII_HITS`].
3606pub(crate) const RECT_WEDGE_SHAPES: [(usize, usize); 6] =
3607 [(8, 16), (16, 8), (16, 32), (32, 16), (8, 32), (32, 8)];
3608
3609fn rect_wedge_slot(bw: usize, bh: usize) -> Option<usize> {
3610 RECT_WEDGE_SHAPES.iter().position(|&s| s == (bw, bh))
3611}
3612
3613// lane-inter16ab r5: how many COMPOUND_WEDGE / wedge-INTERINTRA blocks used a
3614// RECTANGULAR codebook row (hgtw/hltw), per shape -- the gate's proof that
3615// the rect wedge masks lifted this round actually fired, not just the square
3616// ones already counted by `WEDGE_HITS`/`WII_HITS`.
3617thread_local! {
3618 static RECT_WEDGE_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
3619 static RECT_WII_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
3620}
3621
3622/// Current value of [`RECT_WEDGE_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
3623pub(crate) fn rect_wedge_hits() -> [usize; 6] {
3624 RECT_WEDGE_HITS.with(|c| c.get())
3625}
3626
3627/// Current value of [`RECT_WII_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
3628pub(crate) fn rect_wii_hits() -> [usize; 6] {
3629 RECT_WII_HITS.with(|c| c.get())
3630}
3631
3632// lane-inter4 r4: how many 16x8/8x16 INTER LEAVES actually ran the OBMC
3633// blend -- the gate's proof that `--enable-obmc=1` reached this shape (the
3634// r3 refusal's replacement: prefilt frames are bit-exact vs an instrumented
3635// aomdec, neighbour list included).
3636thread_local! {
3637 static OBMC_RECT_LEAF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3638}
3639
3640/// Current value of [`OBMC_RECT_LEAF_HITS`].
3641pub(crate) fn obmc_rect_leaf_hits() -> usize {
3642 OBMC_RECT_LEAF_HITS.with(|c| c.get())
3643}
3644
3645// lane-obmcrec r1: how many OBMC neighbours were taken from the SECOND half of
3646// a 4-wide/4-tall (1:4 strip) chroma pair -- the case whose interp filter used
3647// to be read from the pair's FIRST mi, which is a different block and, when
3648// that half is intra, carries the `[3, 3]` "no filter" sentinel (the three
3649// 1080p 10-bit film cuts refused there). The gate's proof the shape fired.
3650thread_local! {
3651 static OBMC_PAIR_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3652}
3653
3654/// Current value of [`OBMC_PAIR_FILTER_HITS`].
3655pub(crate) fn obmc_pair_filter_hits() -> usize {
3656 OBMC_PAIR_FILTER_HITS.with(|c| c.get())
3657}
3658
3659// lane-t900 r14: how many OBMC neighbour predictions run PAST the frame edge
3660// -- libaom's `op_mi_size` is `AOMMIN(xd->width|height, mi_step)`, the block's
3661// own side, so a block overhanging the bottom/right still predicts the full
3662// neighbour strip (the destination write is what clips). We used to shrink the
3663// prediction to the visible part, which at 4 chroma rows/cols also swaps the
3664// vertical/horizontal kernel to the 4-tap one. The gate's proof the shape fired.
3665thread_local! {
3666 static OBMC_EDGE_SPAN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3667}
3668
3669/// Current value of [`OBMC_EDGE_SPAN_HITS`].
3670#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3671pub(crate) fn obmc_edge_span_hits() -> usize {
3672 OBMC_EDGE_SPAN_HITS.with(|c| c.get())
3673}
3674
3675/// Current value of [`OBMC_HITS_8`].
3676#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3677pub(crate) fn obmc_hits_8() -> usize {
3678 OBMC_HITS_8.with(|c| c.get())
3679}
3680
3681// lane-rectgate r1: how many 32x32 quadrants actually decoded a
3682// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
3683// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
3684// `VERT_B` all still fall into the generic "a partition type this encoder
3685// never writes" refusal below) -- the gate's proof that a free-partition
3686// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
3687// coincidentally never selecting one.
3688thread_local! {
3689 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
3690 const { std::cell::Cell::new(0) };
3691}
3692
3693/// Current value of [`EXTENDED_PARTITION_HITS`].
3694#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3695pub(crate) fn extended_partition_hits() -> usize {
3696 EXTENDED_PARTITION_HITS.with(|c| c.get())
3697}
3698
3699// lane-partitions r1: how many 32x32 quadrants decoded a real
3700// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
3701// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
3702// gate's proof this round's arms actually fired.
3703thread_local! {
3704 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
3705 const { std::cell::Cell::new(0) };
3706}
3707
3708/// Current value of [`RECT_PARTITION_HITS`].
3709#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3710pub(crate) fn rect_partition_hits() -> usize {
3711 RECT_PARTITION_HITS.with(|c| c.get())
3712}
3713
3714// lane-inter8 r1: how many superblocks an inter tile coded as a single
3715// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for
3716// static content, previously a named refusal).
3717thread_local! {
3718 /// lane-sb128c r1: how many 128x128 `PARTITION_NONE` roots this INTER tile
3719 /// path decoded as one whole block (its gate's own witness).
3720 pub(crate) static INTER_SB128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3721 /// 128x64 / 64x128 INTER blocks decoded at the 128 root (lane-sb128c r7).
3722 pub(crate) static INTER_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3723 pub(crate) static INTER_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3724}
3725
3726/// Current value of [`INTER_SB128_HORZ_HITS`], for a gate's before/after delta.
3727pub(crate) fn inter_sb128_horz_hits() -> usize {
3728 INTER_SB128_HORZ_HITS.with(std::cell::Cell::get)
3729}
3730
3731/// Current value of [`INTER_SB128_VERT_HITS`], for a gate's before/after delta.
3732pub(crate) fn inter_sb128_vert_hits() -> usize {
3733 INTER_SB128_VERT_HITS.with(std::cell::Cell::get)
3734}
3735
3736/// Current value of [`INTER_SB128_NONE_HITS`], for a gate's before/after delta.
3737pub fn inter_sb128_none_hits() -> usize {
3738 INTER_SB128_NONE_HITS.with(std::cell::Cell::get)
3739}
3740
3741thread_local! {
3742 /// lane-sb128c r3: how many INTRA-coded 128x128 blocks inside an INTER
3743 /// frame this decoder reconstructed (mu-chunk chroma, four TX_64X64 luma
3744 /// units) -- the gate's witness that the lifted refusal's case fired.
3745 pub(crate) static INTRA_128_IN_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3746}
3747
3748/// Current value of [`INTRA_128_IN_INTER_HITS`], for a gate's before/after delta.
3749pub fn intra_128_in_inter_hits() -> usize {
3750 INTRA_128_IN_INTER_HITS.with(std::cell::Cell::get)
3751}
3752
3753thread_local! {
3754 static INTER_SB_NONE_HITS: std::cell::Cell<usize> =
3755 const { std::cell::Cell::new(0) };
3756}
3757
3758/// Current value of [`INTER_SB_NONE_HITS`].
3759#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3760pub(crate) fn inter_sb_none_hits() -> usize {
3761 INTER_SB_NONE_HITS.with(|c| c.get())
3762}
3763
3764// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter
3765// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle
3766// path has always run that loop, so only this counter proves the newly-lifted
3767// alphabet value fired.
3768thread_local! {
3769 static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> =
3770 const { std::cell::Cell::new(0) };
3771}
3772
3773/// Current value of [`INTER_SUB16_SPLIT_HITS`].
3774#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3775pub(crate) fn inter_sub16_split_hits() -> usize {
3776 INTER_SUB16_SPLIT_HITS.with(|c| c.get())
3777}
3778
3779// lane-t900 r28: how many 16x16 inter splits reached their four 8x8 leaves
3780// while at least one reference picture was SCALED (superres) -- the counter
3781// behind the lifted "8x8 partition leaf under a scaled reference" refusal.
3782thread_local! {
3783 static SCALED_LEAF8_HITS: std::cell::Cell<usize> =
3784 const { std::cell::Cell::new(0) };
3785}
3786
3787/// Current value of [`SCALED_LEAF8_HITS`].
3788pub fn scaled_leaf8_hits() -> usize {
3789 SCALED_LEAF8_HITS.with(|c| c.get())
3790}
3791
3792// lane-t900 r28: how many sub-8x8 inter blocks (the 4x4 split and the 8x4/4x8
3793// rect pair) were predicted from a SCALED reference -- the counter behind the
3794// lifted "sub-8x8 inter block under a scaled reference" refusal.
3795thread_local! {
3796 static SCALED_SUB8_HITS: std::cell::Cell<usize> =
3797 const { std::cell::Cell::new(0) };
3798}
3799
3800/// Current value of [`SCALED_SUB8_HITS`].
3801pub fn scaled_sub8_hits() -> usize {
3802 SCALED_SUB8_HITS.with(|c| c.get())
3803}
3804
3805// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
3806// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
3807// rect coefficient reader itself fired, not just the strip-level partition
3808// symbol [`RECT_PARTITION_HITS`] already counts.
3809thread_local! {
3810 static RECT_COEFF_HITS: std::cell::Cell<usize> =
3811 const { std::cell::Cell::new(0) };
3812}
3813
3814/// Current value of [`RECT_COEFF_HITS`].
3815#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3816pub(crate) fn rect_coeff_hits() -> usize {
3817 RECT_COEFF_HITS.with(|c| c.get())
3818}
3819
3820// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`])
3821// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the
3822// charter's real-aomenc gate hard-asserts.
3823thread_local! {
3824 static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> =
3825 const { std::cell::Cell::new(0) };
3826}
3827
3828/// Current value of [`RECT_LEAF_COEFF_HITS`].
3829#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3830pub(crate) fn rect_leaf_coeff_hits() -> usize {
3831 RECT_LEAF_COEFF_HITS.with(|c| c.get())
3832}
3833
3834// lane-intrarect r1: how many intra-coded HORZ/VERT strips decoded on the
3835// INTER block path ([`decode_intra_rect_in_inter`]), per shape class --
3836// [0] the superblock-level 64x32/32x64, [1] 32x16/16x32, [2] 16x8/8x16.
3837// Every one of them was the named refusal "an intra-coded HORZ/VERT strip
3838// needs rectangular intra prediction" before this round.
3839thread_local! {
3840 static INTRA_RECT_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
3841 const { std::cell::Cell::new([0; 3]) };
3842}
3843
3844/// Current value of [`INTRA_RECT_IN_INTER_HITS`] for one shape class
3845/// (0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16).
3846#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3847pub(crate) fn intra_rect_strip_in_inter_hits(class: usize) -> usize {
3848 INTRA_RECT_IN_INTER_HITS.with(|c| c.get()[class])
3849}
3850
3851// lane-rect64port r1 (ported by hand from lane-intra64split 5ffbaf3): coded
3852// (non-skip) 64-level HORZ/VERT intra strips whose luma transform is the
3853// un-split TX_64X32/TX_32X64 -- the corner-cropped 32x32 coefficient read of
3854// [`decode_rect_split`], the shape both 10-bit 3840x1608 film cuts stop on.
3855// Split by ORIENTATION (index 0 = 64x32 wide / HORZ, 1 = 32x64 tall / VERT):
3856// a single counter cannot tell an axis swap from a working arm
3857// (class [[scan-weights-cross-axis]]), so the gate asserts both cells.
3858thread_local! {
3859 static RECT64_CORNER_TU_HITS: std::cell::Cell<[usize; 2]> =
3860 const { std::cell::Cell::new([0; 2]) };
3861}
3862
3863/// Current value of [`RECT64_CORNER_TU_HITS`] for one orientation
3864/// (0 = 64x32, 1 = 32x64).
3865pub(crate) fn rect64_corner_tu_hits(orient: usize) -> usize {
3866 RECT64_CORNER_TU_HITS.with(|c| c.get()[orient])
3867}
3868
3869// lane-intrasplit r1: intra HORZ/VERT strips inside an INTER frame whose luma
3870// transform is SPLIT, bucketed by the read `tx_depth` (index 1 and 2; index 0
3871// is never incremented) -- the gate's proof that the lifted path ran per depth.
3872thread_local! {
3873 static INTRA_RECT_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 3]> =
3874 const { std::cell::Cell::new([0; 3]) };
3875}
3876
3877// lane-t900 r21: rect intra strips inside an inter frame that read the
3878// screen-content palette syntax (`allow_screen_content_tools` set and the
3879// strip's own shape admitted by `palette_bsize_ctx_wh`) -- the site a blanket
3880// refusal used to guard, so this counter is what keeps its witness gate
3881// non-vacuous.
3882thread_local! {
3883 static INTRA_RECT_IN_INTER_SCREEN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3884}
3885
3886/// Current value of [`INTRA_RECT_IN_INTER_SCREEN_HITS`].
3887#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3888pub(crate) fn intra_rect_in_inter_screen_hits() -> usize {
3889 INTRA_RECT_IN_INTER_SCREEN_HITS.with(std::cell::Cell::get)
3890}
3891
3892/// Resets [`INTRA_RECT_IN_INTER_SCREEN_HITS`] before a decode.
3893#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3894pub(crate) fn reset_intra_rect_in_inter_screen_hits() {
3895 INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(0));
3896}
3897
3898/// Current value of [`INTRA_RECT_IN_INTER_SPLIT_TX_HITS`], indexed by tx depth.
3899#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3900pub(crate) fn intra_rect_in_inter_split_tx_hits() -> [usize; 3] {
3901 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
3902}
3903
3904// lane-midcut r2: rect intra blocks inside an inter frame whose `tx_depth` CDF
3905// ROW moved when libaom's inter-neighbour override was applied -- i.e. exactly
3906// the blocks the key frame's deblock-grid approximation used to mis-read.
3907thread_local! {
3908 static INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS: std::cell::Cell<usize> =
3909 const { std::cell::Cell::new(0) };
3910}
3911
3912/// Current value of [`INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS`].
3913#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
3914pub(crate) fn intra_rect_in_inter_txctx_override_hits() -> usize {
3915 INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS.with(std::cell::Cell::get)
3916}
3917
3918// lane-intra14 r1: how many intra-coded 1:4 strips decoded on the INTER
3919// block path, per shape -- [0] 64x16, [1] 16x64, [2] 32x8, [3] 8x32. Every
3920// one of them was the named refusal "an intra-coded 1:4 (or other non-2:1)
3921// rect strip on the inter block path" before this round.
3922thread_local! {
3923 static INTRA_RECT4_IN_INTER_HITS: std::cell::Cell<[usize; 4]> =
3924 const { std::cell::Cell::new([0; 4]) };
3925}
3926
3927/// Current value of [`INTRA_RECT4_IN_INTER_HITS`] for one shape
3928/// (0 = 64x16, 1 = 16x64, 2 = 32x8, 3 = 8x32).
3929pub(crate) fn intra_rect4_strip_in_inter_hits(shape: usize) -> usize {
3930 INTRA_RECT4_IN_INTER_HITS.with(|c| c.get()[shape])
3931}
3932
3933// lane-intra14 r1: set while an INTRA block of an INTER frame is decoded
3934// through one of the key-frame rect readers ([`decode_block_rect4`],
3935// [`decode_block_rect64`]). `Some((size_group, skip))` tells
3936// [`read_intra_mode_rect`] that (a) `skip`/segment id/cdef/delta-q were
3937// already read by [`decode_inter_block`] and (b) the luma mode comes off
3938// `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`,
3939// decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair.
3940
3941// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
3942// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
3943// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16
3944// slot -- i.e. how often the r5 defect would have picked the wrong CDF row.
3945thread_local! {
3946 static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
3947 const { std::cell::Cell::new(0) };
3948}
3949
3950/// Current value of [`MODE_MI_OVERRIDE_HITS`].
3951#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3952pub(crate) fn mode_mi_override_hits() -> usize {
3953 MODE_MI_OVERRIDE_HITS.with(|c| c.get())
3954}
3955
3956// lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a
3957// TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a
3958// mode from the previous tile, where libaom's `up_available`/`left_available`
3959// make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams:
3960// `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode`
3961// per superblock row in `start_row`, so the luma fallback cannot leak the way
3962// lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is
3963// the invariant that makes the coarse fallback safe.
3964thread_local! {
3965 static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell<usize> =
3966 const { std::cell::Cell::new(0) };
3967}
3968
3969/// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`].
3970#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3971pub(crate) fn mode_tile_edge_coarse_leaks() -> usize {
3972 MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get())
3973}
3974
3975// lane-cfl r1: how many times a chroma intra-edge filter-type read
3976// (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the
3977// mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the
3978// r1 defect would have filtered a chroma edge with the wrong strength.
3979thread_local! {
3980 static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
3981 const { std::cell::Cell::new(0) };
3982}
3983
3984/// Current value of [`UV_MODE_MI_OVERRIDE_HITS`].
3985#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3986pub(crate) fn uv_mode_mi_override_hits() -> usize {
3987 UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get())
3988}
3989
3990// lane-t900 r12: how many chroma edge-filter-type reads took their above/left
3991// `uv_mode` from the mi GRID where the one-slot-per-column map would have
3992// answered differently -- the sub-8x8 pair case where the pair's own first
3993// half had already overwritten the column slot the chroma-ref half reads.
3994thread_local! {
3995 static UV_MODE_GRID_OVERRIDE_HITS: std::cell::Cell<usize> =
3996 const { std::cell::Cell::new(0) };
3997}
3998
3999/// Current value of [`UV_MODE_GRID_OVERRIDE_HITS`].
4000pub fn uv_mode_grid_override_hits() -> usize {
4001 UV_MODE_GRID_OVERRIDE_HITS.with(|c| c.get())
4002}
4003
4004// lane-t900 r8: how many intra edge-filter-type reads (luma + chroma) the
4005// INTER neighbour stamp saved: the coarse SUB band still held a SMOOTH mode
4006// from an earlier block in that pixel row/column while the mi-exact map --
4007// which an inter block only started writing this round -- correctly says the
4008// neighbour is not smooth (libaom `is_smooth`: an inter neighbour's `mode` is
4009// an INTER mode, and its `uv_mode` "is not set for inter blocks").
4010thread_local! {
4011 static INTER_NEIGHBOUR_NOT_SMOOTH_HITS: std::cell::Cell<usize> =
4012 const { std::cell::Cell::new(0) };
4013}
4014
4015/// Current value of [`INTER_NEIGHBOUR_NOT_SMOOTH_HITS`].
4016#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4017pub(crate) fn inter_neighbour_not_smooth_hits() -> usize {
4018 INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|c| c.get())
4019}
4020
4021// lane-mtfix r1: how many times a chroma intra-edge filter-type read was
4022// suppressed at a TILE edge that is not a frame edge -- the above/left
4023// `uv_mode` neighbour of a block on a tile's first mi row/column lives in
4024// another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The
4025// coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per
4026// tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile
4027// above would decide this tile's chroma edge filter strength.
4028thread_local! {
4029 static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell<usize> =
4030 const { std::cell::Cell::new(0) };
4031}
4032
4033/// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`].
4034#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4035pub(crate) fn uv_tile_edge_suppressed_hits() -> usize {
4036 UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get())
4037}
4038
4039// lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs`
4040// read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block
4041// shapes the r1 chroma defect showed up on.
4042thread_local! {
4043 static CFL_BLOCK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4044 static UV_ANGLE_DELTA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4045}
4046
4047/// Current value of [`CFL_BLOCK_HITS`].
4048#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4049pub(crate) fn cfl_block_hits() -> usize {
4050 CFL_BLOCK_HITS.with(|c| c.get())
4051}
4052
4053/// Current value of [`UV_ANGLE_DELTA_HITS`].
4054#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4055pub(crate) fn uv_angle_delta_hits() -> usize {
4056 UV_ANGLE_DELTA_HITS.with(|c| c.get())
4057}
4058
4059// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
4060// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
4061// gate's proof this round's arms actually reached a real block, not just
4062// that `partition_w64` read one of those two symbol values.
4063thread_local! {
4064 static SB_RECT_HITS: std::cell::Cell<usize> =
4065 const { std::cell::Cell::new(0) };
4066}
4067
4068// Current value of [`SB_RECT_HITS`].
4069// lane-hgkf r1: the frame-edge partition bit, one level each. Slot 0 = a
4070// 64-level gathered edge bit read as HORZ/VERT, 1 = the same bit read as
4071// SPLIT, 2/3 = the 32-level pair. A gate asserting slot 0 or 2 proves the
4072// non-SPLIT edge arm actually decoded (before this round the bit was read and
4073// thrown away, so that arm was unreachable).
4074thread_local! {
4075 static EDGE_PART_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
4076}
4077
4078/// Current value of [`EDGE_PART_HITS`].
4079#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4080pub(crate) fn edge_part_hits() -> [usize; 4] {
4081 EDGE_PART_HITS.with(|c| c.get())
4082}
4083
4084/// Reset [`EDGE_PART_HITS`] (a gate counts one stream at a time).
4085#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4086pub(crate) fn reset_edge_part_hits() {
4087 EDGE_PART_HITS.with(|c| c.set([0; 4]));
4088}
4089
4090fn bump_edge_part(slot: usize) {
4091 EDGE_PART_HITS.with(|c| {
4092 let mut h = c.get();
4093 h[slot] += 1;
4094 c.set(h);
4095 });
4096}
4097
4098#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4099pub(crate) fn sb_rect_hits() -> usize {
4100 SB_RECT_HITS.with(|c| c.get())
4101}
4102
4103// lane-golomb r2: the 32x32-level FRAME-EDGE partition. Slot 0/1 = the
4104// gathered edge bit read as 0 (HORZ/VERT) / 1 (SPLIT); slot 2 = a 32-level
4105// PARTITION_HORZ decoded with `has_rows32 == false` (only the top 32x16 half
4106// is coded), slot 3 = a PARTITION_VERT with `has_cols32 == false`. Both tile
4107// paths (intra and inter) feed the same counter.
4108//
4109// lane-golomb r3: slots 4..7 are the same four facts one level up, at the
4110// SUPERBLOCK (64x64) edge -- 4/5 = the gathered 64-level bit read as
4111// HORZ/VERT / SPLIT, 6 = a 64x32 bottom-edge strip decoded with
4112// `has_rows == false`, 7 = a 32x64 right-edge strip. Real aomenc answers a
4113// bottom-edge superblock with the 64-level HORZ (measured: 192x80 flat-band,
4114// every SB of the last row), so the 32-level slots stay 0 on that content and
4115// only these prove the arm fired.
4116thread_local! {
4117 static EDGE32_HITS: std::cell::Cell<[usize; 8]> =
4118 const { std::cell::Cell::new([0; 8]) };
4119}
4120
4121/// Current value of [`EDGE32_HITS`].
4122#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4123pub(crate) fn edge32_hits() -> [usize; 8] {
4124 EDGE32_HITS.with(|c| c.get())
4125}
4126
4127/// [`bump_edge32`] of `base + bit`, returning the bit -- the gathered edge
4128/// reads are `if`-conditions, so the counter has to ride the expression.
4129fn bump_edge32_bit(base: usize, bit: usize) -> usize {
4130 bump_edge32(base + bit.min(1));
4131 bit
4132}
4133
4134fn bump_edge32(slot: usize) {
4135 EDGE32_HITS.with(|c| {
4136 let mut h = c.get();
4137 h[slot] += 1;
4138 c.set(h)
4139 });
4140}
4141
4142// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/
4143// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64
4144// strip) fired. Real aomenc picks these at 64 even with
4145// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is
4146// the counter the gate hard-asserts.
4147thread_local! {
4148 static SB_AB_HITS: std::cell::Cell<[usize; 4]> =
4149 const { std::cell::Cell::new([0; 4]) };
4150}
4151
4152/// Current value of [`SB_AB_HITS`], summed over the four arms.
4153#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4154pub(crate) fn sb_ab_hits() -> usize {
4155 SB_AB_HITS.with(|c| c.get().iter().sum())
4156}
4157
4158/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`,
4159/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a
4160/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as
4161/// proof of all four.
4162#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4163pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] {
4164 SB_AB_HITS.with(std::cell::Cell::get)
4165}
4166
4167// lane-tx64x16: the two 1:4 superblock arms, counted per orientation --
4168// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64
4169// strips). Two counters, not one, because a gate that only proved "some 1:4
4170// strip fired" would pass on a stream that never coded the other axis, and
4171// every scan/context table this round added comes in a transposed pair.
4172thread_local! {
4173 static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4174 static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4175}
4176
4177/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded).
4178#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4179pub(crate) fn sb_rect4_horz_hits() -> usize {
4180 SB_RECT4_HORZ_HITS.with(|c| c.get())
4181}
4182
4183/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded).
4184#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4185pub(crate) fn sb_rect4_vert_hits() -> usize {
4186 SB_RECT4_VERT_HITS.with(|c| c.get())
4187}
4188
4189// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation --
4190// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32
4191// strips), the arms the ReelB mid-film extract stops at.
4192thread_local! {
4193 static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4194 static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4195 /// lane-inter4 r1: the INTER-frame twins of the two counters above --
4196 /// four 32x8 / 8x32 inter strips of a 32x32-level `PARTITION_HORZ_4` /
4197 /// `PARTITION_VERT_4`.
4198 static RECT4_32_HORZ_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4199 static RECT4_32_VERT_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4200 /// lane-inter4 r1: superblock-level inter `PARTITION_HORZ`/`PARTITION_VERT`
4201 /// strips (64x32 / 32x64) and their 1:4 pair (64x16 / 16x64).
4202 static INTER_SB_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4203 static INTER_SB_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4204 static INTER_SB_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4205 static INTER_SB_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4206}
4207
4208// How many 32x32-level 1:4 strips actually read coefficients (non-skip):
4209// a gate that only counted strips would pass on an all-skip stream, which
4210// exercises none of the new scan/context tables.
4211thread_local! {
4212 static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4213}
4214
4215// lane-rectsplitx r1: 1:4 strips (32x8/8x32/64x16/16x64) decoded through the
4216// per-transform-unit split path, split by tx depth -- depth 1 is a 2:1 RECT
4217// unit (TX_16X8/TX_32X16), depth 2 a square one, and the two INTERLEAVE in
4218// every real stream, so a gate must prove both fired. `SUB16_SPLIT_HITS`
4219// counts the same for a 16x8/8x16 strip below 16x16.
4220thread_local! {
4221 static RECT4_SPLIT_DEPTH1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4222 static RECT4_SPLIT_DEPTH2_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4223 static SUB16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4224}
4225
4226/// Current values of `RECT4_SPLIT_DEPTH1_HITS` / `RECT4_SPLIT_DEPTH2_HITS`.
4227#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4228pub(crate) fn rect4_split_depth_hits() -> (usize, usize) {
4229 (
4230 RECT4_SPLIT_DEPTH1_HITS.with(|c| c.get()),
4231 RECT4_SPLIT_DEPTH2_HITS.with(|c| c.get()),
4232 )
4233}
4234
4235/// Current value of `SUB16_SPLIT_HITS`.
4236#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4237pub(crate) fn sub16_split_hits() -> usize {
4238 SUB16_SPLIT_HITS.with(|c| c.get())
4239}
4240
4241// lane-frame36 r2: superblock-level strips ([`decode_block_rect64`]) whose
4242// luma transform is SPLIT and which therefore leave through that fn's early
4243// return -- the arm that published no `TXFM_CONTEXT` band until this round.
4244thread_local! {
4245 static RECT64_SPLIT_TXFM_PUBLISH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4246}
4247
4248/// Current value of `RECT64_SPLIT_TXFM_PUBLISH_HITS`.
4249#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4250pub(crate) fn rect64_split_txfm_publish_hits() -> usize {
4251 RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.get())
4252}
4253
4254/// Current value of `RECT4_COEFF_HITS`.
4255pub(crate) fn rect4_coeff_hits() -> usize {
4256 RECT4_COEFF_HITS.with(|c| c.get())
4257}
4258
4259// lane-sbab r1: how many superblock-level (64x64) AB partitions fired IN AN
4260// INTER frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`,
4261// `_VERT_B` order (the intra-frame counterpart is `SB_AB_HITS`). Each arm is
4262// two 32x32 inter squares plus one true 64x32/32x64 inter strip; the gate
4263// asserts the arms it proves separately so a run whose RD only picked one
4264// cannot pass as proof of the others.
4265thread_local! {
4266 static SB_AB_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
4267}
4268
4269/// [`SB_AB_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 64x64 in an
4270/// inter frame).
4271pub fn sb_ab_inter_hits_by_arm() -> [usize; 4] {
4272 SB_AB_INTER_HITS.with(std::cell::Cell::get)
4273}
4274
4275// lane-inter16ab r1: how many 16x16-level AB partitions fired IN AN INTER
4276// frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B`
4277// order (the intra-frame counterpart is `AB16_HITS`). Each arm is two 8x8
4278// inter leaves (`decode_inter_block8`) plus one true 16x8/8x16 inter strip
4279// (`decode_inter_block` with `write_w`/`write_h`); the gate asserts every
4280// arm separately so a run whose RD only picked one cannot pass as proof of
4281// four.
4282thread_local! {
4283 static AB16_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
4284}
4285
4286/// [`AB16_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16 in an
4287/// inter frame).
4288pub fn ab16_inter_hits_by_arm() -> [usize; 4] {
4289 AB16_INTER_HITS.with(std::cell::Cell::get)
4290}
4291
4292// lane-inter16ab r2: the 16x16-level 1:4 pair as INTER blocks -- four 16x4
4293// (`PARTITION_HORZ_4`) or 4x16 (`PARTITION_VERT_4`) strips. `CHROMA_PAIRS`
4294// counts the odd strips that close a 4:2:0 chroma pair
4295// (`is_chroma_reference`, av1_common_int.h:1454: bh == 1 mi => odd mi_row),
4296// `SUB8_PIECES` the pair chroma blocks whose TOP (LEFT) half was built from
4297// the PREVIOUS strip's own mv/ref/filters -- libaom
4298// `build_inter_predictors_sub8x8` (reconinter_template.inc:87-160), reached
4299// through `is_sub8x8_inter` (same file, :54).
4300thread_local! {
4301 static INTER16_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4302 static INTER16_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4303 static INTER16_CHROMA_PAIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4304 static INTER16_SUB8_PIECE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4305}
4306
4307// lane-intra16x4: INTRA-coded strips of an inter 16x16-level 1:4 partition --
4308// [0] 16x4, [1] 4x16, [2] the odd (chroma-reference) ones, which carry the
4309// pair's single 8x4 (4x8) chroma unit for BOTH strips.
4310thread_local! {
4311 static INTRA16X4_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
4312 const { std::cell::Cell::new([0; 3]) };
4313}
4314
4315/// `(intra 16x4 strips, intra 4x16 strips, of which chroma-reference)` decoded
4316/// inside an INTER 16x16-level 1:4 partition (lane-intra16x4).
4317pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) {
4318 let v = INTRA16X4_IN_INTER_HITS.with(std::cell::Cell::get);
4319 (v[0], v[1], v[2])
4320}
4321
4322/// Current values of the inter 16x16-level 1:4 counters: `(16x4 strips, 4x16
4323/// strips, chroma pairs closed, chroma pairs built from two different
4324/// strips' motion vectors)`.
4325pub fn inter16_rect4_counters() -> (usize, usize, usize, usize) {
4326 (
4327 INTER16_HORZ4_HITS.with(std::cell::Cell::get),
4328 INTER16_VERT4_HITS.with(std::cell::Cell::get),
4329 INTER16_CHROMA_PAIR_HITS.with(std::cell::Cell::get),
4330 INTER16_SUB8_PIECE_HITS.with(std::cell::Cell::get),
4331 )
4332}
4333
4334/// One 16x4 / 4x16 inter strip's chroma situation, handed to
4335/// [`decode_inter_block`] out of band (the same one-shot thread-local idiom
4336/// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites
4337/// that all mean "an ordinary block, chroma of its own".
4338#[derive(Clone, Copy)]
4339pub(crate) struct InterStripChroma {
4340 /// `is_chroma_reference` for this strip: false on strips 0 and 2, which
4341 /// read and reconstruct NO chroma at all.
4342 has_chroma: bool,
4343 /// `PARTITION_HORZ_4` (16x4 strips) rather than `PARTITION_VERT_4`.
4344 horz: bool,
4345 /// The mi position of the EVEN strip of this pair -- `setup_pred_plane`'s
4346 /// `if (ss_y && (mi_row & 1) && mi_size_high[bsize] == 1) mi_row -= 1`,
4347 /// i.e. the origin of the 8x4 (4x8) chroma transform.
4348 pair_mi: (usize, usize),
4349 /// The previous (even) strip's single-reference MC parameters, `None`
4350 /// when it was intra or compound -- `is_sub8x8_inter` then returns false
4351 /// and the whole chroma block is predicted from THIS strip's mv.
4352 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
4353}
4354
4355 /// The single-reference MC parameters of the inter block that decoded
4356 /// last -- read by the next 1:4 strip to build its pair's chroma.
4357
4358fn bump_ab16_inter(arm: usize) {
4359 AB16_INTER_HITS.with(|c| {
4360 let mut v = c.get();
4361 v[arm] += 1;
4362 c.set(v);
4363 });
4364}
4365
4366// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or
4367// 4x16 (`PARTITION_VERT_4`) strips, `CHROMA` counting the odd strips that
4368// close a 4:2:0 chroma pair and `COEFF` the strips with a coded residual.
4369thread_local! {
4370 static RECT4_16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4371 static RECT4_16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4372 static RECT4_16_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4373 static RECT4_16_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4374 static RECT4_16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4375 /// lane-kf1200: pairs whose chroma edge-filter type read from the PAIR's
4376 /// base mi differs from what the strip's own (odd) mi would have said --
4377 /// the shape that made 4 chroma samples of the ReelB `-ss 1200`
4378 /// key frame miss by 1. Zero here means a gate never exercised the fix.
4379 static RECT4_16_UV_PAIR_FILT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4380 /// lane-kf1200 r2: sub-8x8 chroma blocks that are `skip_txfm` AND
4381 /// `UV_CFL_PRED` -- the arm that used to drop the CfL alpha entirely.
4382 static SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4383}
4384
4385/// How many skipped sub-8x8 chroma blocks carried a CfL alpha (the shape
4386/// that reconstructed as flat DC before lane-kf1200 r2).
4387pub fn skip_cfl_hits() -> usize {
4388 SKIP_CFL_HITS.with(|c| c.get())
4389}
4390
4391/// How many 16x4/4x16 chroma pairs took a different `intra_edge_filter_type`
4392/// from the pair's base mi than the strip's own mi would have given.
4393pub fn rect4_16_uv_pair_filt_hits() -> usize {
4394 RECT4_16_UV_PAIR_FILT_HITS.with(|c| c.get())
4395}
4396
4397// lane-reelckf r1: the two chroma defects ReelC's key frames exposed --
4398// CHROMA_SKIP_CFL counts skipped intra blocks whose chroma is `UV_CFL_PRED`
4399// (prediction still runs, libaom `predict_and_reconstruct_intra_block`), and
4400// RECT4_16_CHROMA_DIR counts 1:4 chroma pairs predicted directionally (whose
4401// intra-edge filter type must come from the chroma-reference position).
4402thread_local! {
4403 static CHROMA_SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4404 static RECT4_16_CHROMA_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4405}
4406
4407/// `(skipped UV_CFL_PRED blocks, directional 1:4 chroma pairs)` -- lane-reelckf.
4408pub fn reelc_chroma_counters() -> (usize, usize) {
4409 (
4410 CHROMA_SKIP_CFL_HITS.with(|c| c.get()),
4411 RECT4_16_CHROMA_DIR_HITS.with(|c| c.get()),
4412 )
4413}
4414
4415/// Current values of the 16x16-level 1:4 counters: `(16x4 strips, 4x16
4416/// strips, chroma-reference strips, strips with a coded residual, strips
4417/// whose luma transform is split)`.
4418pub fn rect4_16_counters() -> (usize, usize, usize, usize, usize) {
4419 (
4420 RECT4_16_HORZ_HITS.with(|c| c.get()),
4421 RECT4_16_VERT_HITS.with(|c| c.get()),
4422 RECT4_16_CHROMA_HITS.with(|c| c.get()),
4423 RECT4_16_COEFF_HITS.with(|c| c.get()),
4424 RECT4_16_SPLIT_HITS.with(|c| c.get()),
4425 )
4426}
4427
4428/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded).
4429pub(crate) fn rect4_32_horz_hits() -> usize {
4430 RECT4_32_HORZ_HITS.with(|c| c.get())
4431}
4432
4433/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded).
4434pub(crate) fn rect4_32_vert_hits() -> usize {
4435 RECT4_32_VERT_HITS.with(|c| c.get())
4436}
4437
4438/// Current value of `RECT4_32_HORZ_INTER_HITS` (32x8 inter strips decoded).
4439pub(crate) fn rect4_32_horz_inter_hits() -> usize {
4440 RECT4_32_HORZ_INTER_HITS.with(|c| c.get())
4441}
4442
4443/// Current value of `RECT4_32_VERT_INTER_HITS` (8x32 inter strips decoded).
4444pub(crate) fn rect4_32_vert_inter_hits() -> usize {
4445 RECT4_32_VERT_INTER_HITS.with(|c| c.get())
4446}
4447
4448/// Current value of `INTER_SB_HORZ_HITS` (64x32 inter strips decoded).
4449pub(crate) fn inter_sb_horz_hits() -> usize {
4450 INTER_SB_HORZ_HITS.with(|c| c.get())
4451}
4452
4453/// Current value of `INTER_SB_VERT_HITS` (32x64 inter strips decoded).
4454pub(crate) fn inter_sb_vert_hits() -> usize {
4455 INTER_SB_VERT_HITS.with(|c| c.get())
4456}
4457
4458/// Current value of `INTER_SB_HORZ4_HITS` (64x16 inter strips decoded).
4459pub(crate) fn inter_sb_horz4_hits() -> usize {
4460 INTER_SB_HORZ4_HITS.with(|c| c.get())
4461}
4462
4463/// Current value of `INTER_SB_VERT4_HITS` (16x64 inter strips decoded).
4464pub(crate) fn inter_sb_vert4_hits() -> usize {
4465 INTER_SB_VERT4_HITS.with(|c| c.get())
4466}
4467
4468// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
4469// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
4470// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
4471// just inert-compiled. Zero forever on a passing gate means that gate's
4472// stream never carries `delta_q_present=1` through a rect64 block.
4473thread_local! {
4474 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
4475 const { std::cell::Cell::new(0) };
4476}
4477
4478/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
4479#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4480pub(crate) fn rect64_qidx_drift_hits() -> usize {
4481 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
4482}
4483
4484// lane-partab r1: how many 32x32 quadrants decoded an AB partition
4485// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
4486// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
4487// free-partition gate's proof this round's arms actually fired.
4488thread_local! {
4489 static PARTAB_HITS: std::cell::Cell<usize> =
4490 const { std::cell::Cell::new(0) };
4491}
4492
4493/// Current value of [`PARTAB_HITS`].
4494#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4495pub(crate) fn partab_hits() -> usize {
4496 PARTAB_HITS.with(|c| c.get())
4497}
4498
4499// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm,
4500// one counter per arm rather than one shared total -- the gate hard-asserts
4501// each of these individually nonzero so a recipe that only ever fires
4502// HORZ_A can't silently stand in for the whole set.
4503thread_local! {
4504 static INTRA_HORZ_A_HITS: std::cell::Cell<usize> =
4505 const { std::cell::Cell::new(0) };
4506 static INTRA_HORZ_B_HITS: std::cell::Cell<usize> =
4507 const { std::cell::Cell::new(0) };
4508 static INTRA_VERT_A_HITS: std::cell::Cell<usize> =
4509 const { std::cell::Cell::new(0) };
4510 static INTRA_VERT_B_HITS: std::cell::Cell<usize> =
4511 const { std::cell::Cell::new(0) };
4512}
4513
4514/// Current value of [`INTRA_HORZ_A_HITS`].
4515#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4516pub(crate) fn intra_horz_a_hits() -> usize {
4517 INTRA_HORZ_A_HITS.with(|c| c.get())
4518}
4519/// Current value of [`INTRA_HORZ_B_HITS`].
4520#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4521pub(crate) fn intra_horz_b_hits() -> usize {
4522 INTRA_HORZ_B_HITS.with(|c| c.get())
4523}
4524/// Current value of [`INTRA_VERT_A_HITS`].
4525#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4526pub(crate) fn intra_vert_a_hits() -> usize {
4527 INTRA_VERT_A_HITS.with(|c| c.get())
4528}
4529/// Current value of [`INTRA_VERT_B_HITS`].
4530#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4531pub(crate) fn intra_vert_b_hits() -> usize {
4532 INTRA_VERT_B_HITS.with(|c| c.get())
4533}
4534
4535// How many [`read_inter_compound_mode`] reads actually happened
4536// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
4537// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
4538// mvstack build), not just that `comp_mode` fired. Still refused right
4539// after (no MV assignment or MC wired), so this only counts attempted
4540// reads.
4541thread_local! {
4542 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
4543 const { std::cell::Cell::new(0) };
4544}
4545
4546/// Current value of [`COMPOUND_MODE_HITS`].
4547#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
4548pub(crate) fn compound_mode_hits() -> usize {
4549 COMPOUND_MODE_HITS.with(|c| c.get())
4550}
4551
4552/// How many query blocks folded in at least one temporal MV candidate
4553/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
4554/// temporal-MV gate's own firing counter (lane-av1tmvp).
4555///
4556/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
4557/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
4558/// this file (`decode_inter_block`) still passes `tpl: None` -- this
4559/// counter compiles and the projection math it counts is unit-tested
4560/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
4561/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
4562/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
4563/// against any real stream today. See the module doc on
4564/// `crate::motion_field` and this crate's ledger for the remaining wiring.
4565#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4566pub(crate) fn tmv_hits() -> usize {
4567 crate::mvstack::tmv_hits()
4568}
4569
4570/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
4571/// produced on this thread, the 10-bit inter gate's firing proof.
4572#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4573pub(crate) fn inter_pred_hits() -> usize {
4574 crate::mc::inter_pred_hits()
4575}
4576
4577/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
4578/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
4579/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
4580/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
4581/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
4582/// needs to turn a query block's own resolved `ref_frame` into
4583/// `TplArgs::cur_offset_0` (spec 7.9.3).
4584pub(crate) struct TplFrameArgs<'a> {
4585 pub field: &'a crate::motion_field::TplField,
4586 pub order_hint_bits: u32,
4587 pub order_hint: u32,
4588 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
4589 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
4590 /// frame's own `ref_frame_idx` names for each single reference.
4591 pub ref_order_hints: [u32; 7],
4592}
4593
4594/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
4595/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
4596/// decoded `grid`: every 4x4 unit an inter block covers reads the same
4597/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
4598/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
4599/// exact — every block this crate ever codes is at least 8x8, so no 8x8
4600/// cell straddles two different blocks' values.
4601pub(crate) fn build_motion_field(
4602 grid: &MiGrid,
4603 mi_cols: usize,
4604 mi_rows: usize,
4605 order_hint: u32,
4606 order_hint_bits: u32,
4607 ref_order_hints: [u32; 7],
4608) -> crate::motion_field::MotionField {
4609 let mut field =
4610 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false);
4611 // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference
4612 // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other
4613 // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block
4614 // referencing one stores only its OTHER side's mv. With
4615 // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and
4616 // nothing is skipped.
4617 let other_side = |rf: i8| -> bool {
4618 if order_hint_bits == 0 {
4619 return false;
4620 }
4621 let oh = ref_order_hints[(rf - LAST_FRAME) as usize];
4622 crate::motion_field::get_relative_dist(order_hint_bits, oh, order_hint) > 0
4623 || oh == order_hint
4624 };
4625 // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is
4626 // capped at 12 bits per component; a longer one is not stored at all.
4627 const REFMVS_LIMIT: i32 = (1 << 12) - 1;
4628 for row in 0..mi_rows {
4629 for col in 0..mi_cols {
4630 let Some(info) = grid.get_frame(row, col) else {
4631 continue;
4632 };
4633 // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and
4634 // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`),
4635 // so an intra block -- or an inter block whose every slot is on the
4636 // other side / over the limit -- wipes what an earlier block wrote
4637 // into the same 8x8 cell (only reachable from sub-8x8 leaves, which
4638 // share a cell).
4639 if !info.is_inter {
4640 field.set(row, col, None);
4641 continue;
4642 }
4643 // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST
4644 // qualifying one wins -- a compound block stores its second
4645 // reference's mv, never its first (unless the second is on the
4646 // other side or over the limit). Storing slot 0 unconditionally
4647 // put the wrong (mv, ref_frame_offset) pair in every compound
4648 // block's cell, which a later frame's temporal candidate then
4649 // projected with the wrong reference distance.
4650 let mut saved: Option<crate::motion_field::SavedMv> = None;
4651 for (rf, mv) in [
4652 (info.ref_frame, Some(info.mv)),
4653 (info.ref_frame1.unwrap_or(0), info.mv1),
4654 ] {
4655 let (Some(mv), true) = (mv, rf > 0) else {
4656 continue;
4657 };
4658 if other_side(rf) {
4659 continue;
4660 }
4661 if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT {
4662 continue;
4663 }
4664 saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf });
4665 }
4666 field.set(row, col, saved);
4667 }
4668 }
4669 if crate::envflags::env_flag!("EC_TRACE_TPL") {
4670 eprintln!("EC_TPL_SAVED oh={order_hint}");
4671 for (r, row) in field.occupancy().iter().enumerate() {
4672 eprintln!("EC_TPL_SAVED r{r} {row}");
4673 }
4674 }
4675 field
4676}
4677
4678/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
4679/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
4680#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4681pub(crate) fn ref_hits(ref_frame: i8) -> usize {
4682 let c = match ref_frame {
4683 LAST2_FRAME => &LAST2_HITS,
4684 LAST3_FRAME => &LAST3_HITS,
4685 GOLDEN_FRAME => &GOLDEN_HITS,
4686 BWDREF_FRAME => &BWDREF_HITS,
4687 ALTREF2_FRAME => &ALTREF2_HITS,
4688 ALTREF_FRAME => &ALTREF_HITS,
4689 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
4690 };
4691 c.with(|v| v.get())
4692}
4693
4694 /// The sequence header's `enable_intra_edge_filter`, set once per
4695 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
4696 /// own read of it, kept off the call stack (see that function's own doc
4697 /// comment for why) rather than threaded through every `read_plane`/
4698 /// `decode_block`/`decode_leaf8` call between here and there.
4699
4700/// Set [`ENABLE_EDGE_FILTER`] for this thread.
4701///
4702/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
4703/// never did -- so an inter frame's intra blocks read whatever value the last
4704/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
4705/// harmless (its own key frame sets it first), but a caller that decodes an
4706/// inter frame directly, or a test harness running several streams on one
4707/// thread, inherits a foreign sequence's bit: decode stops being a pure
4708/// function of the bitstream. `decode_stream` now calls this once per stream
4709/// from the sequence header, which covers every frame including inter ones.
4710pub(crate) fn set_enable_edge_filter(value: bool, fctx: &crate::decode::FrameCtx) {
4711 fctx.enable_edge_filter.with(|f| f.set(value));
4712}
4713
4714/// Current value of [`ANGLE_DELTA_HITS`].
4715#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4716pub(crate) fn angle_delta_hits() -> usize {
4717 ANGLE_DELTA_HITS.with(|c| c.get())
4718}
4719
4720/// Current value of [`TX_CLASS1_HITS`].
4721#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4722pub(crate) fn tx_class1_hits() -> usize {
4723 TX_CLASS1_HITS.with(|c| c.get())
4724}
4725
4726// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent
4727// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion
4728// bottom) this thread's decode actually reconstructed -- the same
4729// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream
4730// genuinely exercised the sub-8x8 leaf path rather than every attempt
4731// coincidentally landing on `PARTITION_NONE`.
4732thread_local! {
4733 static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4734 /// How many 8x8 groups an INTER frame split into four BLOCK_4X4 inter
4735 /// sub-blocks (lane-intersub8).
4736 static SUB8_INTER_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4737 /// How many 8x8 groups an INTER frame split into two rectangular sub-8x8
4738 /// inter leaves (lane-intersub8 r3), indexed `[0] = HORZ` (two BLOCK_8X4),
4739 /// `[1] = VERT` (two BLOCK_4X8).
4740 static SUB8_INTER_RECT_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
4741 /// lane-sub8intra: INTRA leaves decoded inside an inter frame's sub-8x8
4742 /// HORZ/VERT partition -- `[0]` 8x4, `[1]` 4x8, `[2]` of those that were
4743 /// the chroma reference (so coded the group's 4x4 chroma intra), `[3]`
4744 /// MIXED groups whose chroma reference is INTER while its sibling is
4745 /// intra (the `is_sub8x8_inter` false path), `[4]` INTRA `BLOCK_4X4`
4746 /// leaves of an inter frame's sub-8x8 `PARTITION_SPLIT` (lane-sub8x4 r2 --
4747 /// the second lifted refusal's own witness; `[0]`/`[1]` count those too,
4748 /// so only this cell separates the split arm from the HORZ/VERT one).
4749 static SUB8_INTRA_RECT_HITS: std::cell::Cell<[usize; 5]> = const { std::cell::Cell::new([0; 5]) };
4750}
4751
4752/// Current value of [`SUB8_INTRA_RECT_HITS`]: `(8x4, 4x8, chroma-reference,
4753/// mixed groups, split 4x4 leaves)`.
4754pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) {
4755 SUB8_INTRA_RECT_HITS.with(|c| {
4756 let h = c.get();
4757 (h[0], h[1], h[2], h[3], h[4])
4758 })
4759}
4760
4761/// Current value of [`SUB8_INTER_RECT_HITS`]: `(8x4 groups, 4x8 groups)`.
4762pub fn sub8_inter_rect_hits() -> (usize, usize) {
4763 SUB8_INTER_RECT_HITS.with(|c| {
4764 let h = c.get();
4765 (h[0], h[1])
4766 })
4767}
4768
4769// lane-cdef r1: (a) how many 8x8 CDEF units `apply_cdef` EXCLUDED because all
4770// four of their mi cells are `skip_txfm` (libaom `cdef.c:29-38`
4771// `is_8x8_block_skip` / `av1_cdef_compute_sb_list`'s dlist test), and (b) how
4772// many 8x8 inter leaves (`decode_inter_block8`) wrote that skip band at all.
4773// (b) was 0 for every stream before this round -- the leaf path never touched
4774// the band, so an all-skip 8x8 group kept the PREVIOUS frame's flags and got
4775// filtered where libaom skips it. A gate asserts both are non-zero.
4776thread_local! {
4777 static CDEF_SKIPPED_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4778 static INTER8_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4779 // lane-cdef r2: (c) 8x8 CDEF units that are FILTERED and whose extent
4780 // crosses the cropped frame edge -- the only units for which "clamp at
4781 // the crop" and "pad past the mi-rounded extent with CDEF_VERY_LARGE"
4782 // (libaom `cdef.c:249-256`, `cdef_prepare_fb`'s hsize/vsize are
4783 // `nhb << mi_wide_l2` off the MI grid, not the crop) differ. A frame
4784 // whose width or height is not a multiple of 8 is the only shape that
4785 // produces one; the straddling-band gate arms assert it grew.
4786 static CDEF_STRADDLE_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4787 // lane-cdefstrip r1: 8x8 CDEF units visited with an UNWRITTEN skip band
4788 // (see `Neighbours::skip_written`).
4789 static CDEF_UNWRITTEN_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4790 // lane-cdefstrip r1: (d) skip RECTANGULAR blocks (every strip arm: 32x8,
4791 // 8x32, 16x8, 32x16, 64x16, AB/1:4 pieces...) that wrote the CDEF skip
4792 // band, and (e) 8x8 CDEF units whose four mi cells do NOT agree on skip --
4793 // the shape libaom's `is_8x8_block_skip` (`cdef.c:29-38`) exists for: an
4794 // 8-tall strip pair where only one half is skip must still be FILTERED.
4795 static RECT_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4796 static CDEF_MIXED_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4797}
4798
4799/// Current value of `RECT_SKIP_BAND_HITS`.
4800pub fn rect_skip_band_hits() -> usize {
4801 RECT_SKIP_BAND_HITS.with(|c| c.get())
4802}
4803
4804/// Current value of `CDEF_MIXED_SKIP_UNITS`.
4805pub fn cdef_mixed_skip_units() -> usize {
4806 CDEF_MIXED_SKIP_UNITS.with(|c| c.get())
4807}
4808
4809/// Current value of `CDEF_SKIPPED_UNITS`.
4810#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4811pub(crate) fn cdef_skipped_units() -> usize {
4812 CDEF_SKIPPED_UNITS.with(|c| c.get())
4813}
4814
4815/// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded
4816/// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1).
4817pub fn cdef_unwritten_skip_units() -> usize {
4818 CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get())
4819}
4820
4821/// Current value of `INTER8_SKIP_BAND_HITS`.
4822#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4823pub(crate) fn inter8_skip_band_hits() -> usize {
4824 INTER8_SKIP_BAND_HITS.with(|c| c.get())
4825}
4826
4827/// Current value of `CDEF_STRADDLE_UNITS`.
4828#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4829pub(crate) fn cdef_straddle_units() -> usize {
4830 CDEF_STRADDLE_UNITS.with(|c| c.get())
4831}
4832
4833/// Current value of [`SUB8_SPLIT_HITS`].
4834#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4835pub(crate) fn sub8_split_hits() -> usize {
4836 SUB8_SPLIT_HITS.with(|c| c.get())
4837}
4838
4839/// Current value of [`SUB8_INTER_SPLIT_HITS`].
4840pub fn sub8_inter_split_hits() -> usize {
4841 SUB8_INTER_SPLIT_HITS.with(|c| c.get())
4842}
4843
4844// lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherits a
4845// `tx_type` DIFFERENT from the group's FIRST sub-block -- the only shape that
4846// tells the two rules apart (`av1_get_tx_type` indexes `xd->tx_type_map`,
4847// which `set_mi_offsets` re-points to the CHROMA-REFERENCE sub-block, so the
4848// first sub-block's type is never the one). Reading it off sub-block 0
4849// inverted one 4x4 chroma unit on the wrong basis with the entropy stream
4850// perfectly in sync (no chroma `tx_type` symbol is coded), so a gate can only
4851// see this rule through this counter.
4852thread_local! {
4853 static SUB8_CHROMA_TX_FROM_REF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4854}
4855
4856/// Current value of `SUB8_CHROMA_TX_FROM_REF_HITS`.
4857pub fn sub8_chroma_tx_from_ref_hits() -> usize {
4858 SUB8_CHROMA_TX_FROM_REF_HITS.with(|c| c.get())
4859}
4860
4861fn note_sub8_chroma_tx(first_sub: TxType, chroma_ref: TxType, coeffs: bool) {
4862 if coeffs && first_sub != chroma_ref {
4863 SUB8_CHROMA_TX_FROM_REF_HITS.with(|c| c.set(c.get() + 1));
4864 }
4865}
4866
4867// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ`
4868// of an 8x8 block) this thread's decode reconstructed with REAL coefficients
4869// -- a skipped leaf exercises the prediction and the mi bookkeeping but never
4870// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate
4871// asserts on these two rather than a plain leaf count.
4872thread_local! {
4873 static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4874 static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4875 /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's
4876 /// two 4x4 transform units, predicted one after the other. A separate
4877 /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so
4878 /// the gate can prove THIS path fired.
4879 static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4880 /// 16x8/8x16 intra strips whose prediction actually read past the block's
4881 /// own width (above-right) or height (below-left) -- the samples
4882 /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/
4883 /// `has_bl_*` table row can corrupt (lane-tx4x8 r3).
4884 static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4885 /// Every 16x8/8x16 intra strip predicted, reaching or not -- the
4886 /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of.
4887 static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4888}
4889
4890/// Current value of [`RECT8_SPLIT_TX_HITS`].
4891#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4892pub(crate) fn rect8_split_tx_hits() -> usize {
4893 RECT8_SPLIT_TX_HITS.with(|c| c.get())
4894}
4895
4896/// Current value of [`RECT_STRIP_PRED_HITS`].
4897#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4898pub(crate) fn rect_strip_pred_hits() -> usize {
4899 RECT_STRIP_PRED_HITS.with(|c| c.get())
4900}
4901
4902/// Current value of [`RECT_STRIP_REACH_HITS`].
4903#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4904pub(crate) fn rect_strip_reach_hits() -> usize {
4905 RECT_STRIP_REACH_HITS.with(|c| c.get())
4906}
4907
4908/// Current value of [`TX4X8_CODED_HITS`].
4909#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4910pub(crate) fn tx4x8_coded_hits() -> usize {
4911 TX4X8_CODED_HITS.with(|c| c.get())
4912}
4913
4914/// Current value of [`TX8X4_CODED_HITS`].
4915#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4916pub(crate) fn tx8x4_coded_hits() -> usize {
4917 TX8X4_CODED_HITS.with(|c| c.get())
4918}
4919
4920// How many CHROMA coefficient blocks read their `eob_pt` from the class-1
4921// (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread.
4922// Chroma never codes a `tx_type` symbol -- it inherits the colocated luma
4923// type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on
4924// an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired
4925// (`eob_pt_{16,64,128,256}_chroma_class1`).
4926thread_local! {
4927 static CHROMA_EOB_CLASS1_HITS: std::cell::Cell<usize> =
4928 const { std::cell::Cell::new(0) };
4929}
4930
4931/// Current value of [`CHROMA_EOB_CLASS1_HITS`].
4932#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4933pub(crate) fn chroma_eob_class1_hits() -> usize {
4934 CHROMA_EOB_CLASS1_HITS.with(|c| c.get())
4935}
4936
4937/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
4938/// `tx_type` put this block's `eob_pt` on the class-1 row.
4939fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
4940 if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD {
4941 CHROMA_EOB_CLASS1_HITS.with(|c| c.set(c.get() + 1));
4942 }
4943}
4944
4945const SUB_MI: u32 = 4;
4946const MI: usize = 4;
4947const SB: usize = 64;
4948/// The `above_side`/`left_side` value a cell with no decoded neighbour holds
4949/// (tile start, superblock-row start).
4950///
4951/// [`Neighbours::partition_ctx_mi`] reads it as libaom's
4952/// `av1_get_partition_plane_context` reads its own zero-initialised
4953/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at
4954/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB`
4955/// (64), which reads identically at every level up to 64x64 but sets the bit
4956/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition
4957/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec
4958/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`).
4959const NO_NEIGHBOUR_SIDE: usize = 128;
4960const BLOCK: usize = 32;
4961const SUB: usize = 16;
4962const TX32: usize = 32;
4963const TX16: usize = 16;
4964const TX8: usize = 8;
4965const TX4: usize = 4;
4966const DC_PRED: usize = 0;
4967/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
4968/// carries an angle delta — [`crate::tile`]'s own private copy of the same
4969/// constant.
4970const V_PRED: usize = 1;
4971const H_PRED: usize = 2;
4972/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
4973/// `Fimode_To_Intradir`, libaom `blockd.h`).
4974const D157_PRED: usize = 6;
4975/// The last directional mode, `D67_PRED`.
4976const D67_PRED: usize = 8;
4977/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
4978/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
4979/// codes anything else, so this decoder never reads anything else either.
4980const ANGLE_DELTA_ZERO: usize = 3;
4981const NUM_BASE_LEVELS: i32 = 2;
4982const COEFF_BASE_RANGE: i32 = 12;
4983const BR_STEP: i32 = 3;
4984const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
4985
4986/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
4987/// whose probability mass a superblock or block half outside the frame
4988/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
4989/// duplicated here (that module is another lane's territory this round) and
4990/// kept in step with it by the byte-exact round-trip tests below rather than
4991/// by sharing code.
4992const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
4993const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
4994
4995fn trace_edge(mi_r: usize, mi_c: usize, bsize: u32, ctx: usize, rng: u32) {
4996 if crate::envflags::env_flag!("EC_AV1_TRACE") {
4997 eprintln!("OUR_PART mi_row={mi_r} mi_col={mi_c} bsize={bsize} ctx={ctx} rng={rng}");
4998 }
4999}
5000
5001fn element_prob(cdf: &[u16], element: usize) -> u16 {
5002 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
5003}
5004
5005/// The two-symbol CDF a partial superblock/block's forced-split flag is read
5006/// with: the mass of `elements` becomes the probability of the one partition
5007/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
5008/// (the encoder's non-adapting counterpart to this read).
5009fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
5010 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
5011 [32768 - split, 32768, 0]
5012}
5013
5014fn unsupported(what: impl Into<String>) -> Error {
5015 Error::unsupported("AV1 tile", what.into())
5016}
5017
5018/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
5019/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
5020/// same rule.
5021pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
5022 match base_q_idx {
5023 0..=20 => 0,
5024 21..=60 => 1,
5025 61..=120 => 2,
5026 _ => 3,
5027 }
5028}
5029
5030/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
5031/// [`crate::tile`]'s writer generates its scan tables with.
5032fn default_scan(side: usize) -> &'static [u16] {
5033 // One table per transform side (4/8/16/32), built once: this used to be a
5034 // fresh heap allocation plus the whole anti-diagonal walk on every
5035 // transform block read.
5036 static SCANS: std::sync::LazyLock<[Vec<u16>; 4]> = std::sync::LazyLock::new(|| {
5037 [
5038 default_scan_gen(4),
5039 default_scan_gen(8),
5040 default_scan_gen(16),
5041 default_scan_gen(32),
5042 ]
5043 });
5044 assert!(
5045 matches!(side, 4 | 8 | 16 | 32),
5046 "no default scan for a {side}-point transform"
5047 );
5048 &SCANS[side.trailing_zeros() as usize - 2]
5049}
5050
5051fn default_scan_gen(side: usize) -> Vec<u16> {
5052 let mut scan = Vec::with_capacity(side * side);
5053 for d in 0..(2 * side - 1) {
5054 let lo = d.saturating_sub(side - 1);
5055 let hi = d.min(side - 1);
5056 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
5057 if d % 2 == 0 {
5058 scan.extend(diagonal.rev());
5059 } else {
5060 scan.extend(diagonal);
5061 }
5062 }
5063 scan
5064}
5065
5066/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
5067/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
5068/// in, instead of the default zigzag. libaom's own tables are keyed by a
5069/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
5070/// physically column-major level buffer, but they decompose to the exact
5071/// same (row, col) walk as a flat row-major traversal of *our* row-major
5072/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
5073/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
5074/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
5075/// transposed (column 0 down every row, then column 1, ...).
5076fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
5077 class_scan_table_wh(side, side, class)
5078}
5079
5080/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
5081/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
5082/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
5083/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
5084/// transcribed with -- `mrow` is the plain row-major raster in our indexing
5085/// and `mcol` its transpose, at rect sizes exactly as at square ones.
5086fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
5087 match class {
5088 TxClass::Vert => (0..(w * h) as u16).collect(),
5089 TxClass::Horiz => (0..w)
5090 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
5091 .collect(),
5092 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
5093 }
5094}
5095
5096fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
5097 match scan_idx {
5098 0 => 0,
5099 i if i <= area / 8 => 1,
5100 i if i <= area / 4 => 2,
5101 _ => 3,
5102 }
5103}
5104
5105fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
5106 if row >= side || col >= side {
5107 0
5108 } else {
5109 grid[row * side + col]
5110 }
5111}
5112
5113/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
5114/// `txb_common.h`): everything but the two lone-axis-identity types this
5115/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
5116#[derive(Clone, Copy, PartialEq, Eq)]
5117enum TxClass {
5118 TwoD,
5119 Horiz,
5120 Vert,
5121}
5122
5123impl TxClass {
5124 fn of(tx_type: TxType) -> Self {
5125 match tx_type {
5126 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
5127 // key on axis alone -- FLIPADST is still ADST for this purpose.
5128 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
5129 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
5130 _ => Self::TwoD,
5131 }
5132 }
5133}
5134
5135/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
5136/// table (indexed by the position along the transform's *coded* axis --
5137/// `col` for horiz, `row` for vert) that places their contexts past the 2D
5138/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
5139/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
5140fn nz_map_ctx_offset_1d(i: usize) -> usize {
5141 match i {
5142 0 => 26,
5143 1 => 31,
5144 _ => 36,
5145 }
5146}
5147
5148fn base_ctx(
5149 grid: &[i32],
5150 side: usize,
5151 row: usize,
5152 col: usize,
5153 class: TxClass,
5154 rect_shape: Option<(usize, usize)>,
5155) -> usize {
5156 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
5157 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
5158 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
5159 // position through the full 1D neighbour sum and offset table. Skipping
5160 // that for every class desynced the last (DC) coefficient of a
5161 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
5162 // 0, which then read one extra `BR` symbol at the max and forced a
5163 // spurious third Golomb call).
5164 if class == TxClass::TwoD && row == 0 && col == 0 {
5165 return 0;
5166 }
5167 let offsets: [(usize, usize); 5] = match class {
5168 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
5169 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
5170 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
5171 };
5172 let mag: i32 = offsets
5173 .iter()
5174 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
5175 .sum();
5176 let ctx = ((mag + 1) >> 1).min(4) as usize;
5177 match class {
5178 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
5179 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
5180 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
5181 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
5182 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
5183 // strip, which own a genuinely different table from the square one
5184 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
5185 // square table vs the real ctx 13 the rect table gives).
5186 TxClass::TwoD => {
5187 // lane-rectsplit r4: apply libaom's GENERATING RULE
5188 // (`txb_common.h:199-209`) directly instead of indexing the
5189 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
5190 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
5191 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
5192 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
5193 // so 32 consecutive entries are one COLUMN: the [`cdf`]
5194 // transcriptions are `[col][row]` and this read had them as
5195 // `[row][col]` -- the transpose, i.e. the other shape's rule with
5196 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
5197 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
5198 // pins the rule against the tables over their whole 5x5 domain.
5199 if let Some((w, h)) = rect_shape {
5200 if crate::envflags::env_flag!("EC_NZOFF_DUMP") {
5201 eprintln!("NZOFF side={side} shape={w}x{h} row={row} col={col}");
5202 }
5203 if w < h && row < 2 {
5204 return ctx + 11;
5205 }
5206 if w > h && col < 2 {
5207 return ctx + 16;
5208 }
5209 }
5210 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
5211 }
5212 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
5213 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
5214 }
5215}
5216
5217fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize, class: TxClass) -> usize {
5218 let extra = match class {
5219 TxClass::TwoD => neighbour(grid, side, row + 1, col + 1).abs(),
5220 TxClass::Horiz => neighbour(grid, side, row, col + 2).abs(),
5221 TxClass::Vert => neighbour(grid, side, row + 2, col).abs(),
5222 };
5223 let mag = neighbour(grid, side, row + 1, col).abs()
5224 + neighbour(grid, side, row, col + 1).abs()
5225 + extra;
5226 let mag = (((mag + 1) >> 1).min(6)) as usize;
5227 if row == 0 && col == 0 {
5228 return mag;
5229 }
5230 let near_origin = match class {
5231 TxClass::TwoD => row < 2 && col < 2,
5232 TxClass::Horiz => col == 0,
5233 TxClass::Vert => row == 0,
5234 };
5235 if near_origin { mag + 7 } else { mag + 14 }
5236}
5237
5238/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
5239/// transposed from libaom's column-major buffer into this decoder's row-major
5240/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
5241/// against the real table). Not the square zigzag formula generalized to
5242/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
5243const SCAN_32X16: [u16; 512] = [
5244 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161,
5245 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39,
5246 8, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72,
5247 41, 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229,
5248 198, 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44,
5249 13, 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418,
5250 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326,
5251 295, 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234,
5252 203, 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142,
5253 111, 80, 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19,
5254 485, 454, 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424,
5255 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332,
5256 301, 270, 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240,
5257 209, 178, 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148,
5258 117, 86, 55, 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25,
5259 491, 460, 429, 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430,
5260 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338,
5261 307, 276, 245, 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246,
5262 215, 184, 153, 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154,
5263 123, 92, 61, 30, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31,
5264 497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405,
5265 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251,
5266 220, 189, 158, 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439,
5267 408, 377, 346, 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503,
5268 472, 441, 410, 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443,
5269 412, 381, 350, 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415,
5270 509, 478, 447, 510, 479, 511,
5271];
5272
5273/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
5274/// [`SCAN_32X16`]'s doc comment).
5275const SCAN_16X32: [u16; 512] = [
5276 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,
5277 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
5278 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
5279 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
5280 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
5281 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
5282 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
5283 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
5284 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
5285 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
5286 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
5287 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
5288 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
5289 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
5290 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
5291 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
5292 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
5293 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
5294 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
5295 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
5296 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
5297 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
5298 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
5299 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
5300 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
5301 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
5302];
5303
5304/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
5305/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
5306/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
5307/// the same source).
5308const SCAN_4X8: [u16; 32] = [
5309 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,
5310 23, 26, 29, 27, 30, 31,
5311];
5312
5313/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
5314const SCAN_8X4: [u16; 32] = [
5315 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,
5316 29, 22, 15, 30, 23, 31,
5317];
5318
5319/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
5320/// [`SCAN_32X16`]'s doc comment).
5321const SCAN_16X8: [u16; 128] = [
5322 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,
5323 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
5324 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
5325 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
5326 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
5327 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
5328];
5329
5330/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
5331/// [`SCAN_32X16`]'s doc comment).
5332const SCAN_8X16: [u16; 128] = [
5333 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,
5334 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
5335 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
5336 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
5337 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
5338 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
5339];
5340
5341/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
5342/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
5343/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
5344/// scans column-major (`p = col * height + row`), so a naive copy of
5345/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
5346/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
5347/// are byte-identical to this decoder's [`SCAN_8X16`].
5348const SCAN_32X8: [u16; 256] = [
5349 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
5350 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226, 195,
5351 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104, 73, 42,
5352 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200, 169,
5353 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78, 47, 16,
5354 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205, 174, 143,
5355 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83, 52, 21, 239,
5356 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210, 179, 148, 117,
5357 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88, 57, 26, 244, 213,
5358 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215, 184, 153, 122, 91,
5359 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93, 62, 31, 249, 218, 187,
5360 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127, 252, 221, 190, 159, 253,
5361 222, 191, 254, 223, 255,
5362];
5363/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
5364/// 16x64 `PARTITION_VERT_4` strip).
5365const SCAN_8X32: [u16; 256] = [
5366 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,
5367 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
5368 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
5369 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
5370 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
5371 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
5372 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
5373 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
5374 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
5375 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
5376 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
5377 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
5378 239, 246, 253, 247, 254, 255,
5379];
5380/// `Default_Scan_16x4`, this decoder's own row-major transcription of
5381/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
5382/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
5383/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
5384/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
5385/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
5386/// were emitted -- a naive copy installs the transpose (class
5387/// reference-layout-not-spec).
5388const SCAN_16X4: [u16; 64] = [
5389 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,
5390 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
5391 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
5392];
5393/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
5394/// 8x32 `PARTITION_VERT_4` strip).
5395const SCAN_4X16: [u16; 64] = [
5396 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,
5397 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
5398 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
5399];
5400
5401/// [`neighbour`] with independent `w` (row stride)/`h` (row-bound) extents
5402/// (lane-rectwire, mirrors [`record_rect`](Neighbours::record_rect)'s
5403/// asymmetric-extent pattern).
5404fn neighbour_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> i32 {
5405 if row >= h || col >= w {
5406 0
5407 } else {
5408 grid[row * w + col]
5409 }
5410}
5411
5412/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
5413/// the rect generalization is libaom's own comment in
5414/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
5415/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
5416/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
5417/// [`decode_block_rect`] codes (see that function's own doc comment).
5418fn base_ctx_rect(
5419 grid: &[i32],
5420 w: usize,
5421 h: usize,
5422 row: usize,
5423 col: usize,
5424 class: TxClass,
5425) -> usize {
5426 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
5427 // the 2D class short-circuits the DC position.
5428 if class == TxClass::TwoD && row == 0 && col == 0 {
5429 return 0;
5430 }
5431 let offsets: [(usize, usize); 5] = match class {
5432 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
5433 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
5434 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
5435 };
5436 let mag: i32 = offsets
5437 .iter()
5438 .map(|&(dr, dc)| neighbour_rect(grid, w, h, row + dr, col + dc).abs().min(3))
5439 .sum();
5440 let ctx = ((mag + 1) >> 1).min(4) as usize;
5441 match class {
5442 TxClass::TwoD => {
5443 if w < h && row < 2 {
5444 return ctx + 11;
5445 }
5446 if w > h && col < 2 {
5447 return ctx + 16;
5448 }
5449 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
5450 }
5451 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
5452 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
5453 // position along one axis only).
5454 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
5455 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
5456 }
5457}
5458
5459/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
5460/// neighbour-offset math itself is shape-independent, only the boundary
5461/// clamp needs the real bound in each axis.
5462fn br_ctx_rect(
5463 grid: &[i32],
5464 w: usize,
5465 h: usize,
5466 row: usize,
5467 col: usize,
5468 class: TxClass,
5469) -> usize {
5470 let extra = match class {
5471 TxClass::TwoD => neighbour_rect(grid, w, h, row + 1, col + 1).abs(),
5472 TxClass::Horiz => neighbour_rect(grid, w, h, row, col + 2).abs(),
5473 TxClass::Vert => neighbour_rect(grid, w, h, row + 2, col).abs(),
5474 };
5475 let mag = neighbour_rect(grid, w, h, row + 1, col).abs()
5476 + neighbour_rect(grid, w, h, row, col + 1).abs()
5477 + extra;
5478 let mag = (((mag + 1) >> 1).min(6)) as usize;
5479 if row == 0 && col == 0 {
5480 return mag;
5481 }
5482 let near_origin = match class {
5483 TxClass::TwoD => row < 2 && col < 2,
5484 TxClass::Horiz => col == 0,
5485 TxClass::Vert => row == 0,
5486 };
5487 if near_origin { mag + 7 } else { mag + 14 }
5488}
5489
5490fn dc_vote(dc: Option<bool>) -> i32 {
5491 match dc {
5492 None => 0,
5493 Some(true) => -1,
5494 Some(false) => 1,
5495 }
5496}
5497
5498fn dc_sign_ctx(vote: i32) -> usize {
5499 match vote.signum() {
5500 0 => 0,
5501 -1 => 1,
5502 _ => 2,
5503 }
5504}
5505
5506/// The `tx_type` a CDF symbol names, given the width of the row it was read
5507/// from.
5508///
5509/// The row's own width names its set (spec `Tx_Type_Intra_Inv_Set*` /
5510/// `Tx_Type_Inter_Inv_Set*`): 17 slots (16 symbols) is `EXT_TX_SET_ALL16`, 13
5511/// (12) `EXT_TX_SET_DTT9_IDTX_1DDCT`, 8 (7) `TX_SET_INTRA_1`, and everything
5512/// narrower the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` order, whose two
5513/// members are a prefix of the five.
5514///
5515/// One function rather than a `match` at each reader, so
5516/// [`crate::refusal_inventory`]'s enumeration of every (width, symbol) pair
5517/// tests the mapping the readers actually use.
5518pub(crate) fn tx_type_from_symbol(cdf_len: usize, t: usize) -> Option<TxType> {
5519 match cdf_len {
5520 17 => TxType::from_symbol_all16(t),
5521 13 => TxType::from_symbol_set2_12(t),
5522 8 => TxType::from_symbol_set1(t),
5523 _ => TxType::from_symbol(t),
5524 }
5525}
5526
5527/// The remainder of a level the base and base-range syntax could not reach
5528/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
5529/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
5530pub(crate) fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
5531 // lane-scaledref r1: this cap MASKS A REAL DEFECT and must not be lifted
5532 // on its own. Reading up to 32 leading zeros (dav1d's `len < 32`; libaom
5533 // itself calls a 21st bit a corrupt frame, decodetxb.c:30) is bit-identical
5534 // for every tail any encoder writes -- our own writer tops out at 19 zeros
5535 // (`tile::MAX_LEVEL == MAX_BR_LEVEL + (1 << 19)`) -- and was implemented
5536 // and round-trip tested here (commit ee1f980, reverted in 314ee08). It
5537 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
5538 // RED: seed 67 stops here today, and with the cap raised it decodes to a
5539 // frame-0 LUMA MISMATCH instead. A key frame cannot legitimately carry a
5540 // level above 1<<19, so the long tail is the SYMPTOM of an earlier desync
5541 // in that intra rect64 stream -- class `refusal-hides-a-defect`. Lift this
5542 // together with that defect's fix, not before.
5543 let mut length = 1u32;
5544 while dec.literal(1) == 0 {
5545 length += 1;
5546 if length > 20 {
5547 return Err(unsupported("a Golomb tail longer than this decoder reads"));
5548 }
5549 }
5550 let mut x = 1u32;
5551 for _ in 1..length {
5552 x = (x << 1) | dec.literal(1);
5553 }
5554 Ok(x - 1)
5555}
5556
5557/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
5558/// [`crate::tile`]'s `write_eob`.
5559fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
5560 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
5561 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
5562
5563 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
5564 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
5565 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
5566 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
5567 // `eob_multi_ctx`). Missing that split desynced the very first
5568 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
5569 // against a real aomdec trace).
5570 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
5571 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
5572 (_, Some(class1)) => class1,
5573 };
5574 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
5575 let (range, value) = dec.debug_state();
5576 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
5577 }
5578 let group = dec.symbol(eob_pt) + 1;
5579 if trace {
5580 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
5581 }
5582 let bits = OFFSET_BITS[group];
5583 let mut offset = 0u32;
5584 if bits > 0 {
5585 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
5586 if trace {
5587 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
5588 }
5589 offset = top << (bits - 1);
5590 if bits > 1 {
5591 offset |= dec.literal(bits - 1);
5592 }
5593 }
5594 GROUP_START[group] + offset as usize
5595}
5596
5597/// One transform block's levels, the inverse of [`crate::tile`]'s
5598/// `write_coeffs`, returned as a `side * side` grid in raster order, along
5599/// with the transform type that grid was coded under (`DCT_DCT` when the
5600/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
5601/// 64-point transforms, which never code anything else).
5602///
5603/// # Errors
5604/// Returns an error if the `tx_type` symbol decodes to a value outside its
5605/// CDF's own set (a corrupt or unsupported bitstream) — every value the
5606/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
5607/// produce dispatches to a real inverse transform.
5608/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
5609/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
5610/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
5611/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
5612/// the plane's own predicted mode instead. Every entry this table can
5613/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
5614/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
5615/// table ever names), so unlike the CDF-coded luma path there is no
5616/// ext-tx-set membership check to fall back from here.
5617fn default_intra_tx_type(mode: u8) -> TxType {
5618 use crate::intra::{
5619 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
5620 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
5621 };
5622 match mode {
5623 DC_PRED | D45_PRED => TxType::DctDct,
5624 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
5625 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
5626 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
5627 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
5628 }
5629}
5630
5631/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
5632/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
5633/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
5634fn is_smooth_mode(mode: usize) -> bool {
5635 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
5636}
5637
5638fn read_coeffs(
5639 dec: &mut SymbolDecoder,
5640 coding: &mut TxbTables,
5641 scan: &[u16],
5642 skip_ctx: usize,
5643 sign_ctx: usize,
5644 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
5645 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
5646 // nothing at all; `DctDct` for every luma call and every chroma call at
5647 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
5648 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
5649 default_tx_type: TxType,
5650 // `Some((w, h))` with `w != h` when this read is a superblock-level
5651 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
5652 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
5653 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
5654 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
5655 // caller's block genuinely is `side` x `side`.
5656 rect_shape: Option<(usize, usize)>,
5657) -> Result<(Vec<i32>, TxType)> {
5658 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
5659 let side = coding.side;
5660 let mut grid = vec![0i32; side * side];
5661 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
5662 let (range, value) = dec.debug_state();
5663 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
5664 }
5665 let dbg_txbskip = if coeff_trace_on() {
5666 coding.txb_skip[skip_ctx]
5667 } else {
5668 [0; 3]
5669 };
5670 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
5671 if coeff_trace_on() {
5672 let (rng, _) = dec.debug_state();
5673 eprintln!(
5674 "EC_COEFF_STEP tag=all_zero side={} ctx={skip_ctx} cdf={dbg_txbskip:?} all_zero={} rng={rng}",
5675 coding.side,
5676 all_zero as i32
5677 );
5678 }
5679 if crate::envflags::env_flag!("EC_AV1_TELL") {
5680 eprintln!(
5681 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
5682 all_zero as u8, dec.debug_bitpos(), dec.debug_state().0
5683 );
5684 }
5685 if trace {
5686 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
5687 }
5688 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
5689 let (range, value) = dec.debug_state();
5690 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
5691 }
5692 if all_zero {
5693 return Ok((grid, TxType::DctDct));
5694 }
5695 let mut tx_type = default_tx_type;
5696 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
5697 // The CDF row's own width names its set (lane-cdffwd2: extended
5698 // past the original two-way intra split once wider `reduced_tx_set
5699 // == 0` inter sets joined the table): 17 slots (16 symbols) is
5700 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
5701 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
5702 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
5703 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
5704 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
5705 let len = tx_type_cdf.len();
5706 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") && len == 3 {
5707 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
5708 }
5709 let t = dec.symbol(tx_type_cdf);
5710 if coeff_trace_on() {
5711 let (rng, _) = dec.debug_state();
5712 eprintln!("EC_COEFF_STEP tag=tx_type len={len} rng={rng}");
5713 }
5714 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
5715 let (range, value) = dec.debug_state();
5716 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
5717 }
5718 if trace {
5719 eprintln!("TRACE tx_type value={t} len={len}");
5720 }
5721 tx_type = tx_type_from_symbol(len, t)
5722 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
5723 }
5724
5725 let class = TxClass::of(tx_type);
5726 if class != TxClass::TwoD {
5727 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
5728 RECT_CLASS1_HITS.with(|c| c.set(c.get() + 1));
5729 }
5730 let eob = read_eob(dec, coding, class);
5731 if trace {
5732 eprintln!("TRACE eob value={eob}");
5733 }
5734 let ec_trace_coeff = coeff_trace_on();
5735 if ec_trace_coeff {
5736 let (rng, _) = dec.debug_state();
5737 let cls = match class { TxClass::TwoD => "2d", TxClass::Horiz => "horiz", TxClass::Vert => "vert" };
5738 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
5739 }
5740 let class_scan;
5741 let scan: &[u16] = if class == TxClass::TwoD {
5742 scan
5743 } else {
5744 class_scan = class_scan_table(side, class);
5745 &class_scan
5746 };
5747 // `side` is one of 4/8/16/32 (every `TxbTables` row), so the per-
5748 // coefficient `pos / side`, `pos % side` was a hardware divide where a
5749 // shift and a mask say the same thing, and the level buffer fits a fixed
5750 // 32x32 frame of stack instead of a heap allocation per transform block.
5751 debug_assert!(side.is_power_of_two() && side <= 32);
5752 let sh = side.trailing_zeros();
5753 let col_mask = side - 1;
5754 let mut levels_buf = [0i32; 32 * 32];
5755 let levels = &mut levels_buf[..side * side];
5756 for scan_idx in (0..eob).rev() {
5757 let pos = scan[scan_idx] as usize;
5758 let (row, col) = (pos >> sh, pos & col_mask);
5759 let level = if scan_idx == eob - 1 {
5760 let ctx = eob_coeff_ctx(scan_idx, side * side);
5761 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
5762 if trace {
5763 eprintln!(
5764 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
5765 );
5766 }
5767 v
5768 } else {
5769 let ctx = base_ctx(levels, side, row, col, class, rect_shape);
5770 let v = dec.symbol(&mut coding.base[ctx]) as i32;
5771 if ec_trace_coeff {
5772 let (rng, _) = dec.debug_state();
5773 // `pos` in libaom's column-major `coeff_idx` convention, so
5774 // the ladder lines up with instrumented `aomdec`.
5775 let apos = col * side + row;
5776 eprintln!(
5777 "EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}"
5778 );
5779 }
5780 if trace {
5781 eprintln!(
5782 "TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
5783 );
5784 }
5785 v
5786 };
5787 let level = if level > NUM_BASE_LEVELS {
5788 let ctx = br_ctx(levels, side, row, col, class);
5789 let mut level = level;
5790 let mut sent = 0;
5791 loop {
5792 let k = dec.symbol(&mut coding.br[ctx]) as i32;
5793 if ec_trace_coeff {
5794 // lane-leaf8tx r3: the `br` rung was missing from THIS
5795 // path's trace, so the cross-decoder range ladder was
5796 // blind to every base-range symbol and mis-reported the
5797 // first divergence (class [[gate-blind-to-feature]]).
5798 let (rng, _) = dec.debug_state();
5799 let apos = col * side + row;
5800 eprintln!(
5801 "EC_COEFF_STEP tag=br c={scan_idx} pos={apos} ctx={ctx} k={k} rng={rng}"
5802 );
5803 }
5804 if trace {
5805 eprintln!(
5806 "TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}"
5807 );
5808 }
5809 level += k;
5810 sent += BR_STEP;
5811 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
5812 break;
5813 }
5814 }
5815 level
5816 } else {
5817 level
5818 };
5819 if ec_trace_coeff && scan_idx == eob - 1 {
5820 let (rng, _) = dec.debug_state();
5821 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
5822 }
5823 levels[pos] = level;
5824 }
5825 if ec_trace_coeff {
5826 let (rng, _) = dec.debug_state();
5827 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
5828 }
5829
5830 for (c, &pos) in scan[..eob].iter().enumerate() {
5831 let level = levels[pos as usize];
5832 if level == 0 {
5833 continue;
5834 }
5835 let negative = if pos == 0 {
5836 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
5837 if trace {
5838 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
5839 }
5840 v
5841 } else {
5842 dec.literal(1) == 1
5843 };
5844 if ec_trace_coeff {
5845 let (rng, _) = dec.debug_state();
5846 eprintln!("EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}", negative as i32);
5847 }
5848 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
5849 let g = read_golomb(dec)?;
5850 if trace {
5851 eprintln!("TRACE golomb pos={pos} value={g}");
5852 }
5853 level + g as i32
5854 } else {
5855 level
5856 };
5857 if ec_trace_coeff {
5858 let (rng, _) = dec.debug_state();
5859 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
5860 }
5861 grid[pos as usize] = if negative { -level } else { level };
5862 }
5863 Ok((grid, tx_type))
5864}
5865
5866/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
5867/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
5868/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
5869/// can ever produce, since every `tx_type` this decoder's rect sets can read
5870/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
5871/// rather than guess-decode if a non-2D class ever shows up here, since
5872/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
5873/// form for those.
5874fn read_coeffs_rect(
5875 dec: &mut SymbolDecoder,
5876 coding: &mut TxbTables,
5877 scan: &[u16],
5878 w: usize,
5879 h: usize,
5880 skip_ctx: usize,
5881 sign_ctx: usize,
5882 default_tx_type: TxType,
5883) -> Result<(Vec<i32>, TxType)> {
5884 let rect_trace = coeff_trace_on();
5885 let mut grid = vec![0i32; w * h];
5886 let entry_rng = dec.debug_state().0;
5887 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
5888 if rect_trace {
5889 eprintln!(
5890 "EC_COEFF_STEP tag=all_zero plane=0 ctx={skip_ctx} entry={entry_rng} all_zero={} rng={}",
5891 all_zero as i32,
5892 dec.debug_state().0
5893 );
5894 }
5895 if all_zero {
5896 return Ok((grid, TxType::DctDct));
5897 }
5898 RECT_COEFF_TU_HITS.with(|c| c.set(c.get() + 1));
5899 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
5900 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
5901 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
5902 // context offsets -- both of which now have rect forms
5903 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
5904 // The rect sets that carry no symbol at all still pass `None` here.
5905 let mut tx_type = default_tx_type;
5906 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
5907 let len = tx_type_cdf.len();
5908 let t = dec.symbol(tx_type_cdf);
5909 tx_type = tx_type_from_symbol(len, t)
5910 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
5911 if rect_trace {
5912 eprintln!("EC_COEFF_STEP tag=tx_type plane=0 rng={}", dec.debug_state().0);
5913 }
5914 }
5915 let class = TxClass::of(tx_type);
5916 if class != TxClass::TwoD {
5917 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
5918 }
5919 let eob = read_eob(dec, coding, class);
5920 if rect_trace {
5921 eprintln!("EC_COEFF_STEP tag=eob eob={eob} rng={}", dec.debug_state().0);
5922 }
5923 let class_scan;
5924 let scan: &[u16] = if class == TxClass::TwoD {
5925 scan
5926 } else {
5927 class_scan = class_scan_table_wh(w, h, class);
5928 &class_scan
5929 };
5930 let mut levels = vec![0i32; w * h];
5931 for scan_idx in (0..eob).rev() {
5932 let pos = scan[scan_idx] as usize;
5933 let (row, col) = (pos / w, pos % w);
5934 // libaom's column-major `coeff_idx`, for ladder comparison.
5935 let _apos = col * h + row;
5936 let level = if scan_idx == eob - 1 {
5937 let ctx = eob_coeff_ctx(scan_idx, w * h);
5938 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
5939 if rect_trace {
5940 eprintln!(
5941 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
5942 dec.debug_state().0
5943 );
5944 }
5945 v
5946 } else {
5947 let ctx = base_ctx_rect(&levels, w, h, row, col, class);
5948 let v = dec.symbol(&mut coding.base[ctx]) as i32;
5949 if rect_trace {
5950 eprintln!(
5951 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
5952 dec.debug_state().0
5953 );
5954 }
5955 v
5956 };
5957 let level = if level > NUM_BASE_LEVELS {
5958 let ctx = br_ctx_rect(&levels, w, h, row, col, class);
5959 let mut level = level;
5960 let mut sent = 0;
5961 loop {
5962 let k = dec.symbol(&mut coding.br[ctx]) as i32;
5963 if rect_trace {
5964 eprintln!(
5965 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
5966 dec.debug_state().0
5967 );
5968 }
5969 level += k;
5970 sent += BR_STEP;
5971 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
5972 break;
5973 }
5974 }
5975 level
5976 } else {
5977 level
5978 };
5979 levels[pos] = level;
5980 if rect_trace {
5981 let (rng, _) = dec.debug_state();
5982 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}");
5983 }
5984 }
5985 if rect_trace {
5986 let (rng, _) = dec.debug_state();
5987 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
5988 }
5989 for &pos in &scan[..eob] {
5990 let level = levels[pos as usize];
5991 if level == 0 {
5992 continue;
5993 }
5994 let negative = if pos == 0 {
5995 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
5996 } else {
5997 dec.literal(1) == 1
5998 };
5999 if rect_trace {
6000 let (rng, _) = dec.debug_state();
6001 eprintln!("EC_COEFF_STEP tag=sign_rect pos={pos} sign={} dcctx={sign_ctx} rng={rng}", u8::from(negative));
6002 }
6003 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
6004 let g = read_golomb(dec)?;
6005 level + g as i32
6006 } else {
6007 level
6008 };
6009 grid[pos as usize] = if negative { -level } else { level };
6010 }
6011 Ok((grid, tx_type))
6012}
6013
6014/// What one coded block leaves behind for the blocks that read it as a
6015/// neighbour: whether it coded anything at all, and the sign of its DC —
6016/// [`crate::tile`]'s own private `Neighbour`.
6017#[derive(Clone, Copy, Default)]
6018struct Neighbour {
6019 /// The transform unit's cumulative coefficient level (spec `cul_level`,
6020 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
6021 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
6022 /// boolean (`level != 0`) is enough for every context this decoder read
6023 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
6024 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
6025 /// needs the actual magnitude tier of its above/left neighbours, not
6026 /// just whether they coded anything.
6027 level: u8,
6028 dc: Option<bool>,
6029}
6030
6031/// `dst[start .. start + n] = v`, with the same per-cell bounds behaviour the
6032/// per-4x4-cell `get_mut` loops it replaces had: a cell past the end of the
6033/// grid is dropped, never a panic. One `memset` per grid row instead of a
6034/// bounds check per cell (lane-mi) -- the index span a row of a mi rect covers
6035/// is contiguous, so this writes exactly the cells the cell loop did,
6036/// including the ones a `mi_c + cc` past `skip_grid_cols_mi` folded into the
6037/// next row.
6038#[inline]
6039fn fill_span<T: Copy>(dst: &mut [T], start: usize, n: usize, v: T) {
6040 let end = (start + n).min(dst.len());
6041 if start < end {
6042 dst[start..end].fill(v);
6043 }
6044}
6045
6046fn neighbour_state(grid: &[i32]) -> Neighbour {
6047 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
6048 Neighbour {
6049 level: cul.min(7) as u8,
6050 dc: (grid[0] != 0).then_some(grid[0] < 0),
6051 }
6052}
6053
6054/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
6055/// transform unit smaller than the block it sits in): `top`/`left` are the
6056/// above/left neighbours' magnitude tiers, each already clamped to 4.
6057const SKIP_CONTEXTS: [[usize; 5]; 5] = [
6058 [1, 2, 2, 2, 3],
6059 [2, 4, 4, 4, 5],
6060 [2, 4, 4, 4, 5],
6061 [2, 4, 4, 4, 5],
6062 [3, 5, 5, 5, 6],
6063];
6064
6065/// The neighbour state a block's contexts are read from — a duplicate of
6066/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
6067/// territory this round), kept at the same two granularities the real writer
6068/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
6069/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
6070/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
6071/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
6072/// chroma transform straddling the true, odd-sized frame edge see its
6073/// neighbour's state clamped at its own subsampled edge rather than luma's.
6074struct Neighbours {
6075 above: Vec<[Neighbour; 3]>,
6076 left: Vec<[Neighbour; 3]>,
6077 above_mode: Vec<usize>,
6078 left_mode: Vec<usize>,
6079 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
6080 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
6081 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
6082 /// luma one -- the same block can (and often does) code a different
6083 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
6084 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
6085 /// within-block neighbour finer than this grid) is luma-only -- a known,
6086 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
6087 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
6088 above_uv_mode: Vec<usize>,
6089 left_uv_mode: Vec<usize>,
6090 above_side: Vec<usize>,
6091 left_side: Vec<usize>,
6092 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
6093 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
6094 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
6095 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
6096 /// array cannot tell the second leaf's partition symbol that the first
6097 /// one was coded at 8x8.
6098 above_side_mi: Vec<usize>,
6099 left_side_mi: Vec<usize>,
6100 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
6101 /// / row, with the mi position it was written at
6102 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
6103 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
6104 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
6105 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
6106 /// leaf whose neighbour is another split group needs that group's leaf 3
6107 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
6108 /// and read only by [`decode_leaf_split4`]; the position guard makes it
6109 /// fall back to the coarse slot whenever the real neighbour was a block
6110 /// of 8x8 or larger (whose one mode is correct for every row it spans).
6111 sub8_mode_col: Vec<(usize, usize)>,
6112 sub8_mode_row: Vec<(usize, usize)>,
6113 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
6114 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
6115 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
6116 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
6117 /// the leaf above writes the same row slot the block to the left owns.
6118 uv_mode_col: Vec<(usize, usize)>,
6119 uv_mode_row: Vec<(usize, usize)>,
6120 /// Every mi cell's own `uv_mode`, the mi grid libaom's
6121 /// `chroma_above_mbmi`/`chroma_left_mbmi` read directly (`set_mi_row_col`,
6122 /// blockd.h). lane-t900 r12: the one-slot-per-column
6123 /// `uv_mode_col`/`uv_mode_row` maps above hold only the LAST block written
6124 /// in that column, so a sub-8x8 pair's own first (non-chroma-ref) half
6125 /// overwrote the row the pair's chroma-ref half then wanted to read --
6126 /// the mi-exact match failed and the coarse [`SUB`] band answered instead.
6127 /// `u8::MAX` = no block has written this cell yet (fall back to the maps).
6128 uv_mode_grid: Vec<u8>,
6129 /// [`Self::uv_mode_grid`]'s stride, in mi units (superblock-padded, like
6130 /// every other band here).
6131 uv_grid_cols: usize,
6132 /// Whether the block above/left of this column/row was coded `skip` --
6133 /// an inter frame's own `skip` context (spec `SkipContext`), which the
6134 /// key-frame writer never tracks (its skip context is always zero); a
6135 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
6136 /// `left_skip`.
6137 above_skip: Vec<bool>,
6138 left_skip: Vec<bool>,
6139 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
6140 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
6141 /// pixels last written over each unit by `set_txfm_ctxs`/
6142 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
6143 /// symbol reads its context from (lane-txselect, spec 5.11.17).
6144 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
6145 /// array is exactly libaom's per-superblock-row reset, since each mi row
6146 /// is only ever visited inside one superblock row.
6147 above_txfm: Vec<u8>,
6148 left_txfm: Vec<u8>,
6149 /// Whether the block above/left of this column/row coded `skip_mode`
6150 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
6151 /// lane-av1comp round 14.
6152 above_skip_mode: Vec<bool>,
6153 left_skip_mode: Vec<bool>,
6154 /// Whether the block above/left was coded inter -- the `is_inter`
6155 /// context (spec `av1_get_intra_inter_context`), a duplicate of
6156 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
6157 above_inter: Vec<bool>,
6158 left_inter: Vec<bool>,
6159 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
6160 /// alphabet) the block above/left of this column/row coded, or `-1` for
6161 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
6162 /// functions (`mvstack::ref_ctx` family) need the real reference, not
6163 /// just "was it inter" (lane-av1refs: every inter block used to be
6164 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
6165 /// enough).
6166 above_ref: Vec<i8>,
6167 left_ref: Vec<i8>,
6168 /// The block above/left's *second* reference frame when it was coded
6169 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
6170 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
6171 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
6172 /// `i8`, once a compound `read_ref_frames` lands. Always `None` today
6173 /// (no decode path here ever produces a compound block yet).
6174 above_ref1: Vec<Option<i8>>,
6175 left_ref1: Vec<Option<i8>>,
6176 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
6177 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
6178 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
6179 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
6180 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
6181 above_comp_group_idx: Vec<u8>,
6182 left_comp_group_idx: Vec<u8>,
6183 above_compound_idx: Vec<u8>,
6184 left_compound_idx: Vec<u8>,
6185 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
6186 /// `3` = "no info": an intra neighbour or the frame's own border) of the
6187 /// block above/left of this column/row -- spec
6188 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
6189 above_filter: Vec<[u8; 2]>,
6190 left_filter: Vec<[u8; 2]>,
6191 mi_cols: usize,
6192 mi_rows: usize,
6193 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
6194 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
6195 /// 7.15) never filters an 8x8 luma block whose covering coded block read
6196 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
6197 /// grain [`Self::record_mi`] already writes at), read back at 8x8
6198 /// granularity by [`apply_cdef`] since `skip` is constant across every
6199 /// mi cell one coded block covers.
6200 skip_grid: Vec<bool>,
6201 /// lane-cdefstrip r1 instrument: whether any coded block actually WROTE
6202 /// [`Self::skip_grid`] at this mi cell during this frame. A fresh
6203 /// `Neighbours` seeds `skip_grid` all-`false` ("not skip"), so a decode
6204 /// arm that forgets [`Self::fill_skip_grid_rect`] silently makes
6205 /// [`apply_cdef`] filter an 8x8 unit libaom's `is_8x8_block_skip`
6206 /// (`cdef.c:29-38`) excludes -- exactly the lane-cdef defect, and
6207 /// unobservable from the pixels alone. Counted by
6208 /// [`cdef_unwritten_skip_units`].
6209 skip_written: Vec<bool>,
6210 /// Per-4x4-mi origin `(mi_row, mi_col)` of the coded (prediction) block
6211 /// covering that cell -- spec 7.14.2's `isBlockEdge`/libaom `pu_edge`,
6212 /// which re-enables the loop filter at a prediction boundary between two
6213 /// skipped inter blocks (lane-mergefix r4). Written by
6214 /// [`Self::fill_skip_grid_rect`], whose `at_mi` IS that origin.
6215 blk_org_grid: Vec<[u16; 2]>,
6216 /// Per-4x4-mi `(width, height)` in mi units of the coded block covering
6217 /// that cell -- the other half of `pu_edge`: libaom tests the edge
6218 /// coordinate against the block's size in the FILTERED plane's own
6219 /// pixels, which for chroma is `max(luma_dim / 2, 4)` (lane-t900 r30b).
6220 blk_dim_grid: Vec<[u8; 2]>,
6221 skip_grid_cols_mi: usize,
6222 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
6223 /// never splits a coded block's transform below its own size (round 2:
6224 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
6225 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
6226 /// edge-length lookup (`apply_deblock`).
6227 tx_grid: Vec<u8>,
6228 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
6229 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
6230 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
6231 tx_h_grid: Vec<u8>,
6232 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
6233 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
6234 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
6235 /// does NOT follow luma's `tx_depth` split, so deriving it as
6236 /// `tx_grid / 2` invented chroma transform edges the deblocker then
6237 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
6238 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
6239 /// every caller routes through.
6240 uv_tx_grid: Vec<u8>,
6241 uv_tx_h_grid: Vec<u8>,
6242 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
6243 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
6244 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
6245 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
6246 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
6247 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
6248 /// reference onto `LAST_FRAME`'s own delta).
6249 ref_grid: Vec<i8>,
6250 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
6251 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
6252 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
6253 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
6254 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
6255 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
6256 /// to know which mode produced the value.
6257 delta_lf_grid: Vec<[i8; 4]>,
6258 /// The block above/left's own palette-Y size (0 = not a palette block)
6259 /// and its base colours -- `av1_get_palette_mode_ctx`/
6260 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
6261 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
6262 above_palette_size: Vec<usize>,
6263 left_palette_size: Vec<usize>,
6264 above_palette_colors: Vec<[u16; 8]>,
6265 left_palette_colors: Vec<[u16; 8]>,
6266 /// As the four fields above, for the neighbour's own chroma (U-channel
6267 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
6268 /// palette size/colours (lane-palette2 r1).
6269 above_palette_uv_size: Vec<usize>,
6270 left_palette_uv_size: Vec<usize>,
6271 above_palette_uv_colors: Vec<[u16; 8]>,
6272 left_palette_uv_colors: Vec<[u16; 8]>,
6273 /// This tile's own top-left corner, in 4x4 mode-info units (spec
6274 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
6275 /// neighbour" check compares against this instead of literal `0`, since a
6276 /// block at the tile's own top/left edge has no usable neighbour even
6277 /// though a decoded block sits there in the picture (spec `decode_tile`'s
6278 /// per-tile `clear_above_context`/`left_available`/`up_available`).
6279 /// `0` for a single-tile frame, matching every existing caller exactly.
6280 tile_row0_mi: usize,
6281 tile_col0_mi: usize,
6282}
6283
6284#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6285impl Neighbours {
6286 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
6287 /// true (unpadded) size in 4x4 mode-info units.
6288 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize, fctx: &crate::decode::FrameCtx) -> Self {
6289 // lane-sb128c r7: a 128x64 block at the bottom frame edge records its
6290 // neighbour state over the whole 64-row extent, past the frame's last
6291 // mi row (mi_rows 198, block rows 192..208). libaom's own context
6292 // buffers are superblock-aligned for exactly that reason
6293 // (`av1_alloc_context_buffers` rounds to `MAX_MIB_SIZE`), so pad the
6294 // side arrays to a superblock multiple and leave those cells unread --
6295 // every availability check uses the true `mi_rows`/`mi_cols` below.
6296 let sb_sub = (sb_mi_cur(fctx) as usize) / (SUB / MI);
6297 let (cols, rows) = (
6298 cols.next_multiple_of(sb_sub),
6299 rows.next_multiple_of(sb_sub),
6300 );
6301 Self {
6302 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
6303 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
6304 above_mode: vec![DC_PRED; cols],
6305 left_mode: vec![DC_PRED; rows],
6306 above_uv_mode: vec![DC_PRED; cols],
6307 left_uv_mode: vec![DC_PRED; rows],
6308 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
6309 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
6310 above_side_mi: vec![NO_NEIGHBOUR_SIDE; cols * (SUB / MI)],
6311 left_side_mi: vec![NO_NEIGHBOUR_SIDE; rows * (SUB / MI)],
6312 sub8_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],
6313 sub8_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)],
6314 uv_mode_col: vec![(usize::MAX, 0); cols * (SUB / MI)],
6315 uv_mode_row: vec![(usize::MAX, 0); rows * (SUB / MI)],
6316 uv_mode_grid: vec![u8::MAX; cols * (SUB / MI) * rows * (SUB / MI)],
6317 uv_grid_cols: cols * (SUB / MI),
6318 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
6319 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
6320 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
6321 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
6322 // 16x16 block beside it, which a SUB-grid slot cannot name
6323 // (class context-read-from-one-cell).
6324 above_skip: vec![false; cols * (SUB / MI)],
6325 left_skip: vec![false; rows * (SUB / MI)],
6326 above_skip_mode: vec![false; cols * (SUB / MI)],
6327 left_skip_mode: vec![false; rows * (SUB / MI)],
6328 above_inter: vec![false; cols * (SUB / MI)],
6329 left_inter: vec![false; rows * (SUB / MI)],
6330 above_ref: vec![-1; cols * (SUB / MI)],
6331 left_ref: vec![-1; rows * (SUB / MI)],
6332 above_ref1: vec![None; cols * (SUB / MI)],
6333 left_ref1: vec![None; rows * (SUB / MI)],
6334 above_comp_group_idx: vec![0; cols * (SUB / MI)],
6335 left_comp_group_idx: vec![0; rows * (SUB / MI)],
6336 above_compound_idx: vec![0; cols * (SUB / MI)],
6337 left_compound_idx: vec![0; rows * (SUB / MI)],
6338 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
6339 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
6340 mi_cols,
6341 mi_rows,
6342 skip_grid: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
6343 skip_written: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
6344 blk_org_grid: vec![[0u16; 2]; cols * (SUB / MI) * rows * (SUB / MI)],
6345 blk_dim_grid: vec![[1u8; 2]; cols * (SUB / MI) * rows * (SUB / MI)],
6346 skip_grid_cols_mi: cols * (SUB / MI),
6347 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
6348 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
6349 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
6350 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
6351 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
6352 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
6353 above_palette_size: vec![0; cols * (SUB / MI)],
6354 left_palette_size: vec![0; rows * (SUB / MI)],
6355 above_palette_colors: vec![[0u16; 8]; cols * (SUB / MI)],
6356 left_palette_colors: vec![[0u16; 8]; rows * (SUB / MI)],
6357 above_palette_uv_size: vec![0; cols * (SUB / MI)],
6358 left_palette_uv_size: vec![0; rows * (SUB / MI)],
6359 above_palette_uv_colors: vec![[0u16; 8]; cols * (SUB / MI)],
6360 left_palette_uv_colors: vec![[0u16; 8]; rows * (SUB / MI)],
6361 tile_row0_mi: 0,
6362 tile_col0_mi: 0,
6363 }
6364 }
6365
6366 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
6367 /// tile's own column span (`col1_mi` exclusive), plus recording
6368 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
6369 /// availability check below. Left context resets every superblock row
6370 /// regardless of tile ([`Self::start_row`], already called once per SB
6371 /// row by every caller) so it needs no tile-specific reset here.
6372 fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize, fctx: &crate::decode::FrameCtx) {
6373 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
6374 // are tile-relative, same as every other neighbour lookup here.
6375 fctx.seg_tile_origin.with(|c| c.set((row0_mi, col0_mi)));
6376 self.tile_row0_mi = row0_mi;
6377 self.tile_col0_mi = col0_mi;
6378 let end = col1_mi.min(self.above.len());
6379 for i in col0_mi.min(end)..end {
6380 self.above[i] = Default::default();
6381 self.above_side_mi[i] = NO_NEIGHBOUR_SIDE;
6382 }
6383 let (sc0, sc1) = (
6384 col0_mi / (SUB / MI),
6385 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
6386 );
6387 for i in sc0.min(sc1)..sc1 {
6388 self.above_mode[i] = DC_PRED;
6389 self.above_side[i] = NO_NEIGHBOUR_SIDE;
6390 }
6391 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
6392 // the tile's own mi column span directly.
6393 let mend = col1_mi.min(self.above_skip.len());
6394 for i in col0_mi.min(mend)..mend {
6395 self.above_skip[i] = false;
6396 self.above_skip_mode[i] = false;
6397 self.above_inter[i] = false;
6398 self.above_ref[i] = -1;
6399 self.above_ref1[i] = None;
6400 self.above_comp_group_idx[i] = 0;
6401 self.above_compound_idx[i] = 0;
6402 self.above_filter[i] = [3u8; 2];
6403 }
6404 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
6405 // stale `(row, mode)` from the tile to the LEFT names an mi row this
6406 // tile's first block would read as its own above neighbour.
6407 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
6408 for i in col0_mi.min(mcol_end)..mcol_end {
6409 self.sub8_mode_col[i] = (usize::MAX, 0);
6410 self.uv_mode_col[i] = (usize::MAX, 0);
6411 }
6412 // lane-mergefix r2: `av1_zero_above_context` also memsets the txfm row
6413 // over the tile's own column span (to `tx_size_wide[TX_SIZES_LARGEST]`,
6414 // not zero) -- without it a second tile column reads the first one's
6415 // resolved transform sizes as its own above context.
6416 let tend = col1_mi.min(self.above_txfm.len());
6417 for i in col0_mi.min(tend)..tend {
6418 self.above_txfm[i] = TXFM_CTX_INIT;
6419 }
6420 }
6421
6422 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
6423 /// for a non-palette block, clearing any stale neighbour state) into every
6424 /// [`SUB`]-grid cell it covers on both the above and left edges --
6425 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
6426 /// call sites are all square blocks).
6427 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
6428 self.record_palette_y_rect((at.0 * (SUB / MI), at.1 * (SUB / MI)), side, side, size, colors);
6429 }
6430
6431 /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
6432 /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
6433 /// [`Self::record`]): a true rect strip's above/left neighbour spans
6434 /// differ.
6435 fn record_palette_y_rect(
6436 &mut self,
6437 mi: (usize, usize),
6438 w: usize,
6439 h: usize,
6440 size: usize,
6441 colors: [u16; 8],
6442 ) {
6443 let (r, c) = mi;
6444 if crate::envflags::env_flag!("EC_PALPUB") {
6445 eprintln!("EC_PALPUB yrect mi={r},{c} bw={w} bh={h} y={size}");
6446 }
6447 // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size`
6448 // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi
6449 // cell immediately left of the block, not its 16px [`SUB`] cell. The
6450 // old SUB grid let a 16x8 strip pair share one slot, so the second
6451 // strip of mi(0,8) read the FIRST strip's palette size and the colour
6452 // cache came out one entry short (class [[context-read-from-one-cell]]).
6453 for cell in 0..(w / MI).max(1) {
6454 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
6455 *e = size;
6456 self.above_palette_colors[c + cell] = colors;
6457 }
6458 }
6459 for cell in 0..(h / MI).max(1) {
6460 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
6461 *e = size;
6462 self.left_palette_colors[r + cell] = colors;
6463 }
6464 }
6465 }
6466
6467 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
6468 /// neighbours that are themselves a palette-Y block, plus
6469 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
6470 /// cache (pred_common.c:73).
6471 ///
6472 /// The SB-top-row exclusion of the above neighbour (`row % 64` in
6473 /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
6474 /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
6475 /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
6476 /// the ctx too made every superblock in the frame's second SB row read
6477 /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
6478 /// palette block decoded as "no palette" and the tile desynced from
6479 /// there (class [[cdf-row-held-constant]]).
6480 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
6481 self.palette_ctx_and_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
6482 }
6483
6484 /// [`Self::palette_ctx_and_cache`] with the block's REAL mi row, which a
6485 /// 1:4 strip does not share with its [`SUB`] cell: `av1_get_palette_cache`
6486 /// drops the above neighbour on a 64-px superblock boundary
6487 /// (pred_common.c:76, `row % (1 << MIN_SB_SIZE_LOG2)` with `row` the
6488 /// block's own PIXEL row), and strip 1 of a HORZ_4 sits 8 px into the
6489 /// cell -- reading `at.0 % 4` there excludes strip 0 from the cache of
6490 /// every strip in an SB's top cell row, which libaom does not do.
6491 fn palette_ctx_and_cache_mi(&self, mi: (usize, usize)) -> (usize, Vec<u16>) {
6492 let (r, c) = mi;
6493 let above_ok = r % 16 != 0;
6494 // `xd->above_mbmi` exists for every row but the tile's own first.
6495 let above_is_palette = r > self.tile_row0_mi && self.above_palette_size[c] > 0;
6496 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
6497 (self.above_palette_size[c], self.above_palette_colors[c])
6498 } else {
6499 (0, [0u16; 8])
6500 };
6501 // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which
6502 // is NULL whenever the block sits at its TILE's own left column
6503 // (`left_available`), not the frame's -- without this guard a second
6504 // tile column reads the previous tile's palette colours into its cache
6505 // and its `palette_y_mode` ctx.
6506 let left_ok = c > self.tile_col0_mi;
6507 let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 {
6508 (self.left_palette_size[r], self.left_palette_colors[r])
6509 } else {
6510 (0, [0u16; 8])
6511 };
6512 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
6513 let mut cache = Vec::with_capacity(16);
6514 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
6515 if cache.last() != Some(&v) {
6516 cache.push(v);
6517 }
6518 };
6519 let (mut ai, mut li) = (0usize, 0usize);
6520 while ai < above_n && li < left_n {
6521 let (va, vl) = (above_colors[ai], left_colors[li]);
6522 if vl < va {
6523 push_dedup(&mut cache, vl);
6524 li += 1;
6525 } else {
6526 push_dedup(&mut cache, va);
6527 ai += 1;
6528 if vl == va {
6529 li += 1;
6530 }
6531 }
6532 }
6533 while ai < above_n {
6534 push_dedup(&mut cache, above_colors[ai]);
6535 ai += 1;
6536 }
6537 while li < left_n {
6538 push_dedup(&mut cache, left_colors[li]);
6539 li += 1;
6540 }
6541 (ctx, cache)
6542 }
6543
6544 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
6545 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
6546 /// same way (lane-palette2 r1).
6547 fn record_palette_uv(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
6548 self.record_palette_uv_rect(
6549 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
6550 side,
6551 side,
6552 size,
6553 colors,
6554 );
6555 }
6556
6557 /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
6558 /// extents, in LUMA pixels (lane-palette2 r4, same convention as
6559 /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
6560 /// luma resolution regardless of which plane the recorded state is for).
6561 fn record_palette_uv_rect(
6562 &mut self,
6563 mi: (usize, usize),
6564 w: usize,
6565 h: usize,
6566 size: usize,
6567 colors: [u16; 8],
6568 ) {
6569 let (r, c) = mi;
6570 // mi granularity, see [`Self::record_palette_y_rect`].
6571 for cell in 0..(w / MI).max(1) {
6572 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
6573 *e = size;
6574 self.above_palette_uv_colors[c + cell] = colors;
6575 }
6576 }
6577 for cell in 0..(h / MI).max(1) {
6578 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
6579 *e = size;
6580 self.left_palette_uv_colors[r + cell] = colors;
6581 }
6582 }
6583 }
6584
6585 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
6586 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
6587 /// no neighbour lookup at all (it is this block's own just-decided Y
6588 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
6589 /// so only the cache is wanted here.
6590 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
6591 self.palette_uv_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
6592 }
6593
6594 /// [`Self::palette_uv_cache`] with the block's real mi row -- see
6595 /// [`Self::palette_ctx_and_cache_mi`].
6596 fn palette_uv_cache_mi(&self, mi: (usize, usize)) -> Vec<u16> {
6597 let (r, c) = mi;
6598 let above_ok = r % 16 != 0;
6599 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
6600 (self.above_palette_uv_size[c], self.above_palette_uv_colors[c])
6601 } else {
6602 (0, [0u16; 8])
6603 };
6604 // Same tile-relative left availability as the luma cache above.
6605 let left_ok = c > self.tile_col0_mi;
6606 let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 {
6607 (self.left_palette_uv_size[r], self.left_palette_uv_colors[r])
6608 } else {
6609 (0, [0u16; 8])
6610 };
6611 let mut cache = Vec::with_capacity(16);
6612 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
6613 if cache.last() != Some(&v) {
6614 cache.push(v);
6615 }
6616 };
6617 let (mut ai, mut li) = (0usize, 0usize);
6618 while ai < above_n && li < left_n {
6619 let (va, vl) = (above_colors[ai], left_colors[li]);
6620 if vl < va {
6621 push_dedup(&mut cache, vl);
6622 li += 1;
6623 } else {
6624 push_dedup(&mut cache, va);
6625 ai += 1;
6626 if vl == va {
6627 li += 1;
6628 }
6629 }
6630 }
6631 while ai < above_n {
6632 push_dedup(&mut cache, above_colors[ai]);
6633 ai += 1;
6634 }
6635 while li < left_n {
6636 push_dedup(&mut cache, left_colors[li]);
6637 li += 1;
6638 }
6639 cache
6640 }
6641
6642 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
6643 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
6644 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
6645 /// units as [`Self::fill_skip_grid`].
6646 fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8, fctx: &crate::decode::FrameCtx) {
6647 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame, fctx);
6648 }
6649
6650 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
6651 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
6652 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
6653 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
6654 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
6655 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
6656 /// libaom `set_one_param_for_line_luma`/`_chroma`: an edge that is a
6657 /// transform-unit edge but NOT a prediction-unit edge is not filtered when
6658 /// `curr_skipped = mbmi->skip_txfm && is_inter_block(mbmi)`. Widening this
6659 /// block's published transform extent to its own size is exactly that
6660 /// suppression for the deblocker's `x0 % tx != 0` test -- the only shape
6661 /// that needs it is the 128 root, whose chroma extent (64) is the one
6662 /// [`Self::fill_lf_grid_rect`]'s TX_32X32 cap narrows. An INTRA block is
6663 /// never suppressed (libaom's `is_inter_block` term), so this is called
6664 /// only from the skipped-inter branch.
6665 fn suppress_internal_lf_edges(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize) {
6666 let (mi_r, mi_c) = at_mi;
6667 let (uv_w, uv_h) = ((w_mi * MI / 2).max(4) as u8, (h_mi * MI / 2).max(4) as u8);
6668 for rr in 0..h_mi {
6669 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
6670 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_w);
6671 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_h);
6672 }
6673 }
6674
6675 fn fill_lf_grid_rect(
6676 &mut self,
6677 at_mi: (usize, usize),
6678 w_mi: usize,
6679 h_mi: usize,
6680 tx_px: u8,
6681 tx_h_px: u8,
6682 ref_frame: i8, fctx: &crate::decode::FrameCtx,
6683 ) {
6684 let (mi_r, mi_c) = at_mi;
6685 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
6686 // half its luma one (min 4 px, the smallest transform), capped at
6687 // TX_32X32 -- independent of this block's luma `tx_depth`.
6688 let uv_tx_w = ((w_mi * MI / 2).max(4).min(32)) as u8;
6689 let uv_tx_h = ((h_mi * MI / 2).max(4).min(32)) as u8;
6690 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
6691 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}");
6692 }
6693 let cur = fctx.current_delta_lf.with(|c| c.get());
6694 let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) {
6695 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
6696 } else {
6697 [cur[0].clamp(-63, 63) as i8; 4]
6698 };
6699 for rr in 0..h_mi {
6700 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
6701 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
6702 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
6703 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_tx_w);
6704 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_tx_h);
6705 fill_span(&mut self.ref_grid, start, w_mi, ref_frame);
6706 fill_span(&mut self.delta_lf_grid, start, w_mi, snapshot);
6707 }
6708 }
6709
6710 /// One var-tx / split-tx LEAF's own LUMA transform dims over its mi span.
6711 /// libaom `get_transform_size` (av1_loopfilter.c:207) applies the split
6712 /// override only `if ((plane == AOM_PLANE_Y) && ...)` -- chroma keeps
6713 /// `av1_get_max_uv_txsize(mbmi->bsize)`, the whole BLOCK's uv transform.
6714 /// Routing a leaf through [`Self::fill_lf_grid_rect`] recomputed the uv
6715 /// dims from the LEAF span and so invented chroma transform edges the
6716 /// deblocker then filtered (lane-golomb r6). `ref_grid`/`delta_lf_grid`
6717 /// are already correct from the block's own fill over the same span.
6718 fn fill_lf_grid_leaf_luma(
6719 &mut self,
6720 at_mi: (usize, usize),
6721 w_mi: usize,
6722 h_mi: usize,
6723 tx_px: u8,
6724 tx_h_px: u8,
6725 ) {
6726 let (mi_r, mi_c) = at_mi;
6727 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
6728 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}");
6729 }
6730 for rr in 0..h_mi {
6731 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
6732 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
6733 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
6734 }
6735 }
6736
6737 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
6738 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
6739 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
6740 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
6741 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
6742 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
6743 }
6744
6745 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
6746 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
6747 let (mi_r, mi_c) = at_mi;
6748 if skip && w_mi != h_mi {
6749 RECT_SKIP_BAND_HITS.with(|c| c.set(c.get() + 1));
6750 }
6751 for rr in 0..h_mi {
6752 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
6753 fill_span(&mut self.skip_grid, start, w_mi, skip);
6754 fill_span(&mut self.skip_written, start, w_mi, true);
6755 fill_span(&mut self.blk_org_grid, start, w_mi, [mi_r as u16, mi_c as u16]);
6756 fill_span(&mut self.blk_dim_grid, start, w_mi, [w_mi as u8, h_mi as u8]);
6757 }
6758 }
6759
6760 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
6761 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
6762 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
6763 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
6764 /// straddle the region with a mix of skip/non-skip blocks).
6765 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
6766 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
6767 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
6768 /// filtered edge's two sides are each exactly one coded block wide.
6769 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
6770 self.skip_grid
6771 .get(mi_r * self.skip_grid_cols_mi + mi_c)
6772 .copied()
6773 .unwrap_or(false)
6774 }
6775
6776 /// The `skip_txfm` context of a block whose top-left mi cell is
6777 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
6778 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
6779 /// with an absent neighbour contributing 0. The mi grid is per tile, so
6780 /// row/column 0 is a tile edge and has no neighbour on that axis.
6781 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
6782 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
6783 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
6784 }
6785
6786 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
6787 (0..2).all(|rr| {
6788 (0..2).all(|cc| {
6789 self.skip_grid
6790 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
6791 .copied()
6792 .unwrap_or(false)
6793 })
6794 })
6795 }
6796
6797 fn start_row(&mut self) {
6798 self.left.iter_mut().for_each(|l| *l = Default::default());
6799 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
6800 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
6801 self.left_side.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
6802 self.left_side_mi.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
6803 self.left_skip.iter_mut().for_each(|s| *s = false);
6804 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
6805 self.left_inter.iter_mut().for_each(|i| *i = false);
6806 self.left_ref.iter_mut().for_each(|r| *r = -1);
6807 self.left_ref1.iter_mut().for_each(|r| *r = None);
6808 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
6809 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
6810 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
6811 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
6812 // context (a tile/SB-row boundary has no left neighbour).
6813 self.sub8_mode_row.iter_mut().for_each(|s| *s = (usize::MAX, 0));
6814 self.uv_mode_row.iter_mut().for_each(|s| *s = (usize::MAX, 0));
6815 // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands
6816 // are per-mi maps like every other one here, so they reset with the
6817 // row too -- the left guard above is what actually stops a cross-tile
6818 // read, this keeps a stale colour out of the arrays at all.
6819 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
6820 self.left_palette_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
6821 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
6822 self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
6823 // lane-mergefix r2: `av1_zero_left_context` memsets
6824 // `left_txfm_context_buffer` to `tx_size_high[TX_SIZES_LARGEST]` at
6825 // every superblock row of every tile -- the var-tx left context does
6826 // NOT carry over a tile boundary (its `txfm_partition` ctx read the
6827 // previous tile column's last block otherwise).
6828 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
6829 }
6830
6831 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
6832 /// block that reads it as a neighbour -- [`crate::tile`]'s
6833 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
6834 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
6835 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
6836 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
6837 /// the real value, not just `is_inter`).
6838 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6839 fn record_inter(
6840 &mut self,
6841 at: (usize, usize),
6842 side: usize,
6843 skip: bool,
6844 is_inter: bool,
6845 ref_frame: i8,
6846 filter: [u8; 2],
6847 skip_mode: bool,
6848 ) {
6849 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
6850 }
6851
6852 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
6853 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
6854 /// r1: a true rectangular strip's above-context span (its own width) and
6855 /// left-context span (its own height) differ, unlike every caller before
6856 /// this round (class neighbour-votes-all-its-fields).
6857 #[allow(clippy::too_many_arguments)]
6858 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6859 fn record_inter_rect(
6860 &mut self,
6861 at: (usize, usize),
6862 w_sub: usize,
6863 h_sub: usize,
6864 skip: bool,
6865 is_inter: bool,
6866 ref_frame: i8,
6867 filter: [u8; 2],
6868 skip_mode: bool,
6869 ) {
6870 let (r, c) = at;
6871 self.record_inter_rect_mi(
6872 (r * (SUB / MI), c * (SUB / MI)),
6873 w_sub / MI,
6874 h_sub / MI,
6875 skip,
6876 is_inter,
6877 ref_frame,
6878 filter,
6879 skip_mode,
6880 );
6881 }
6882
6883 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
6884 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
6885 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
6886 /// routes through the wrapper above.
6887 #[allow(clippy::too_many_arguments)]
6888 fn record_inter_rect_mi(
6889 &mut self,
6890 at_mi: (usize, usize),
6891 w_mi: usize,
6892 h_mi: usize,
6893 skip: bool,
6894 is_inter: bool,
6895 ref_frame: i8,
6896 filter: [u8; 2],
6897 skip_mode: bool,
6898 ) {
6899 let (r, c) = at_mi;
6900 // lane-t900 r8 (class new-map-ignores-tile-edge's twin: a map NOBODY
6901 // writes for a whole block class): an INTER block left the luma mode
6902 // map untouched, so a later intra block's `get_intra_edge_filter_type`
6903 // (spec 7.11.2, libaom `reconintra.h`'s `is_smooth`) fell back to the
6904 // coarse SUB-row band, which still held a SMOOTH mode from an earlier
6905 // block in that pixel row -- the directional edge filter then ran at
6906 // strength 3 instead of 2. libaom reads `mbmi->mode` of the neighbour,
6907 // which for an inter block is an INTER mode (>= NEARESTMV) and is
6908 // never smooth; DC_PRED is this map's equivalent (the sub-8x8 groups
6909 // already stamped it).
6910 // The chroma twin: `is_smooth(mbmi, plane > 0)` returns 0 outright for
6911 // an inter neighbour ("uv_mode is not set for inter blocks"), so the
6912 // uv map must read DC_PRED over an inter block's cells too.
6913 if is_inter {
6914 self.record_mode_mi(r, c, w_mi, h_mi, DC_PRED);
6915 self.record_uv_mode_mi(r, c, w_mi, h_mi, DC_PRED);
6916 }
6917 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
6918 self.above_skip[c..c + w_mi].fill(skip);
6919 self.above_skip_mode[c..c + w_mi].fill(skip_mode);
6920 self.above_inter[c..c + w_mi].fill(is_inter);
6921 self.above_ref[c..c + w_mi].fill(ref_frame);
6922 // lane-av1comp: no caller of `record_inter` ever decodes a
6923 // compound block yet (see [`Self::above_ref1`]'s doc); the
6924 // parameter this becomes lands with `read_ref_frames`.
6925 self.above_ref1[c..c + w_mi].fill(None);
6926 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
6927 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
6928 // as `3`/`1` even though this block has no second reference.
6929 // `record_compound_ctx` overwrites this with the real bit for an
6930 // actual compound block's cells, called right after this one.
6931 self.above_comp_group_idx[c..c + w_mi].fill(if altref { 3 } else { 0 });
6932 self.above_compound_idx[c..c + w_mi].fill(u8::from(altref));
6933 self.above_filter[c..c + w_mi].fill(filter);
6934 self.left_skip[r..r + h_mi].fill(skip);
6935 self.left_skip_mode[r..r + h_mi].fill(skip_mode);
6936 self.left_inter[r..r + h_mi].fill(is_inter);
6937 self.left_ref[r..r + h_mi].fill(ref_frame);
6938 self.left_ref1[r..r + h_mi].fill(None);
6939 self.left_comp_group_idx[r..r + h_mi].fill(if altref { 3 } else { 0 });
6940 self.left_compound_idx[r..r + h_mi].fill(u8::from(altref));
6941 self.left_filter[r..r + h_mi].fill(filter);
6942 }
6943
6944 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
6945 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
6946 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
6947 /// `get_comp_index_context`) -- called right after `record_inter` for
6948 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
6949 /// stamps `above_ref1`/`left_ref1` with the block's real second
6950 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
6951 /// this is the one caller that actually knows it) -- so the next block's
6952 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
6953 /// neighbour instead of `record_inter`'s single-ref default.
6954 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6955 fn record_compound_ctx(
6956 &mut self,
6957 at: (usize, usize),
6958 side: usize,
6959 ref1: i8,
6960 comp_group_idx: u8,
6961 compound_idx: u8,
6962 ) {
6963 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
6964 }
6965
6966 /// [`Self::record_compound_ctx`] with independent above/left extents,
6967 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
6968 #[allow(clippy::too_many_arguments)]
6969 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6970 fn record_compound_ctx_rect(
6971 &mut self,
6972 at: (usize, usize),
6973 w_sub: usize,
6974 h_sub: usize,
6975 ref1: i8,
6976 comp_group_idx: u8,
6977 compound_idx: u8,
6978 ) {
6979 let (r, c) = at;
6980 self.record_compound_ctx_rect_mi(
6981 (r * (SUB / MI), c * (SUB / MI)),
6982 w_sub / MI,
6983 h_sub / MI,
6984 ref1,
6985 comp_group_idx,
6986 compound_idx,
6987 );
6988 }
6989
6990 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
6991 /// [`Self::record_inter_rect_mi`]).
6992 fn record_compound_ctx_rect_mi(
6993 &mut self,
6994 at_mi: (usize, usize),
6995 w_mi: usize,
6996 h_mi: usize,
6997 ref1: i8,
6998 comp_group_idx: u8,
6999 compound_idx: u8,
7000 ) {
7001 let (r, c) = at_mi;
7002 for cell in 0..w_mi {
7003 self.above_ref1[c + cell] = Some(ref1);
7004 self.above_comp_group_idx[c + cell] = comp_group_idx;
7005 self.above_compound_idx[c + cell] = compound_idx;
7006 }
7007 for cell in 0..h_mi {
7008 self.left_ref1[r + cell] = Some(ref1);
7009 self.left_comp_group_idx[r + cell] = comp_group_idx;
7010 self.left_compound_idx[r + cell] = compound_idx;
7011 }
7012 }
7013
7014 /// The context of a block's partition symbol: delegates to the mi-precise
7015 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
7016 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
7017 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
7018 /// only touches the finer mi arrays -- leaves them stale for the *next*
7019 /// sibling's own partition symbol.
7020 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
7021 let (r, c) = at;
7022 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
7023 }
7024
7025 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
7026 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
7027 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
7028 /// than the enclosing 16x16 slot's stale, shared state.
7029 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
7030 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side)
7031 + usize::from(self.above_side_mi[mi_c] * 2 <= side)
7032 }
7033
7034 /// The gathered coded/DC-sign state of the blocks above and to the left
7035 /// of a block `side` samples across, per plane.
7036 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
7037 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
7038 }
7039
7040 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
7041 /// units, for the same reason [`Self::record_mi`] does.
7042 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
7043 let side_mi = side / MI;
7044 std::array::from_fn(|plane| {
7045 let mut above_coded = false;
7046 let mut left_coded = false;
7047 let mut vote = 0;
7048 for cell in 0..side_mi {
7049 let above = &self.above[mi_c + cell][plane];
7050 let left = &self.left[mi_r + cell][plane];
7051 above_coded |= above.level != 0;
7052 left_coded |= left.level != 0;
7053 vote += dc_vote(above.dc) + dc_vote(left.dc);
7054 }
7055 (above_coded, left_coded, vote)
7056 })
7057 }
7058
7059 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
7060 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
7061 /// extent pattern for a true rectangular strip's own coefficient context.
7062 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
7063 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
7064 }
7065
7066 /// [`Self::around_rect`] taking the block's position directly in 4x4
7067 /// mode-info units, mirroring [`Self::around_mi`].
7068 fn around_mi_rect(&self, (mi_r, mi_c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
7069 let (w_mi, h_mi) = (w / MI, h / MI);
7070 std::array::from_fn(|plane| {
7071 let mut above_coded = false;
7072 let mut left_coded = false;
7073 let mut vote = 0;
7074 for cell in 0..w_mi {
7075 let above = &self.above[mi_c + cell][plane];
7076 above_coded |= above.level != 0;
7077 vote += dc_vote(above.dc);
7078 }
7079 for cell in 0..h_mi {
7080 let left = &self.left[mi_r + cell][plane];
7081 left_coded |= left.level != 0;
7082 vote += dc_vote(left.dc);
7083 }
7084 if crate::envflags::env_flag!("EC_DCDUMP") {
7085 let ab: Vec<String> = (0..w_mi)
7086 .map(|k| format!("{:?}/{}", self.above[mi_c + k][plane].dc, self.above[mi_c + k][plane].level))
7087 .collect();
7088 let lf: Vec<String> = (0..h_mi)
7089 .map(|k| format!("{:?}/{}", self.left[mi_r + k][plane].dc, self.left[mi_r + k][plane].level))
7090 .collect();
7091 eprintln!("EC_DCDUMP mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]", ab.join(","), lf.join(","));
7092 }
7093 (above_coded, left_coded, vote)
7094 })
7095 }
7096
7097 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
7098 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
7099 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
7100 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
7101 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
7102 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
7103 /// is always 0, spec's `plane_bsize == tx_size` branch).
7104 fn luma_skip_ctx(&self, at_mi: (usize, usize), side_mi: usize) -> usize {
7105 self.luma_skip_ctx_rect(at_mi, side_mi, side_mi)
7106 }
7107
7108 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi
7109 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above
7110 /// context over `tx_size_wide` and the left one over `tx_size_high`.
7111 fn luma_skip_ctx_rect(
7112 &self,
7113 (mi_r, mi_c): (usize, usize),
7114 w_mi: usize,
7115 h_mi: usize,
7116 ) -> usize {
7117 let side_mi = w_mi;
7118 let mut top = 0u8;
7119 let mut left = 0u8;
7120 for cell in 0..w_mi {
7121 top |= self.above[mi_c + cell][0].level;
7122 }
7123 for cell in 0..h_mi {
7124 left |= self.left[mi_r + cell][0].level;
7125 }
7126 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
7127 if crate::envflags::env_flag!("EC_ECDUMP") {
7128 let ab: Vec<String> =
7129 (0..w_mi).map(|k| self.above[mi_c + k][0].level.to_string()).collect();
7130 let lf: Vec<String> =
7131 (0..h_mi).map(|k| self.left[mi_r + k][0].level.to_string()).collect();
7132 eprintln!(
7133 "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},]",
7134 ab.join(","), lf.join(",")
7135 );
7136 }
7137 if crate::envflags::env_flag!("EC_AV1_TRACE") {
7138 eprintln!(
7139 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx} band={:?}",
7140 self.left.iter().map(|e| e[0].level).collect::<Vec<_>>()
7141 );
7142 }
7143 ctx
7144 }
7145
7146 /// Writes one coded block into every cell it covers, on both grids: the
7147 /// mode/side arrays up to `side`'s own width, and the coefficient-context
7148 /// arrays up to the true frame edge — the units past it are left at their
7149 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
7150 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
7151 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
7152 /// not from this block's own side).
7153 fn record(
7154 &mut self,
7155 at: (usize, usize),
7156 side: usize,
7157 mode: usize,
7158 uv_mode: usize,
7159 grids: &[Vec<i32>; 3],
7160 ) {
7161 self.record_rect(at, side, side, mode, uv_mode, grids);
7162 }
7163
7164 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
7165 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
7166 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
7167 /// spec's per-edge partition-context rule, so a true rectangular block
7168 /// naturally wants two different values here rather than one.
7169 /// Writes this block's luma `mode` into the mi-granular
7170 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
7171 /// position a *later* neighbour would read it from: the block's LAST mi
7172 /// row for every column it spans (what the block below reads via
7173 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
7174 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
7175 /// read these back, and only when the recorded position is exactly their
7176 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
7177 fn record_mode_mi(
7178 &mut self,
7179 mi_r: usize,
7180 mi_c: usize,
7181 mi_w: usize,
7182 mi_h: usize,
7183 mode: usize,
7184 ) {
7185 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
7186 for cell in 0..mi_w {
7187 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
7188 *slot = (last_r, mode);
7189 }
7190 }
7191 for cell in 0..mi_h {
7192 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
7193 *slot = (last_c, mode);
7194 }
7195 }
7196 }
7197
7198 /// The mi-exact above/left neighbour luma mode for a block whose top-left
7199 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
7200 /// mi position (then the coarse [`SUB`]-grid slot is right by
7201 /// construction). See [`Self::record_mode_mi`].
7202 fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
7203 match self.sub8_mode_col.get(mi_c) {
7204 Some(&(row, m)) if mi_r > self.tile_row0_mi && row == mi_r - 1 => Some(m),
7205 _ => None,
7206 }
7207 }
7208
7209 fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
7210 match self.sub8_mode_row.get(mi_r) {
7211 Some(&(col, m)) if mi_c > self.tile_col0_mi && col == mi_c - 1 => Some(m),
7212 _ => None,
7213 }
7214 }
7215
7216 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
7217 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
7218 fn record_uv_mode_mi(
7219 &mut self,
7220 mi_r: usize,
7221 mi_c: usize,
7222 mi_w: usize,
7223 mi_h: usize,
7224 uv_mode: usize,
7225 ) {
7226 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
7227 fill_span(&mut self.uv_mode_col, mi_c, mi_w, (last_r, uv_mode));
7228 fill_span(&mut self.uv_mode_row, mi_r, mi_h, (last_c, uv_mode));
7229 // libaom writes one `MB_MODE_INFO` pointer into every mi cell a block
7230 // covers, so the chroma neighbour read below is a plain grid read.
7231 let stride = self.uv_grid_cols;
7232 let n = stride.saturating_sub(mi_c).min(last_c + 1 - mi_c);
7233 for row in mi_r..=last_r {
7234 fill_span(&mut self.uv_mode_grid, row * stride + mi_c, n, uv_mode as u8);
7235 }
7236 }
7237
7238 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
7239 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
7240 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
7241 /// block has recorded the exact neighbouring mi.
7242 fn smooth_uv_neighbour(&self, mi_r: usize, mi_c: usize, r: usize, c: usize) -> bool {
7243 // lane-kf900 r2: libaom reads the chroma neighbours off the CHROMA
7244 // REFERENCE block, not off the mi that carries the chroma syntax.
7245 // `set_mi_row_col` (`blockd.h`) takes
7246 // `base_mi = &xd->mi[-(mi_row & ss_y) * stride - (mi_col & ss_x)]` and
7247 // only then `chroma_above_mbmi = base_mi[-stride]` /
7248 // `chroma_left_mbmi = base_mi[-1]`. A sub-8 pair codes its chroma at
7249 // the ODD mi, so without the snap we looked one mi row/column too far
7250 // down/right -- the mi-exact slot never matched and the coarse
7251 // fallback answered instead. Measured on a 4K 10-bit key frame, chroma
7252 // 8x4 at (688, 100) = mi (51, 344): libaom's
7253 // `get_intra_edge_filter_type` is 1 (the chroma block above it is
7254 // `UV_SMOOTH_PRED`), ours was 0, which flips
7255 // `av1_use_intra_edge_upsample(8, 4, -6, type)` (`blk_wh == 12`:
7256 // false for type 1, TRUE for type 0) and upsampled an edge libaom
7257 // leaves alone -- +1 on rows 2/3 of that block and every chroma block
7258 // predicting from it (class `context-read-from-one-cell`).
7259 self.smooth_uv_neighbour_unsnapped(mi_r & !1, mi_c & !1, r, c)
7260 }
7261
7262 /// [`Self::smooth_uv_neighbour`] without the chroma-reference snap, i.e.
7263 /// read off the mi passed in exactly. Only the 16x4/4x16 pair witness
7264 /// counter wants this: it measures how often the snap CHANGES the answer,
7265 /// which is what the lane-kf1200/kf900 chroma-reference fix buys. Every
7266 /// decode path uses the snapping form.
7267 fn smooth_uv_neighbour_unsnapped(
7268 &self,
7269 mi_r: usize,
7270 mi_c: usize,
7271 r: usize,
7272 c: usize,
7273 ) -> bool {
7274 // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the
7275 // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid
7276 // array that `start_tile` does not clear, so a block on a tile's first
7277 // mi row used to read the uv_mode of the block above it in the tile
7278 // ABOVE and filter its chroma edge at that neighbour's strength
7279 // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block
7280 // at chroma (120, 32), the top-right tile's first block).
7281 let have_above = mi_r > self.tile_row0_mi;
7282 let have_left = mi_c > self.tile_col0_mi;
7283 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
7284 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
7285 {
7286 UV_TILE_EDGE_SUPPRESSED_HITS.with(|h| h.set(h.get() + 1));
7287 }
7288 // The mi grid is libaom's own read; the two maps below stay as the
7289 // fallback for cells no block has written (see [`Self::uv_mode_grid`]).
7290 let cell = |grid: &Vec<u8>, row: usize, col: usize| -> Option<usize> {
7291 (col < self.uv_grid_cols)
7292 .then(|| grid.get(row * self.uv_grid_cols + col).copied())
7293 .flatten()
7294 .filter(|&m| m != u8::MAX)
7295 .map(usize::from)
7296 };
7297 let above = match self.uv_mode_col.get(mi_c) {
7298 _ if have_above && let Some(m) = cell(&self.uv_mode_grid, mi_r - 1, mi_c) => m,
7299 Some(&(row, m)) if have_above && row == mi_r - 1 => m,
7300 _ if have_above => self.above_uv_mode[c],
7301 _ => DC_PRED,
7302 };
7303 let left = match self.uv_mode_row.get(mi_r) {
7304 _ if have_left && let Some(m) = cell(&self.uv_mode_grid, mi_r, mi_c - 1) => m,
7305 Some(&(col, m)) if have_left && col == mi_c - 1 => m,
7306 _ if have_left => self.left_uv_mode[r],
7307 _ => DC_PRED,
7308 };
7309 if have_above && cell(&self.uv_mode_grid, mi_r - 1, mi_c).is_some_and(|m| {
7310 !matches!(self.uv_mode_col.get(mi_c), Some(&(row, cm)) if row == mi_r - 1 && cm == m)
7311 }) || have_left && cell(&self.uv_mode_grid, mi_r, mi_c - 1).is_some_and(|m| {
7312 !matches!(self.uv_mode_row.get(mi_r), Some(&(col, cm)) if col == mi_c - 1 && cm == m)
7313 }) {
7314 UV_MODE_GRID_OVERRIDE_HITS.with(|h| h.set(h.get() + 1));
7315 }
7316 // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs
7317 // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would
7318 // have been filtered at the wrong strength by the coarse map alone.
7319 if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] {
7320 UV_MODE_MI_OVERRIDE_HITS.with(|h| h.set(h.get() + 1));
7321 }
7322 if (is_smooth_mode(self.above_uv_mode[c]) && !is_smooth_mode(above))
7323 || (is_smooth_mode(self.left_uv_mode[r]) && !is_smooth_mode(left))
7324 {
7325 INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|h| h.set(h.get() + 1));
7326 }
7327 is_smooth_mode(above) || is_smooth_mode(left)
7328 }
7329
7330 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
7331 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
7332 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
7333 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
7334 /// holding an OLDER, larger block's mode -- it only ever recorded into the
7335 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
7336 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
7337 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
7338 /// a different CDF for the same mode value).
7339 /// lane-rectsplitx r2: availability-correct above/left luma modes for a
7340 /// block whose top-left mi is `(mi_r, mi_c)`. libaom reads `above_mbmi`
7341 /// only when `up_available` and `left_mbmi` only when `left_available`;
7342 /// the coarse [`SUB`] bands cannot express that, and with 8-px strips they
7343 /// actively lie -- four 32x8 strips of one `HORZ_4` share ONE 16x16
7344 /// `left_mode` cell, so the second strip at tile column 0 read the FIRST
7345 /// strip's mode as its "left neighbour" (measured on the band fixture at
7346 /// mi(10,0): mode 2 where libaom has DC, a different `kf_y_mode` row).
7347 fn modes_above_left_mi(
7348 &self,
7349 mi_r: usize,
7350 mi_c: usize,
7351 fallback: (usize, usize),
7352 ) -> (usize, usize) {
7353 let above = if mi_r > self.tile_row0_mi {
7354 self.mode_above_mi(mi_r, mi_c).unwrap_or(fallback.0)
7355 } else {
7356 DC_PRED
7357 };
7358 let left = if mi_c > self.tile_col0_mi {
7359 self.mode_left_mi(mi_r, mi_c).unwrap_or(fallback.1)
7360 } else {
7361 DC_PRED
7362 };
7363 (above, left)
7364 }
7365
7366 /// lane-modectx r1: the coarse-[`SUB`]-grid entry point, now availability
7367 /// correct. The mi-exact lookups already refuse to cross a tile edge, but
7368 /// their FALLBACK (`above_mode`/`left_mode`) did not: `left_mode` is reset
7369 /// per superblock row and never per tile, so the first block column of
7370 /// tile 2..N read the previous tile's mode as its left neighbour, and the
7371 /// above band survives across a tile ROW boundary the same way lane-mtfix's
7372 /// `above_uv_mode` did. libaom reads `above_mbmi`/`left_mbmi` only when
7373 /// `up_available`/`left_available` and uses DC_PRED otherwise
7374 /// ([`Self::modes_above_left_mi`]).
7375 fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
7376 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
7377 let (above, left) =
7378 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));
7379 if above != self.above_mode[c] || left != self.left_mode[r] {
7380 MODE_MI_OVERRIDE_HITS.with(|h| h.set(h.get() + 1));
7381 }
7382 if (is_smooth_mode(self.above_mode[c]) && !is_smooth_mode(above))
7383 || (is_smooth_mode(self.left_mode[r]) && !is_smooth_mode(left))
7384 {
7385 INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|h| h.set(h.get() + 1));
7386 }
7387 // A neighbour the coarse band offered where the tile edge makes it
7388 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).
7389 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)
7390 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)
7391 {
7392 MODE_TILE_EDGE_COARSE_LEAKS.with(|h| h.set(h.get() + 1));
7393 }
7394 (above, left)
7395 }
7396
7397 fn record_rect(
7398 &mut self,
7399 at: (usize, usize),
7400 w: usize,
7401 h: usize,
7402 mode: usize,
7403 uv_mode: usize,
7404 grids: &[Vec<i32>; 3],
7405 ) {
7406 self.record_rect_mi(sub16_to_mi(at), w, h, mode, uv_mode, grids);
7407 }
7408
7409 /// [`Self::record_rect`] in mi (4 px) units -- lane-inter4 r1: a
7410 /// 32x8/8x32 strip of a 32-level 1:4 partition sits at an 8-px offset the
7411 /// [`SUB`]-unit `at` cannot name. The coarse 16-px bands are still keyed
7412 /// by the enclosing cell (a sub-16 extent writes none of them, exactly as
7413 /// the [`SUB`]-unit path does).
7414 fn record_rect_mi(
7415 &mut self,
7416 at_mi: (usize, usize),
7417 w: usize,
7418 h: usize,
7419 mode: usize,
7420 uv_mode: usize,
7421 grids: &[Vec<i32>; 3],
7422 ) {
7423 let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI));
7424 // lane-inter4 r2: a strip whose own footprint runs past the frame's
7425 // last 16-px column/row stamps only the cells that exist (libaom's
7426 // arrays are padded past the frame and those cells are never read).
7427 for cell in 0..w / SUB {
7428 if c + cell >= self.above_mode.len() {
7429 break;
7430 }
7431 self.above_mode[c + cell] = mode;
7432 self.above_uv_mode[c + cell] = uv_mode;
7433 self.above_side[c + cell] = w;
7434 }
7435 for cell in 0..h / SUB {
7436 if r + cell >= self.left_mode.len() {
7437 break;
7438 }
7439 self.left_mode[r + cell] = mode;
7440 self.left_uv_mode[r + cell] = uv_mode;
7441 self.left_side[r + cell] = h;
7442 }
7443 self.record_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, mode);
7444 self.record_uv_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, uv_mode);
7445 self.record_mi_rect(at_mi, w, h, grids);
7446 }
7447
7448 /// The coefficient-context half of [`Self::record`], taking the block's
7449 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
7450 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
7451 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
7452 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
7453 self.record_mi_rect(at_mi, side, side, grids);
7454 }
7455
7456 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
7457 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
7458 fn record_mi_rect(
7459 &mut self,
7460 at_mi: (usize, usize),
7461 w: usize,
7462 h: usize,
7463 grids: &[Vec<i32>; 3],
7464 ) {
7465 let (mi_r, mi_c) = at_mi;
7466 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
7467 let (w_mi, h_mi) = (w / MI, h / MI);
7468 if crate::envflags::env_flag!("EC_ECPUB") {
7469 eprintln!("EC_ECPUB blk mi=({mi_r},{mi_c}) wh=({w},{h}) lvl={}", states[0].level);
7470 }
7471 fill_span(&mut self.left_side_mi, mi_r, h_mi, h);
7472 fill_span(&mut self.above_side_mi, mi_c, w_mi, w);
7473 // A chroma 4x4 unit straddling the true luma edge is still whole in
7474 // chroma's own halved grid, so libaom rounds the luma bound up to the
7475 // plane's own 4x4 unit before clamping a subsampled plane
7476 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
7477 let round_up_even = |n: usize| n.div_ceil(2) * 2;
7478 let bound_h = [
7479 self.mi_rows,
7480 round_up_even(self.mi_rows),
7481 round_up_even(self.mi_rows),
7482 ];
7483 let bound_w = [
7484 self.mi_cols,
7485 round_up_even(self.mi_cols),
7486 round_up_even(self.mi_cols),
7487 ];
7488 // lane-sb128c r7: a 128x64 at the bottom frame edge names mi rows
7489 // past the padded side arrays (mi_rows 198, block rows 192..208);
7490 // libaom's own arrays are superblock-sized, so those cells simply
7491 // have no reader -- [`fill_span`] drops them, as the `break` did.
7492 // `bound_h[1] == bound_h[2] >= bound_h[0]`, so the per-cell plane
7493 // predicate is three contiguous runs: all planes, chroma only, none
7494 // (lane-mi).
7495 let luma_h = h_mi.min(bound_h[0].saturating_sub(mi_r));
7496 let chroma_h = h_mi.min(bound_h[1].saturating_sub(mi_r));
7497 let uv_only = [Neighbour::default(), states[1], states[2]];
7498 fill_span(&mut self.left, mi_r, luma_h, states);
7499 fill_span(&mut self.left, mi_r + luma_h, chroma_h - luma_h, uv_only);
7500 fill_span(
7501 &mut self.left,
7502 mi_r + chroma_h,
7503 h_mi - chroma_h,
7504 [Neighbour::default(); 3],
7505 );
7506 let luma_w = w_mi.min(bound_w[0].saturating_sub(mi_c));
7507 let chroma_w = w_mi.min(bound_w[1].saturating_sub(mi_c));
7508 let uv_only_w = [Neighbour::default(), states[1], states[2]];
7509 fill_span(&mut self.above, mi_c, luma_w, states);
7510 fill_span(&mut self.above, mi_c + luma_w, chroma_w - luma_w, uv_only_w);
7511 fill_span(
7512 &mut self.above,
7513 mi_c + chroma_w,
7514 w_mi - chroma_w,
7515 [Neighbour::default(); 3],
7516 );
7517 }
7518
7519 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
7520 /// inside a coded block whose luma transform is smaller than its own
7521 /// side (`TxMode::Select`): the real per-transform-unit coefficient
7522 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
7523 /// coarse per-block `tx_grid`/`fill_lf_grid` state
7524 /// [`Self::record_split_luma`] still writes once for the whole block.
7525 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
7526 /// the caller's own [`Self::record_split_luma`] call sets those once,
7527 /// at the block's own true side, not this TU's.
7528 fn record_mi_luma(&mut self, at_mi: (usize, usize), tx_px: usize, grid: &[i32]) {
7529 self.record_mi_luma_rect(at_mi, tx_px, tx_px, grid);
7530 }
7531
7532 /// [`Self::record_mi_luma`] for ONE CHROMA transform unit of a block whose
7533 /// uv plane block is several units (lane-sb128b r2: a 128x128 block's
7534 /// 64x64 uv plane block is four TX_32X32 units, `av1_get_max_uv_txsize`).
7535 /// `w_px`/`h_px` are the unit's extent in LUMA pixels -- the chroma
7536 /// coefficient-context arrays are indexed by luma mi, the convention
7537 /// [`Self::record_split_luma_rect_mi`] already writes them in, frame-edge
7538 /// clamp included.
7539 fn record_mi_chroma(
7540 &mut self,
7541 (mi_r, mi_c): (usize, usize),
7542 w_px: usize,
7543 h_px: usize,
7544 plane: usize,
7545 grid: &[i32],
7546 ) {
7547 let round_up_even = |n: usize| n.div_ceil(2) * 2;
7548 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
7549 let state = neighbour_state(grid);
7550 for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) {
7551 self.left[mi_r + cell][plane] = state;
7552 }
7553 for cell in 0..(w_px / MI).min(bound_w.saturating_sub(mi_c)) {
7554 self.above[mi_c + cell][plane] = state;
7555 }
7556 }
7557
7558 /// [`Self::record_mi_luma`] for a RECTANGULAR transform unit (lane-rectsplitx
7559 /// r1): the above context spans the unit's width, the left context its
7560 /// height, which for a square unit is the same loop it always was.
7561 fn record_mi_luma_rect(
7562 &mut self,
7563 (mi_r, mi_c): (usize, usize),
7564 w_px: usize,
7565 h_px: usize,
7566 grid: &[i32],
7567 ) {
7568 let state = neighbour_state(grid);
7569 if crate::envflags::env_flag!("EC_ECPUB") {
7570 eprintln!("EC_ECPUB tu mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={}", state.level);
7571 }
7572 for cell in 0..h_px / MI {
7573 if mi_r + cell < self.mi_rows {
7574 self.left[mi_r + cell][0] = state;
7575 }
7576 }
7577 for cell in 0..w_px / MI {
7578 if mi_c + cell < self.mi_cols {
7579 self.above[mi_c + cell][0] = state;
7580 }
7581 }
7582 }
7583
7584 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
7585 /// block whose luma was decoded as several transform units through
7586 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
7587 /// whole-block luma write -- everything [`Self::record`] does except
7588 /// plane 0, which is already correct per-TU by the time this runs.
7589 fn record_split_luma(
7590 &mut self,
7591 at: (usize, usize),
7592 side: usize,
7593 mode: usize,
7594 uv_mode: usize,
7595 chroma_grids: [&[i32]; 2],
7596 ) {
7597 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
7598 }
7599
7600 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
7601 /// extents in pixels (lane-rectsplit r1), the same relationship
7602 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
7603 /// luma transform split into several square units needs exactly this
7604 /// bookkeeping, at its own true rectangular extents.
7605 fn record_split_luma_rect(
7606 &mut self,
7607 at: (usize, usize),
7608 w: usize,
7609 h: usize,
7610 mode: usize,
7611 uv_mode: usize,
7612 chroma_grids: [&[i32]; 2],
7613 ) {
7614 let (r, c) = at;
7615 self.record_split_luma_rect_mi(
7616 (r * (SUB / MI), c * (SUB / MI)),
7617 w,
7618 h,
7619 mode,
7620 uv_mode,
7621 chroma_grids,
7622 );
7623 }
7624
7625 /// [`Self::record_split_luma_rect`] addressed in mi units (lane-rectsplitx
7626 /// r1) -- a strip 8 px tall starts mid-[`SUB`]-cell, which the coarse
7627 /// `(r, c)` form cannot name. The coarse mode/side arrays are stamped for
7628 /// every cell the strip TOUCHES (`div_ceil`), last writer wins, the
7629 /// convention [`decode_block_rect4`] already established for 1:4 strips.
7630 fn record_split_luma_rect_mi(
7631 &mut self,
7632 at_mi: (usize, usize),
7633 w: usize,
7634 h: usize,
7635 mode: usize,
7636 uv_mode: usize,
7637 chroma_grids: [&[i32]; 2],
7638 ) {
7639 let (mi_r, mi_c) = at_mi;
7640 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
7641 for cell in 0..w.div_ceil(SUB) {
7642 if c + cell >= self.above_mode.len() {
7643 break;
7644 }
7645 self.above_mode[c + cell] = mode;
7646 self.above_uv_mode[c + cell] = uv_mode;
7647 self.above_side[c + cell] = w;
7648 }
7649 for cell in 0..h.div_ceil(SUB) {
7650 if r + cell >= self.left_mode.len() {
7651 break;
7652 }
7653 self.left_mode[r + cell] = mode;
7654 self.left_uv_mode[r + cell] = uv_mode;
7655 self.left_side[r + cell] = h;
7656 }
7657
7658 let (w_mi, h_mi) = (w / MI, h / MI);
7659 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
7660 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
7661 fill_span(&mut self.left_side_mi, mi_r, h_mi, h);
7662 fill_span(&mut self.above_side_mi, mi_c, w_mi, w);
7663 let round_up_even = |n: usize| n.div_ceil(2) * 2;
7664 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
7665 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
7666 let plane = plane_idx + 1;
7667 let state = neighbour_state(grid);
7668 for cell in 0..h_mi {
7669 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
7670 self.left[mi_r + cell][plane] = state;
7671 }
7672 }
7673 for cell in 0..w_mi {
7674 if cell < w_mi.min(bound_w.saturating_sub(mi_c)) {
7675 self.above[mi_c + cell][plane] = state;
7676 }
7677 }
7678 }
7679 }
7680}
7681
7682/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
7683/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
7684/// exactly — including its skip context, which the real key-frame writer
7685/// always writes at a fixed context of zero (it never tracks a neighbour-based
7686/// one for intra blocks; that is the inter-frame writer's rule instead).
7687/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
7688/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
7689/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
7690/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
7691/// plain DC chroma.
7692/// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which
7693/// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's
7694/// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode
7695/// instead (the defect commit 1a89ed9 fixed at the square sites).
7696fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize {
7697 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
7698 filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi])
7699}
7700
7701/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
7702/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
7703/// bound (spec `filter_intra_mode_info` never reads a symbol there).
7704fn filter_intra_size_class(side: usize) -> Option<usize> {
7705 match side {
7706 4 => Some(0),
7707 8 => Some(1),
7708 16 => Some(2),
7709 32 => Some(3),
7710 _ => None,
7711 }
7712}
7713
7714/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
7715/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
7716/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
7717/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
7718fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
7719 match (bw, bh) {
7720 (32, 16) => Some(4),
7721 (16, 32) => Some(5),
7722 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
7723 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
7724 // here dropped that symbol on every DC_PRED strip of that size and
7725 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
7726 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
7727 (16, 8) => Some(6),
7728 (8, 16) => Some(7),
7729 // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <=
7730 // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of
7731 // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0.
7732 (4, 8) => Some(8),
7733 (8, 4) => Some(9),
7734 // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair
7735 // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no
7736 // `use_filter_intra` symbol on those strips although aomenc writes
7737 // one for every DC_PRED block of that shape with
7738 // `--enable-filter-intra=1` (its default), silently desyncing the
7739 // tile (class symbol-consumption-gap).
7740 (32, 8) => Some(10),
7741 (8, 32) => Some(11),
7742 // lane-r14: the 16x16-level 1:4 pair (`decode_rect4_16`'s 16x4/4x16
7743 // strips), rows 17/16 of `default_filter_intra_cdfs`.
7744 (16, 4) => Some(12),
7745 (4, 16) => Some(13),
7746 _ if bw == bh => filter_intra_size_class(bw),
7747 _ => None,
7748 }
7749}
7750
7751/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
7752/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
7753/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
7754/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
7755/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
7756fn palette_bsize_ctx(side: usize) -> Option<usize> {
7757 palette_bsize_ctx_wh(side, side)
7758}
7759
7760/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
7761/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
7762/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
7763/// for ANY bsize, not just the square ones a hand-picked table happened to
7764/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
7765/// row breaks the moment its indexing field moves off the diagonal, and a
7766/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
7767/// block dimension is a power of two, so `bw*bh` always is too and
7768/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
7769/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
7770fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
7771 // lane-r14: `av1_allow_palette`'s bound is `sb_type >= BLOCK_8X8` by the
7772 // BLOCK_SIZES_ALL enum INDEX, which the 1:4 shapes BLOCK_4X16 (16) and
7773 // BLOCK_16X4 (17) clear -- a 64-pixel block, so `av1_get_palette_bsize_ctx`
7774 // (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`) is 0 for them, exactly as
7775 // for an 8x8. Reading the dimension bound as "both sides >= 8" dropped
7776 // `palette_y_mode` on every 16x4/4x16 strip of a screen-content frame.
7777 if bw > 64 || bh > 64 || bw * bh < 64 {
7778 return None;
7779 }
7780 Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
7781}
7782
7783/// A just-decoded palette-Y block's own size, base colours (only the first
7784/// `size` entries are real), and per-pixel colour-index map (`side*side`,
7785/// row-major, each entry `< size`).
7786struct PaletteY {
7787 size: usize,
7788 colors: [u16; 8],
7789 map: Vec<u8>,
7790}
7791
7792/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
7793/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
7794/// shared between U and V, both co-located after 4:2:0 subsampling) plus
7795/// each plane's own base colours.
7796struct PaletteUv {
7797 size: usize,
7798 u_colors: [u16; 8],
7799 v_colors: [u16; 8],
7800 map: Vec<u8>,
7801}
7802
7803/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
7804/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
7805/// `get_unsigned_bits`, which is the same formula): smallest `n` with
7806/// `2^n >= x`, `0` for `x <= 1`.
7807fn ceil_log2(x: u32) -> u32 {
7808 if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() }
7809}
7810
7811/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
7812/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
7813fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
7814 let l = ceil_log2(n as u32);
7815 let m = (1usize << l) - n;
7816 let v = dec.literal(l - 1) as usize;
7817 if v < m {
7818 v
7819 } else {
7820 (v << 1) - m + dec.literal(1) as usize
7821 }
7822}
7823
7824/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
7825/// colours (already-known, from the above/left neighbours) with the
7826/// ascending `transmitted` ones (delta-coded off the wire) back into one
7827/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
7828/// value picks the cached copy first, matching the C `<=`.
7829fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
7830 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
7831 let (mut ci, mut ti) = (0, 0);
7832 while ci < cached.len() && ti < transmitted.len() {
7833 if cached[ci] <= transmitted[ti] {
7834 out.push(cached[ci]);
7835 ci += 1;
7836 } else {
7837 out.push(transmitted[ti]);
7838 ti += 1;
7839 }
7840 }
7841 out.extend_from_slice(&cached[ci..]);
7842 out.extend_from_slice(&transmitted[ti..]);
7843 out
7844}
7845
7846/// `read_palette_colors_y` (decodemv.c:478), at the sequence's real
7847/// `bit_depth` -- lane-kf900 r3: every raw literal here (the first colour,
7848/// each delta's width, the `range` bound and the clamp) is sized by
7849/// `bit_depth`, and hardcoding 8 read 2 bits too few per colour on every
7850/// 10-bit palette block. Raw literals are EQUIPROBABLE, and at the ranges
7851/// this stream reaches (e.g. 62728) an equiprobable read is a FIXED POINT of
7852/// the msac range, so a cross-decoder range ladder stays bit-identical
7853/// through the whole miscount -- only the decoded VALUE differs (class
7854/// `compare-range-not-tell`'s blind spot). (this
7855/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
7856/// (one flag bit each, in cache order), then delta-codes the remainder
7857/// (first value raw, each following delta `>= 1` off a shrinking bit width),
7858/// and merges the two ascending lists back together.
7859fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16], fctx: &crate::decode::FrameCtx) -> [u16; 8] {
7860 let mut cached = Vec::with_capacity(n);
7861 for &c in cache {
7862 if cached.len() >= n {
7863 break;
7864 }
7865 if dec.literal(1) == 1 {
7866 cached.push(c);
7867 }
7868 }
7869 let bd = u32::from(bit_depth(fctx));
7870 let max_val = (1i32 << bd) - 1;
7871 let mut colors = [0u16; 8];
7872 let n_cached = cached.len();
7873 if n_cached < n {
7874 let mut transmitted = Vec::with_capacity(n - n_cached);
7875 let first = dec.literal(bd) as u16;
7876 transmitted.push(first);
7877 if n_cached + 1 < n {
7878 let min_bits = bd - 3;
7879 let mut bits = min_bits + dec.literal(2);
7880 let mut range = (1i32 << bd) - i32::from(first) - 1;
7881 for _ in (n_cached + 1)..n {
7882 let delta = dec.literal(bits) as i32 + 1;
7883 let prev = *transmitted.last().unwrap();
7884 let val = (i32::from(prev) + delta).clamp(0, max_val) as u16;
7885 range -= i32::from(val) - i32::from(prev);
7886 bits = bits.min(ceil_log2(range.max(0) as u32));
7887 transmitted.push(val);
7888 }
7889 }
7890 let merged = merge_colors(&transmitted, &cached);
7891 colors[..n].copy_from_slice(&merged);
7892 } else {
7893 colors[..n].copy_from_slice(&cached[..n]);
7894 }
7895 colors
7896}
7897
7898/// `read_palette_colors_uv` (decodemv.c:509), at the sequence's real
7899/// `bit_depth` (see [`read_palette_colors_y`]): U reads
7900/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
7901/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
7902/// unbiased by `+1` -- both differences from Y's own reader, matching the C
7903/// side by side). V never uses a cache: a leading bit picks either `n` raw
7904/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
7905/// rather than clamp.
7906fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16], fctx: &crate::decode::FrameCtx) -> ([u16; 8], [u16; 8]) {
7907 let mut cached = Vec::with_capacity(n);
7908 for &c in cache {
7909 if cached.len() >= n {
7910 break;
7911 }
7912 if dec.literal(1) == 1 {
7913 cached.push(c);
7914 }
7915 }
7916 let bd = u32::from(bit_depth(fctx));
7917 let max_val = 1i32 << bd;
7918 let mut u_colors = [0u16; 8];
7919 let n_cached = cached.len();
7920 if n_cached < n {
7921 let mut transmitted = Vec::with_capacity(n - n_cached);
7922 let first = dec.literal(bd) as u16;
7923 transmitted.push(first);
7924 if n_cached + 1 < n {
7925 let min_bits = bd - 3;
7926 let mut bits = min_bits + dec.literal(2);
7927 let mut range = max_val - i32::from(first);
7928 for _ in (n_cached + 1)..n {
7929 let delta = dec.literal(bits) as i32;
7930 let prev = *transmitted.last().unwrap();
7931 let val = (i32::from(prev) + delta).clamp(0, max_val - 1) as u16;
7932 range -= i32::from(val) - i32::from(prev);
7933 bits = bits.min(ceil_log2(range.max(0) as u32));
7934 transmitted.push(val);
7935 }
7936 }
7937 let merged = merge_colors(&transmitted, &cached);
7938 u_colors[..n].copy_from_slice(&merged);
7939 } else {
7940 u_colors[..n].copy_from_slice(&cached[..n]);
7941 }
7942 let mut v_colors = [0u16; 8];
7943 if dec.literal(1) == 1 {
7944 let min_bits_v = bd - 4;
7945 let bits = min_bits_v + dec.literal(2);
7946 v_colors[0] = dec.literal(bd) as u16;
7947 for i in 1..n {
7948 let mut delta = dec.literal(bits) as i32;
7949 if delta != 0 && dec.literal(1) == 1 {
7950 delta = -delta;
7951 }
7952 let mut val = i32::from(v_colors[i - 1]) + delta;
7953 if val < 0 {
7954 val += max_val;
7955 }
7956 if val >= max_val {
7957 val -= max_val;
7958 }
7959 v_colors[i] = val as u16;
7960 }
7961 } else {
7962 for i in 0..n {
7963 v_colors[i] = dec.literal(bd) as u16;
7964 }
7965 }
7966 (u_colors, v_colors)
7967}
7968
7969/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
7970/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
7971/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
7972const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
7973
7974/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
7975/// map's own per-pixel context and colour-order permutation, from the
7976/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
7977/// selection sort). `map`'s stride is `side` (this decoder never crops a
7978/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
7979/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
7980/// actual colour index to store.
7981fn palette_color_index_context(
7982 map: &[u8],
7983 side: usize,
7984 row: usize,
7985 col: usize,
7986 n: usize,
7987) -> (usize, [u8; 8]) {
7988 let left = if col >= 1 { Some(map[row * side + col - 1]) } else { None };
7989 let up_left = if col >= 1 && row >= 1 {
7990 Some(map[(row - 1) * side + col - 1])
7991 } else {
7992 None
7993 };
7994 let up = if row >= 1 { Some(map[(row - 1) * side + col]) } else { None };
7995 let mut scores = [0i32; 8];
7996 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
7997 if let Some(v) = neighbour {
7998 scores[v as usize] += weight;
7999 }
8000 }
8001 let mut color_order = [0u8; 8];
8002 for i in 0..8 {
8003 color_order[i] = i as u8;
8004 }
8005 for i in 0..3 {
8006 let mut max = scores[i];
8007 let mut max_idx = i;
8008 for j in (i + 1)..n {
8009 if scores[j] > max {
8010 max = scores[j];
8011 max_idx = j;
8012 }
8013 }
8014 if max_idx != i {
8015 let max_score = scores[max_idx];
8016 let max_color = color_order[max_idx];
8017 for k in (i + 1..=max_idx).rev() {
8018 scores[k] = scores[k - 1];
8019 color_order[k] = color_order[k - 1];
8020 }
8021 scores[i] = max_score;
8022 color_order[i] = max_color;
8023 }
8024 }
8025 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
8026 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
8027 (ctx as usize, color_order)
8028}
8029
8030/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
8031/// map's wavefront decode over a `side x side` grid -- this decoder's
8032/// palette blocks are always square and never straddle the frame's true
8033/// (possibly odd) edge without already allocating the full `side*side`
8034/// region (every other skip/residual path here does the same), so no
8035/// rows/cols-vs-plane_width/height cropping special case is needed, unlike
8036/// libaom's own non-block-aligned split.
8037fn decode_color_index_map(
8038 dec: &mut SymbolDecoder,
8039 cdfs: &mut Cdfs,
8040 n: usize,
8041 side: usize,
8042 uv: bool,
8043) -> Vec<u8> {
8044 decode_color_index_map_wh(dec, cdfs, n, side, side, uv)
8045}
8046
8047/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
8048/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
8049/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
8050/// independently rather than one shared `side` -- the square call above is
8051/// just `bw == bh`.
8052fn decode_color_index_map_wh(
8053 dec: &mut SymbolDecoder,
8054 cdfs: &mut Cdfs,
8055 n: usize,
8056 bw: usize,
8057 bh: usize,
8058 uv: bool,
8059) -> Vec<u8> {
8060 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
8061 let mut map = vec![0u8; bw * bh];
8062 if trace {
8063 let (rng, _) = dec.debug_state();
8064 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
8065 }
8066 map[0] = read_uniform(dec, n) as u8;
8067 if trace {
8068 let (rng, _) = dec.debug_state();
8069 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
8070 }
8071 for i in 1..(bw + bh - 1) {
8072 let j_hi = i.min(bw - 1);
8073 let j_lo = i.saturating_sub(bh - 1);
8074 for j in (j_lo..=j_hi).rev() {
8075 let row = i - j;
8076 let col = j;
8077 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
8078 if trace {
8079 let (rng, _) = dec.debug_state();
8080 let row_cdf = if uv {
8081 &cdfs.palette_uv_color_index[n - 2][ctx]
8082 } else {
8083 &cdfs.palette_y_color_index[n - 2][ctx]
8084 };
8085 eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} cdf0={} cnt={} rng={rng}", row_cdf[0], row_cdf[n]);
8086 }
8087 let symbol = if uv {
8088 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
8089 } else {
8090 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
8091 };
8092 map[row * bw + col] = color_order[symbol];
8093 if trace {
8094 let (rng, _) = dec.debug_state();
8095 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
8096 }
8097 }
8098 }
8099 map
8100}
8101
8102/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
8103/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
8104/// size class comes from [`filter_intra_size_class_rect`] instead of the
8105/// square-only [`filter_intra_size_class`], and the palette read (when
8106/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
8107/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
8108/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
8109/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
8110#[allow(clippy::too_many_arguments)]
8111fn read_intra_mode_rect(
8112 dec: &mut SymbolDecoder,
8113 cdfs: &mut Cdfs,
8114 above_mode: usize,
8115 left_mode: usize,
8116 cfl: bool,
8117 // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall
8118 // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads
8119 // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's
8120 // chroma is coded once, on the closing strip). Every other caller is a
8121 // block big enough to own its chroma and passes `true`.
8122 has_chroma: bool,
8123 bw: usize,
8124 bh: usize,
8125 enable_filter_intra: bool,
8126 skip_ctx: usize,
8127 allow_screen_content_tools: bool,
8128 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
8129 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
8130 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
8131 palette: Option<(usize, &[u16])>,
8132 palette_uv_cache: &[u16],
8133 mi_r: usize,
8134 mi_c: usize, fctx: &crate::decode::FrameCtx,
8135) -> Result<(
8136 bool,
8137 usize,
8138 i32,
8139 usize,
8140 i32,
8141 Option<(i32, i32)>,
8142 Option<usize>,
8143 Option<PaletteY>,
8144 Option<PaletteUv>,
8145)> {
8146 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
8147 if ec_istep {
8148 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
8149 // (decodemv.c:818), printed at the same point: before the first
8150 // mode-info symbol of the block, so a cross-decoder range ladder can
8151 // be keyed on the BLOCK, not just on the symbol sequence.
8152 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);
8153 }
8154 macro_rules! istep {
8155 ($name:literal, $val:expr) => {
8156 if ec_istep {
8157 let (rng, _) = dec.debug_state();
8158 eprintln!(
8159 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
8160 $name, $val
8161 );
8162 }
8163 };
8164 }
8165 // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is
8166 // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at
8167 // the one point every rect caller routes through, so no call site can
8168 // offer the 14-symbol CFL alphabet on a 64-axis block (class
8169 // wrong-alphabet-same-value: same value, wrong interval, silent desync).
8170 let cfl = if cfl && bw.max(bh) > 32 {
8171 NOCFL_UV_MODE_HITS.with(|c| c.set(c.get() + 1));
8172 false
8173 } else {
8174 cfl
8175 };
8176 // lane-intra14 r1: on the INTER block path everything up to and including
8177 // `is_inter` was already read by [`decode_inter_block`], so this reader
8178 // starts at the mode syntax with the `skip` that caller read.
8179 let inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get);
8180 let skip = if let Some((_, skip)) = inter {
8181 skip
8182 } else {
8183 // Same `intra_segment_id` placement as the square reader above.
8184 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
8185 if seg_id_pre_skip(fctx) {
8186 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
8187 }
8188 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
8189 istep!("skip", skip as i32);
8190 if !seg_id_pre_skip(fctx) {
8191 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
8192 }
8193 maybe_read_cdef_idx(dec, mi_r, mi_c, skip, fctx);
8194 istep!("cdef", 0);
8195 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
8196 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
8197 // `false`.
8198 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
8199 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
8200 istep!("dq", 0);
8201 // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after
8202 // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the
8203 // `use_intrabc` symbol is read for EVERY intra block of an `allow_intrabc`
8204 // frame -- `av1_allow_intrabc` is a frame-level test with no shape term, so
8205 // rect strips read it exactly like square leaves ([`read_intra_mode`],
8206 // [`read_intra_mode_sub8`]). Missing it here desynced the arithmetic
8207 // decoder at the FIRST symbol of the first rect block of every
8208 // `--tune-content=screen` key frame. Reconstruction of a real intrabc
8209 // block at this shape is out of scope, so the flag is consumed and
8210 // refused by name when it fires.
8211 if allow_intrabc_frame(fctx) {
8212 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
8213 RECT_INTRABC_READS.with(|c| c.set(c.get() + 1));
8214 istep!("intrabc", use_intrabc as i32);
8215 if use_intrabc {
8216 INTRABC_HITS.with(|c| c.set(c.get() + 1));
8217 return Err(unsupported(
8218 "intra block copy on a HORZ/VERT/1:4 rect intra strip (reconstruction is not ported at this shape)",
8219 ));
8220 }
8221 }
8222 skip
8223 };
8224 // libaom `read_intra_block_mode_info` (decodemv.c:1189) vs the key
8225 // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode`
8226 // off `kf_y_mode_cdf[above][left]`).
8227 let mode = if let Some((size_group, _)) = inter {
8228 dec.symbol(&mut cdfs.y_mode[size_group])
8229 } else {
8230 let above_ctx = INTRA_MODE_CTX[above_mode];
8231 let left_ctx = INTRA_MODE_CTX[left_mode];
8232 dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx])
8233 };
8234 istep!("mode", mode as i32);
8235 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
8236 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
8237 } else {
8238 0
8239 };
8240 istep!("angle_y", angle_delta_y);
8241 // lane-sb128c r3 (class sweep): libaom `read_intra_mode_uv(.., is_cfl_allowed(xd), ..)`
8242 // and `is_cfl_allowed` (blockd.h) is `block_size_wide[bsize] <= 32 &&
8243 // block_size_high[bsize] <= 32` on the LUMA bsize. Deciding the alphabet
8244 // here, from the block's own size, is the single point every caller routes
8245 // through -- a caller passing `true` for a >32 strip used to pick the
8246 // 14-symbol CFL CDF, same value but a different range (class
8247 // wrong-alphabet-same-value).
8248 let cfl = cfl && bw <= 32 && bh <= 32;
8249 let uv_mode = if !has_chroma {
8250 DC_PRED
8251 } else if cfl {
8252 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
8253 } else {
8254 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
8255 };
8256 istep!("uv_mode", uv_mode as i32);
8257 let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED {
8258 Some(read_cfl_alphas(dec, cdfs))
8259 } else {
8260 None
8261 };
8262 if has_chroma && (9..=12).contains(&uv_mode) {
8263 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
8264 }
8265 let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) {
8266 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
8267 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
8268 } else {
8269 0
8270 };
8271 istep!("angle_uv", angle_delta_uv);
8272 if angle_delta_uv != 0 {
8273 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
8274 }
8275 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
8276 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
8277 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
8278 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
8279 // colours only here, the colour-index maps deferred past `filter_intra`
8280 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
8281 // runs from the caller, after the whole mode-info read).
8282 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
8283 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
8284 if allow_screen_content_tools
8285 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
8286 {
8287 // r6: this is the exact site the removed blanket refusal used to
8288 // guard -- reached for EVERY rect strip in a screen-content frame,
8289 // independent of whether the block ends up using a palette.
8290 RECT_SCREEN_CONTENT_HITS.with(|c| c.set(c.get() + 1));
8291 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
8292 let use_palette_y =
8293 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
8294 if use_palette_y {
8295 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
8296 let colors = read_palette_colors_y(dec, n, cache, fctx);
8297 palette_y_pending = Some((n, colors));
8298 }
8299 let palette_uv_mode_ctx = usize::from(use_palette_y);
8300 // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard.
8301 if has_chroma
8302 && uv_mode == DC_PRED
8303 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
8304 {
8305 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
8306 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
8307 palette_uv_pending = Some((n, u_colors, v_colors));
8308 }
8309 }
8310 let mut filter_intra = None;
8311 if crate::envflags::env_flag!("EC_AV1_TRACE") {
8312 let (rng, _) = dec.debug_state();
8313 eprintln!(
8314 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
8315 class={:?} rng={rng}",
8316 enable_filter_intra as i32,
8317 filter_intra_size_class_rect(bw, bh)
8318 );
8319 }
8320 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
8321 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
8322 if mode == DC_PRED
8323 && enable_filter_intra
8324 && palette_y_pending.is_none()
8325 && let Some(class) = filter_intra_size_class_rect(bw, bh)
8326 {
8327 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
8328 if crate::envflags::env_flag!("EC_AV1_TRACE") {
8329 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
8330 }
8331 istep!("use_filter_intra", use_filter_intra as i32);
8332 if use_filter_intra {
8333 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
8334 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
8335 istep!("filter_intra_mode", fi_mode as i32);
8336 filter_intra = Some(fi_mode);
8337 }
8338 }
8339 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
8340 // same order as [`read_intra_mode`]'s own square path.
8341 let palette_y = palette_y_pending.map(|(n, colors)| {
8342 let map = decode_color_index_map_wh(dec, cdfs, n, bw, bh, false);
8343 PALETTE_HITS.with(|c| c.set(c.get() + 1));
8344 PALETTE_RECT_HITS.with(|c| c.set(c.get() + 1));
8345 PaletteY { size: n, colors, map }
8346 });
8347 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
8348 // `av1_get_plane_block_size(bsize, 1, 1)` (`ss_size_lookup`), NOT a
8349 // plain halving: BLOCK_16X4 subsamples to BLOCK_8X4 and BLOCK_4X16 to
8350 // BLOCK_4X8, both floored at the 4-px transform. Halving the short
8351 // axis to 2 read HALF the colour-index symbols of a 1:4 strip's
8352 // chroma palette and desynced the tile from there.
8353 let (cw, ch) = ((bw / 2).max(4), (bh / 2).max(4));
8354 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, true);
8355 PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
8356 PaletteUv { size: n, u_colors, v_colors, map }
8357 });
8358 Ok((
8359 skip,
8360 mode,
8361 angle_delta_y,
8362 uv_mode,
8363 angle_delta_uv,
8364 alpha,
8365 filter_intra,
8366 palette_y,
8367 palette_uv,
8368 ))
8369}
8370
8371/// Stamps a 1:4 strip's palette state into the mi-granular above/left arrays,
8372/// at the strip's REAL mi position. `av1_get_palette_cache` reads
8373/// `xd->above_mbmi`/`xd->left_mbmi`, i.e. the mi cell above/left of the
8374/// block, so each strip owns its own rows and columns and no aliasing rule
8375/// is needed (lane-kf900 r6).
8376#[allow(clippy::too_many_arguments)]
8377fn record_strip_palette(
8378 n: &mut Neighbours,
8379 mi: (usize, usize),
8380 bw: usize,
8381 bh: usize,
8382 y_size: usize,
8383 y_colors: [u16; 8],
8384 uv_size: usize,
8385 uv_colors: [u16; 8],
8386) {
8387 let (r, c) = mi;
8388 // lane-t900 r23 rung: every publication of a block's palette state into
8389 // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode
8390 // path left a stale `left_palette_size` behind when
8391 // `av1_get_palette_mode_ctx` disagrees with libaom's.
8392 if crate::envflags::env_flag!("EC_PALPUB") {
8393 eprintln!("EC_PALPUB strip mi={r},{c} bw={bw} bh={bh} y={y_size} uv={uv_size}");
8394 }
8395 // lane-kf900 r6: the palette side bands are mi-granular now, so a strip
8396 // writes its OWN span on BOTH axes -- the old `last` split-axis rule only
8397 // existed because the 16px [`SUB`] cell held one slot for all the strips
8398 // of a HORZ_4/VERT_4 and leaf 0 zeroing the other axis threw away the
8399 // real neighbour leaf 1 reads.
8400 {
8401 for cell in 0..(bw / MI).max(1) {
8402 if let Some(e) = n.above_palette_size.get_mut(c + cell) {
8403 *e = y_size;
8404 n.above_palette_colors[c + cell] = y_colors;
8405 n.above_palette_uv_size[c + cell] = uv_size;
8406 n.above_palette_uv_colors[c + cell] = uv_colors;
8407 }
8408 }
8409 }
8410 {
8411 for cell in 0..(bh / MI).max(1) {
8412 if n.left_palette_size.get(r + cell).is_none() {
8413 break;
8414 }
8415 n.left_palette_size[r + cell] = y_size;
8416 n.left_palette_colors[r + cell] = y_colors;
8417 n.left_palette_uv_size[r + cell] = uv_size;
8418 n.left_palette_uv_colors[r + cell] = uv_colors;
8419 }
8420 }
8421}
8422
8423/// [`tx_size_context`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
8424/// `get_tx_size_context` (libaom `pred_common.h`) compares the neighbour
8425/// above against this block's own *width* and the neighbour to the left
8426/// against its own *height* -- for a square block those are the same value,
8427/// which is why the square-only version can get away with one `own_side`.
8428fn tx_size_context_rect(
8429 n: &Neighbours,
8430 (mi_r, mi_c): (usize, usize),
8431 own_w: usize,
8432 own_h: usize,
8433) -> usize {
8434 // `get_tx_size_context` compares against `max_txsize_rect_lookup[bsize]`,
8435 // not the block's own side: no transform is wider or taller than 64, so a
8436 // block with a 128 side resolves against 64 (the square path already caps
8437 // this way, lane-sb128b r1). Without the cap the 64x128 half of a 128-root
8438 // VERT reads the tx-depth symbol off row 0 where libaom uses row 1.
8439 let (own_w, own_h) = (own_w.min(64), own_h.min(64));
8440 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w;
8441 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h;
8442 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
8443 eprintln!(
8444 "EC_TXCTX mi_row={mi_r} mi_col={mi_c} w={own_w} h={own_h} above_px={} left_px={} ctx={}",
8445 if mi_r > n.tile_row0_mi { tx_px_at(n, false, mi_r - 1, mi_c) } else { 0 },
8446 if mi_c > n.tile_col0_mi { tx_h_px_at(n, false, mi_r, mi_c - 1) } else { 0 },
8447 usize::from(above) + usize::from(left)
8448 );
8449 }
8450 usize::from(above) + usize::from(left)
8451}
8452
8453/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
8454fn cfl_ac_q3_rect(y: &PlaneBuf<'_>, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
8455 let (cw, ch) = (bw / 2, bh / 2);
8456 let mut ac = vec![0i32; cw * ch];
8457 let mut sum = 0i32;
8458 for cy in 0..ch {
8459 for cx in 0..cw {
8460 let (lx, ly) = (px + cx * 2, py + cy * 2);
8461 let q3 = (i32::from(y.data[ly * y.width + lx])
8462 + i32::from(y.data[ly * y.width + lx + 1])
8463 + i32::from(y.data[(ly + 1) * y.width + lx])
8464 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
8465 << 1;
8466 ac[cy * cw + cx] = q3;
8467 sum += q3;
8468 }
8469 }
8470 let num_pel = (cw * ch) as i32;
8471 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
8472 ac.iter_mut().for_each(|v| *v -= avg);
8473 ac
8474}
8475
8476/// Everything a rect strip already read out of the stream before its luma
8477/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
8478/// (nine values that would otherwise be nine more parameters).
8479struct RectStripModes {
8480 skip: bool,
8481 mode: usize,
8482 angle_delta_y: i32,
8483 uv_predict_mode: usize,
8484 angle_delta_uv: i32,
8485 alpha: Option<(i32, i32)>,
8486 filter_intra: Option<usize>,
8487 smooth_neighbor: bool,
8488 smooth_neighbor_uv: bool,
8489 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
8490 /// mapped through the colour table), sliced per transform unit below --
8491 /// palette prediction reads no edge pixels, so a unit's slice of the
8492 /// whole-block map IS its prediction. Without this a palette strip whose
8493 /// transform splits predicted DC and came out flat grey while the entropy
8494 /// stream stayed in sync (the coefficients are read either way).
8495 palette_y: Option<Vec<u16>>,
8496 /// As `palette_y`, for the un-split chroma transform (U, V).
8497 palette_uv: Option<(Vec<u16>, Vec<u16>)>,
8498}
8499
8500/// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth`
8501/// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times
8502/// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the
8503/// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's
8504/// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 ->
8505/// TX_32X16`) and only the second reaches a square -- the reason
8506/// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
8507/// already square) mis-tiled 1:4 strips.
8508fn depth_to_tx_wh(bw: usize, bh: usize, depth: usize) -> (usize, usize) {
8509 let (mut w, mut h) = (bw.min(64), bh.min(64));
8510 for _ in 0..depth {
8511 match w.cmp(&h) {
8512 std::cmp::Ordering::Greater => w /= 2,
8513 std::cmp::Ordering::Less => h /= 2,
8514 std::cmp::Ordering::Equal => {
8515 w /= 2;
8516 h /= 2;
8517 }
8518 }
8519 }
8520 (w, h)
8521}
8522
8523/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
8524/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
8525/// rect path here refused by name until now ("per-unit rect prediction is not
8526/// ported").
8527///
8528/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
8529/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
8530/// strip the very first step already lands on a SQUARE transform
8531/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
8532/// every further step halves a square) -- so each unit is square and reads
8533/// through the ordinary square [`read_plane`]. What is genuinely rectangular
8534/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
8535/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
8536/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
8537/// split by luma's depth.
8538///
8539/// Each unit predicts off whatever the earlier units of this same block
8540/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
8541/// inside `av1_foreach_transformed_block`, raster order), which is exactly
8542/// what predicting the whole strip in one shot got wrong.
8543#[allow(clippy::too_many_arguments)]
8544fn decode_rect_split(
8545 dec: &mut SymbolDecoder,
8546 cdfs: &mut Cdfs,
8547 neighbours: &mut Neighbours,
8548 at_mi: (usize, usize),
8549 bw: usize,
8550 bh: usize,
8551 // The transform unit's own width and height in pixels. Square for every
8552 // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
8553 // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
8554 // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
8555 tx_w: usize,
8556 tx_h: usize,
8557 m: &RectStripModes,
8558 y: &mut PlaneBuf<'static>,
8559 u: &mut PlaneBuf<'static>,
8560 v: &mut PlaneBuf<'static>,
8561 base_q_idx: u8,
8562 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
8563) -> Result<()> {
8564 let (mi_r, mi_c) = at_mi;
8565 let (px, py) = (mi_c * MI, mi_r * MI);
8566 let (cpx, cpy) = (px / 2, py / 2);
8567 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
8568 // The chroma transform is picked before any symbol is read, so an
8569 // unsupported chroma shape refuses before this strip desyncs the tile.
8570 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
8571 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
8572 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
8573 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
8574 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
8575 // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32
8576 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx`
8577 // squares a rect transform down to a CDF set by
8578 // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set,
8579 // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets
8580 // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`)
8581 // paths already prove for these same shapes.
8582 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
8583 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
8584 (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])),
8585 (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])),
8586 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
8587 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
8588 _ => None,
8589 };
8590 if !m.skip {
8591 if let Some(i) = match (chroma_w, chroma_h) {
8592 (32, 8) => Some(0),
8593 (8, 32) => Some(1),
8594 (8, 4) => Some(2),
8595 (4, 8) => Some(3),
8596 _ => None,
8597 } {
8598 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
8599 let mut hits = c.get();
8600 hits[i] += 1;
8601 c.set(hits);
8602 });
8603 }
8604 if chroma.is_none() {
8605 // Diagnostic for the next caller that lands here (class
8606 // refusal-names-a-correlate: the message names the tool, not the
8607 // shape); the refusal below keeps its inventory-pinned wording.
8608 eprintln!("EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} chroma={chroma_w}x{chroma_h}");
8609 }
8610 }
8611 // lane-rectsplit r2 (verifier finding): with both callers wired
8612 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
8613 // 64x32/32x64) every shape that reaches here has a table above, so this
8614 // arm is UNREACHABLE today. It stays as the shape guard for the next
8615 // caller -- a new strip size would otherwise hit the `expect` below and
8616 // panic instead of refusing by name -- and so stays in
8617 // `refusal_inventory::REFUSALS`.
8618 if !m.skip && chroma.is_none() {
8619 return Err(unsupported(
8620 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
8621 ));
8622 }
8623 RECT_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
8624 if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 {
8625 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.set(c.get() + 1));
8626 }
8627 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
8628 // A square unit reads through the ordinary square [`read_plane`]; a rect
8629 // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with
8630 // the very tables the unsplit 16x8/32x16 paths use.
8631 let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) {
8632 (w, h) if w == h => None,
8633 (16, 8) | (8, 16) => Some((
8634 if reduced_tx_set {
8635 TxbSet::LumaRect16x8
8636 } else {
8637 TxbSet::LumaRect16x8Set1
8638 },
8639 if tx_w == 16 { &SCAN_16X8[..] } else { &SCAN_8X16[..] },
8640 )),
8641 (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])),
8642 (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])),
8643 // lane-rect64port r1: the un-split TX_64X32/TX_32X64 of a 64-level
8644 // strip, read through the `luma_64corner` arm below instead of a rect
8645 // table -- a 64-length axis codes only its low 32 coefficients
8646 // (`av1_get_max_eob` / the zero-out of `av1_get_adjusted_tx_size`), so
8647 // the coded unit is the 32x32 corner [`decode_block_rect64`]'s own
8648 // depth-0 arm already reads on the key-frame path.
8649 //
8650 // lane-sub8x4 r3: WITNESS FOUND, so this is no longer behind
8651 // `EC_RECT64_SPLIT`. r1's "no witness" was true only while the
8652 // sub-8x8 intra leaves still refused: with those lifted (r2) the
8653 // first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode
8654 // all 33 frames pixel-exact against ffmpeg while this arm fires 90x
8655 // 64x32 + 5x 32x64 -- pinned as `fixtures/reelb_rect64_intra16x4_witness.obu`
8656 // and gated by `a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact`.
8657 // lane-wit16x4 r1 re-measured that fixture on the merged tip: this arm
8658 // fires 64x32=148 32x64=123 (the 90/5 above were counted out of the
8659 // frame-33 desync lane-frame36 r2 fixed), all 33 frames pixel-exact.
8660 (64, 32) | (32, 64) => None,
8661 _ => {
8662 return Err(unsupported(format!(
8663 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \
8664 coefficient tables for that shape here)"
8665 )))
8666 }
8667 };
8668 // The `None` above that is NOT the square arm.
8669 let luma_64corner = tx_w != tx_h;
8670 // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact
8671 // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole
8672 // frame exactly, two sub-16 split strips in it), but the RECT-unit arm --
8673 // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the
8674 // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the
8675 // per-unit rect walk stay wired above/below; the round that finds that
8676 // defect deletes this refusal and nothing else.
8677 let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set);
8678 let luma_scan = default_scan(tx_w.min(tx_h));
8679 let zero_tu = vec![0i32; tx_w * tx_h];
8680 // The strip's OWN edge availability, the fallback for a transform unit
8681 // whose top-right/bottom-left pixels fall outside the strip.
8682 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
8683 for tu_row in 0..bh / tx_h {
8684 for tu_col in 0..bw / tx_w {
8685 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
8686 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
8687 let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h);
8688 // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged):
8689 // libaom clips `av1_foreach_transformed_block_in_plane` to
8690 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
8691 // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose
8692 // TOP-LEFT sample falls outside the frame is never coded. We read
8693 // coefficients for those phantom units and desynced the stream at
8694 // the very next symbol.
8695 if tu_px >= y.true_width || tu_py >= y.true_height {
8696 continue;
8697 }
8698 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
8699 // transform unit INSIDE a block, which is a different rule from
8700 // the standalone-block table [`Reach::of`] applies -- and the
8701 // reason a depth-2 superblock strip came out one sample off
8702 // before this: `Reach::of(tx, ..)` answered as if the unit were
8703 // its own block at that superblock position.
8704 // * top-right: if the unit's right neighbour is still inside the
8705 // strip the pixels are already reconstructed (`col_off +
8706 // tx_wide < plane_bw`); otherwise only the strip's own top row
8707 // of units can reach past it, through the block-level answer.
8708 // * bottom-left: a unit that is not in the strip's left column
8709 // has none (`col_off > 0` returns 0); inside the strip
8710 // (`row_off + tx_high < plane_bh`) they are the left
8711 // neighbour's, already reconstructed; the last row falls back
8712 // to the block-level answer.
8713 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach);
8714 // The unit's own window on the block's palette prediction.
8715 if let Some(buf) = &m.palette_y {
8716 let tu_buf: Vec<u16> = (0..tx_h)
8717 .flat_map(|i| {
8718 let base = (row_off + i) * bw + col_off;
8719 buf[base..base + tx_w].iter().copied()
8720 })
8721 .collect();
8722 set_palette_pred(tu_buf, fctx);
8723 }
8724 if m.skip {
8725 push_intra_rect(0,
8726 tu_px,
8727 tu_py,
8728 tx_w,
8729 tx_h,
8730 m.mode,
8731 m.angle_delta_y,
8732 tu_reach,
8733 &zero_tu,
8734 None,
8735 m.filter_intra,
8736 m.smooth_neighbor, fctx,
8737 );
8738 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
8739 } else if luma_64corner && luma_rect.is_none() {
8740 // The un-split 64-level luma transform: `read_coeffs` on the
8741 // 32x32 CDF set [`TxbSet::Luma64`] with `default_scan(TX32)`
8742 // and the real rect shape passed through for
8743 // `av1_nz_map_ctx_offset` -- byte for byte
8744 // [`decode_block_rect64`]'s depth-0 read, which the key-frame
8745 // 64-level strip gate already proves. `tx_type` is not coded
8746 // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once
8747 // the square-up size is TX_64X64), and this unit covers its
8748 // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat.
8749 if crate::envflags::env_flag!("EC_RECT64TU") {
8750 eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode);
8751 }
8752 RECT64_CORNER_TU_HITS.with(|c| {
8753 let mut v = c.get();
8754 v[usize::from(tx_h > tx_w)] += 1;
8755 c.set(v);
8756 });
8757 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
8758 let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra));
8759 let (corner, tu_tx_type) = read_coeffs(
8760 dec,
8761 &mut coding,
8762 default_scan(TX32),
8763 0,
8764 dc_sign_ctx(tu_around.2),
8765 TxType::DctDct,
8766 Some((tx_w, tx_h)),
8767 )?;
8768 let (cw, ch) = (tx_w.min(TX32), tx_h.min(TX32));
8769 let mut tu_grid = vec![0i32; tx_w * tx_h];
8770 for row in 0..ch {
8771 tu_grid[row * tx_w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
8772 }
8773 let residual = dequant_and_inverse_typed_wh(
8774 &tu_grid,
8775 tx_w,
8776 tx_h,
8777 crate::decode::bit_depth(fctx),
8778 block_q_idx(fctx),
8779 plane_q_delta(0, fctx).0,
8780 plane_q_delta(0, fctx).1,
8781 tu_tx_type,
8782 );
8783 push_intra_rect(0,
8784 tu_px,
8785 tu_py,
8786 tx_w,
8787 tx_h,
8788 m.mode,
8789 m.angle_delta_y,
8790 tu_reach,
8791 &residual,
8792 None,
8793 m.filter_intra,
8794 m.smooth_neighbor, fctx,
8795 );
8796 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
8797 } else if let Some((rect_set, rect_scan)) = luma_rect {
8798 // The rect-unit twin of the square arm below: same contexts,
8799 // same order, through the rect coefficient reader. The
8800 // `tx_type` CDF row of a filter-intra block is
8801 // `fimode_to_intradir[filter_intra_mode]`, never the block's
8802 // own (always DC_PRED) mode -- [`read_plane`] applies that
8803 // for the square arm, so this one must too.
8804 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
8805 // libaom `get_txb_ctx`: a LUMA transform that covers its whole
8806 // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the
8807 // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the
8808 // neighbour-magnitude table is for a unit SMALLER than its
8809 // block. [`decode_block_rect`]'s own unsplit read passes a
8810 // literal 0 for the same reason; this arm applied the table
8811 // unconditionally and desynced every depth-0 rect strip that
8812 // reached it (lane-intrarect r2: ctx 5 where aomdec read 0).
8813 let tu_skip_ctx = if tx_w == bw && tx_h == bh {
8814 0
8815 } else {
8816 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI)
8817 };
8818 let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra));
8819 let (tu_grid, tu_tx_type) = read_coeffs_rect(
8820 dec,
8821 &mut coding,
8822 rect_scan,
8823 tx_w,
8824 tx_h,
8825 tu_skip_ctx,
8826 dc_sign_ctx(tu_around.2),
8827 TxType::DctDct,
8828 )?;
8829 let residual = dequant_and_inverse_typed_wh(
8830 &tu_grid,
8831 tx_w,
8832 tx_h,
8833 crate::decode::bit_depth(fctx),
8834 block_q_idx(fctx),
8835 plane_q_delta(0, fctx).0,
8836 plane_q_delta(0, fctx).1,
8837 tu_tx_type,
8838 );
8839 push_intra_rect(0,
8840 tu_px,
8841 tu_py,
8842 tx_w,
8843 tx_h,
8844 m.mode,
8845 m.angle_delta_y,
8846 tu_reach,
8847 &residual,
8848 None,
8849 m.filter_intra,
8850 m.smooth_neighbor, fctx,
8851 );
8852 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
8853 } else {
8854 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
8855 // This unit is smaller than the block it sits in, so
8856 // `txb_skip_ctx` is the neighbour-magnitude table, not the
8857 // lone-TU 0 (spec `get_txb_ctx_general`).
8858 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
8859 let tu_grid = read_plane(
8860 dec,
8861 cdfs,
8862 luma_set,
8863 &luma_scan,
8864 0,
8865 tu_around,
8866 m.mode,
8867 m.mode,
8868 m.angle_delta_y,
8869 tu_reach,
8870 y,
8871 tu_px,
8872 tu_py,
8873 tx_w,
8874 tx_w,
8875 base_q_idx,
8876 None,
8877 m.filter_intra,
8878 Some(tu_skip_ctx),
8879 m.smooth_neighbor, fctx,
8880 )?;
8881 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
8882 }
8883 }
8884 }
8885 // CHROMA: one un-split rect transform for the whole strip.
8886 let ac = m.alpha.map(|_| cfl_src_rect(px, py, bw, bh));
8887 let reach = block_reach;
8888 let (u_grid, v_grid) = if m.skip {
8889 let zero = vec![0i32; chroma_w * chroma_h];
8890 if let Some((ub, _)) = &m.palette_uv {
8891 set_palette_pred(ub.clone(), fctx);
8892 }
8893 push_intra_rect(1,
8894 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
8895 m.alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv, fctx,
8896 );
8897 if let Some((_, vb)) = &m.palette_uv {
8898 set_palette_pred(vb.clone(), fctx);
8899 }
8900 push_intra_rect(2,
8901 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
8902 m.alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv, fctx,
8903 );
8904 (zero.clone(), zero)
8905 } else {
8906 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
8907 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
8908 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
8909 // so only the 16x8/8x16 pair takes the mode-indexed default.
8910 let default_tx = if chroma_w.max(chroma_h) >= 32 {
8911 TxType::DctDct
8912 } else {
8913 default_intra_tx_type(m.uv_predict_mode as u8)
8914 };
8915 let around = neighbours.around_mi_rect(at_mi, bw, bh);
8916 let mut grids: Vec<Vec<i32>> = Vec::with_capacity(2);
8917 for plane_idx in 1..=2 {
8918 let skip_ctx =
8919 usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
8920 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
8921 let (levels, tx_type) = read_coeffs_rect(
8922 dec,
8923 &mut coding,
8924 chroma_scan,
8925 chroma_w,
8926 chroma_h,
8927 skip_ctx,
8928 dc_sign_ctx(around[plane_idx].2),
8929 default_tx,
8930 )?;
8931 // The same delta_q proof the unsplit rect64 path records
8932 // (lane-rectsplit r4: lifting the split-transform refusal moved
8933 // superblock strips onto this path, so only counting there would
8934 // leave the delta_q gate's counter silent for them).
8935 if bw.max(bh) == 64 && fctx.current_q_idx.with(|c| c.get()) != i32::from(base_q_idx) {
8936 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
8937 }
8938 let residual = dequant_and_inverse_typed_wh(
8939 &levels,
8940 chroma_w,
8941 chroma_h,
8942 crate::decode::bit_depth(fctx),
8943 fctx.current_q_idx.with(|c| c.get()),
8944 plane_q_delta(plane_idx, fctx).0,
8945 plane_q_delta(plane_idx, fctx).1,
8946 tx_type,
8947 );
8948 let cfl = m
8949 .alpha
8950 .zip(ac)
8951 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
8952 let _plane = if plane_idx == 1 { &mut *u } else { &mut *v };
8953 if let Some((ub, vb)) = &m.palette_uv {
8954 let buf = if plane_idx == 1 { ub } else { vb };
8955 set_palette_pred(buf.clone(), fctx);
8956 }
8957 push_intra_rect(plane_idx,
8958 cpx,
8959 cpy,
8960 chroma_w,
8961 chroma_h,
8962 m.uv_predict_mode,
8963 m.angle_delta_uv,
8964 reach,
8965 &residual,
8966 cfl,
8967 None,
8968 m.smooth_neighbor_uv, fctx,
8969 );
8970 grids.push(levels);
8971 }
8972 let mut it = grids.into_iter();
8973 (it.next().unwrap(), it.next().unwrap())
8974 };
8975 neighbours.record_split_luma_rect_mi(
8976 at_mi,
8977 bw,
8978 bh,
8979 m.mode,
8980 m.uv_predict_mode,
8981 [&u_grid, &v_grid],
8982 );
8983 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
8984 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
8985 if crate::envflags::env_flag!("EC_AV1_TRACE") {
8986 let (rng, _) = dec.debug_state();
8987 eprintln!(
8988 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
8989 tx={tx_w}x{tx_h} rng={rng}"
8990 );
8991 }
8992 Ok(())
8993}
8994
8995/// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect
8996/// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name
8997/// because it predicts squares only. Every pixel here goes through the rect
8998/// machinery the key-frame paths already prove: [`decode_rect_split`], which
8999/// at `depth == 0` is the unsplit strip as a single transform unit and
9000/// beyond it the per-unit walk of [`depth_to_tx_wh`].
9001///
9002/// What is genuinely different from [`decode_block_rect`] is the mode
9003/// syntax: on an inter frame an intra block reads `y_mode[size_group]` and
9004/// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never
9005/// the key frame's `kf_y_mode` above/left pair. This mirrors the square
9006/// intra-in-inter arm's own reads at the rect footprint, including its
9007/// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe
9008/// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the
9009/// square and this arm) and a nonzero luma angle delta refused by name.
9010///
9011/// The strip's own neighbour records (luma per transform unit, chroma, skip
9012/// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the
9013/// inter-side bands and the mi map.
9014#[allow(clippy::too_many_arguments)]
9015/// The `(size_group_lookup, bsize_to_tx_size_cat)` row an INTRA block coded
9016/// inside an inter frame reads its `y_mode` and `tx_depth` symbols from, for
9017/// the rect footprints [`decode_intra_rect_in_inter`] resolves itself (the
9018/// 128-root halves and the 16x4/4x16 strips of a 1:4 partition take their own
9019/// branches before this). libaom `common_data.h:61` / `blockd.h:1347`: the 2:1
9020/// strips keep the group/category diagonal (BLOCK_16X8 -> 1/1, BLOCK_32X16 ->
9021/// 2/2, BLOCK_64X32 -> 3/3), the 1:4 ones break it (BLOCK_32X8 is group 1 but
9022/// category 2, BLOCK_64X16 group 2 and category 3), which is why the row is a
9023/// table here rather than a shift of `bw.min(bh)`.
9024fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> {
9025 Some(match (bw.min(bh), bw.max(bh)) {
9026 (8, 16) => (1usize, 1usize),
9027 (16, 32) => (2, 2),
9028 (32, 64) => (3, 3),
9029 (8, 32) => (1, 2),
9030 (16, 64) => (2, 3),
9031 _ => return None,
9032 })
9033}
9034
9035/// lane-t900 r20, refusal B ("an intra-coded {bw}x{bh} block on the inter
9036/// block path"): the shapes that can reach that arm, enumerated against the
9037/// MEASURED domain of the inter block path
9038/// ([`INTER_BLOCK_SHAPES`], the census the gate
9039/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`
9040/// fills from three real streams).
9041///
9042/// [`decode_intra_rect_in_inter`] is called from one site, under
9043/// `write_w != side || write_h != side`, and only after two earlier arms have
9044/// taken their shapes: a footprint with a side below 8 is either a 16x4/4x16
9045/// strip WITH a chroma-pair record (the `strip16` branch) or refused by name,
9046/// and a 128-px footprint returns from the `bw.max(bh) == 128` branch. What is
9047/// left is every rectangular census shape with `8 <= min` and `max <= 64` --
9048/// and each of those has a row, so the refusal names a shape no measured
9049/// stream can present.
9050#[test]
9051fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() {
9052 let mut checked = 0;
9053 for &(side, w, h) in &INTER_BLOCK_SHAPES {
9054 if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 {
9055 continue;
9056 }
9057 assert!(
9058 intra_in_inter_size_row(w, h).is_some(),
9059 "the inter path decodes {w}x{h} blocks, and an INTRA one of that shape would hit \
9060 the \"no size-group/tx-category row\" refusal"
9061 );
9062 checked += 1;
9063 }
9064 assert_eq!(
9065 checked, 10,
9066 "the block-shape census changed: {checked} rect shapes reach the intra-in-inter row \
9067 lookup, not the 10 this claim was measured over"
9068 );
9069}
9070
9071/// The `motion_mode` / `obmc` CDF row for a block footprint: libaom's
9072/// `motion_mode_cdf[mbmi->bsize]`, in this crate's packed row order (which
9073/// `cdf::MOTION_MODE` documents -- the 128-px rows come last, so they are
9074/// matched before the square arm's `log2` shortcut).
9075///
9076/// `None` is the refusal "a motion_mode symbol for a block shape with no CDF
9077/// row here"; the enumeration below is what proves no conformant block can
9078/// reach it.
9079pub(crate) fn motion_mode_cdf_row(write_w: usize, write_h: usize) -> Option<usize> {
9080 Some(match (write_w, write_h) {
9081 // lane-sb128c r5: the 128 root's own rows come FIRST -- the square arm
9082 // below maps 128 to row 4 (BLOCK_16X32).
9083 (64, 128) => 14,
9084 (128, 64) => 15,
9085 (128, 128) => 16,
9086 (w, h) if w == h => (w.trailing_zeros() - 3) as usize,
9087 (16, 32) => 4,
9088 (32, 16) => 5,
9089 (32, 64) => 6,
9090 (64, 32) => 7,
9091 (8, 32) => 8,
9092 (32, 8) => 9,
9093 (16, 64) => 10,
9094 (64, 16) => 11,
9095 // lane-inter4 r3: the 16x16-level rect inter leaves.
9096 (8, 16) => 12,
9097 (16, 8) => 13,
9098 _ => return None,
9099 })
9100}
9101
9102/// Every `BLOCK_SIZES_ALL` footprint, as `(width, height)` in pixels: the six
9103/// squares, the ten 2:1 shapes and the six 1:4 ones (libaom `common_data.h`,
9104/// `block_size_wide`/`block_size_high`).
9105#[cfg(test)]
9106const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [
9107 (4, 4),
9108 (4, 8),
9109 (8, 4),
9110 (8, 8),
9111 (8, 16),
9112 (16, 8),
9113 (16, 16),
9114 (16, 32),
9115 (32, 16),
9116 (32, 32),
9117 (32, 64),
9118 (64, 32),
9119 (64, 64),
9120 (64, 128),
9121 (128, 64),
9122 (128, 128),
9123 (4, 16),
9124 (16, 4),
9125 (8, 32),
9126 (32, 8),
9127 (16, 64),
9128 (64, 16),
9129];
9130
9131/// lane-t900 r25, enumeration: the refusal "a motion_mode symbol for a block
9132/// shape with no CDF row here" names a shape no conformant stream can present.
9133///
9134/// A `motion_mode`/`obmc` symbol is read only under `motion_mode_eligible`,
9135/// whose `write_w.min(write_h) >= 8` clause is libaom's
9136/// `is_motion_variation_allowed_bsize` (`blockd.h:1455`). So the reachable
9137/// domain of [`motion_mode_cdf_row`] is exactly the `BLOCK_SIZES_ALL`
9138/// footprints with `min(bw, bh) >= 8` -- 17 of the 22 -- and each of those
9139/// must map to a distinct row of the 17-row `Cdfs::motion_mode` table. The
9140/// five it excludes (4x4, 4x8, 8x4, 4x16, 16x4) are the ones the eligibility
9141/// clause rejects before the lookup.
9142#[test]
9143fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() {
9144 let mut rows = std::collections::BTreeSet::new();
9145 let mut excluded = 0;
9146 for (w, h) in BLOCK_SIZES_ALL_WH {
9147 if w.min(h) < 8 {
9148 excluded += 1;
9149 assert!(
9150 w == 4 || h == 4,
9151 "{w}x{h} is not one of the sub-8 shapes is_motion_variation_allowed_bsize rejects"
9152 );
9153 continue;
9154 }
9155 let row = motion_mode_cdf_row(w, h).unwrap_or_else(|| {
9156 panic!(
9157 "a {w}x{h} block passes is_motion_variation_allowed_bsize and reads a motion_mode \
9158 symbol, but has no CDF row -- the refusal is a real gap, not a dead arm"
9159 )
9160 });
9161 assert!(
9162 row < 17,
9163 "{w}x{h} maps to motion_mode row {row}, outside the 17-row table"
9164 );
9165 assert!(rows.insert(row), "{w}x{h} shares motion_mode row {row}");
9166 }
9167 assert_eq!(excluded, 5, "the sub-8 footprint set changed");
9168 assert_eq!(
9169 rows.len(),
9170 17,
9171 "17 eligible footprints must fill all 17 rows of the motion_mode table"
9172 );
9173}
9174
9175fn decode_intra_rect_in_inter(
9176 dec: &mut SymbolDecoder,
9177 cdfs: &mut Cdfs,
9178 neighbours: &mut Neighbours,
9179 at: (usize, usize),
9180 bw: usize,
9181 bh: usize,
9182 skip: bool,
9183 allow_screen_content_tools: bool,
9184 // `(PARTITION_HORZ_4, is_chroma_reference)` when this strip is one of the
9185 // four 16x4 / 4x16 strips of a 16x16-level 1:4 partition (lane-intra16x4).
9186 strip16: Option<(bool, bool)>,
9187 y: &mut PlaneBuf<'static>,
9188 u: &mut PlaneBuf<'static>,
9189 v: &mut PlaneBuf<'static>,
9190 base_q_idx: u8, fctx: &crate::decode::FrameCtx,
9191) -> Result<()> {
9192 // `at` is in MI units (the inter path's own unit since lane-inter4);
9193 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands
9194 // below are still keyed by.
9195 let (mi_r, mi_c) = at;
9196 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
9197 // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat`
9198 // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 /
9199 // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx
9200 // finding -- the category is NOT the same for every strip size).
9201 // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so
9202 // it is refused by name rather than read from the wrong CDF row.
9203 // lane-intra16x4: the 16x16-level 1:4 strip. `size_group_lookup`
9204 // (common_data.h:61) puts BLOCK_16X4/BLOCK_4X16 in group 0 and its
9205 // tx-depth category is 1 -- but nothing here has to know either, because
9206 // the strip decodes through the very body the KEY FRAME path proves for
9207 // this shape ([`decode_rect4_16_strip`]), including the 4:2:0 chroma
9208 // pairing (`is_chroma_reference`: strips 0 and 2 read no chroma at all,
9209 // strips 1 and 3 code one 8x4 (4x8) unit at the PAIR's origin). The only
9210 // inter-frame difference is the mode-info read, which
9211 // [`INTRA_IN_INTER_MODE`] switches to `read_intra_block_mode_info`'s
9212 // `y_mode[0]` plus the `skip` this caller already read.
9213 if let Some((horz, has_chroma)) = strip16 {
9214 // lane-t900 r22: the screen-content refusal here was STALE (class
9215 // stale-premise): [`decode_rect4_16_strip`] takes
9216 // `allow_screen_content_tools` and reads the whole palette syntax
9217 // (mode/size/colours/colour-index map, its own `palette_ctx_and_cache_mi`
9218 // pair) -- the key frame proves that body. Lifted with the 10-bit
9219 // witness `palette_screen_witness_10bit.obu`, whose inter frames carry
9220 // 16x4/4x16 intra strips inside a `--tune-content=screen` frame.
9221 debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) });
9222 fctx.intra_in_inter_mode.with(|c| c.set(Some((0, skip))));
9223 let res = decode_rect4_16_strip(
9224 dec,
9225 cdfs,
9226 neighbours,
9227 (mi_r, mi_c),
9228 horz,
9229 has_chroma,
9230 // The inter strips of the same partition publish their own
9231 // mi-exact mode, so the key-frame caller's coarse-cell stand-in
9232 // has nothing to add here.
9233 None,
9234 y,
9235 u,
9236 v,
9237 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
9238 allow_screen_content_tools,
9239 base_q_idx,
9240 fctx.tx_select_inter.with(std::cell::Cell::get),
9241 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
9242 );
9243 fctx.intra_in_inter_mode.with(|c| c.set(None));
9244 let (mode, uv, (tx_w, tx_h)) = res?;
9245 // lane-intra16x4, the same publication the 2:1 intra-in-inter strip
9246 // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs
9247 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` for EVERY
9248 // block of an inter frame, intra ones included, and
9249 // `txfm_partition_update` for the var-tx context. The key-frame body
9250 // writes neither (a key frame has no var-tx tree and its own readers
9251 // use the deblock grid), so the block AFTER this strip read a stale
9252 // band -- measured: a 128x128 8-bit stream decoded the two intra 16x4
9253 // strips at mi(23,16)/(23,20) exactly and then broke on the very next
9254 // 16x16 row.
9255 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
9256 for i in 0..bw / MI {
9257 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
9258 *cell = tx_w as u8;
9259 }
9260 }
9261 for i in 0..bh / MI {
9262 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
9263 *cell = tx_h as u8;
9264 }
9265 }
9266 // [`decode_rect4_16`]'s own post-loop publication, per strip (the
9267 // coarse 16-px cell holds one entry for the whole 16x16 and the last
9268 // block to write it wins).
9269 neighbours.above_mode[c] = mode;
9270 neighbours.left_mode[r] = mode;
9271 if let Some(uvm) = uv {
9272 neighbours.above_uv_mode[c] = uvm;
9273 neighbours.left_uv_mode[r] = uvm;
9274 }
9275 neighbours.above_side[c] = bw;
9276 neighbours.left_side[r] = bh;
9277 if crate::envflags::env_flag!("EC_INTRA16X4") {
9278 eprintln!(
9279 "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}",
9280 mi_c * MI,
9281 mi_r * MI
9282 );
9283 }
9284 INTRA16X4_IN_INTER_HITS.with(|h| {
9285 let mut v = h.get();
9286 v[usize::from(!horz)] += 1;
9287 v[2] += usize::from(has_chroma);
9288 h.set(v);
9289 });
9290 return Ok(());
9291 }
9292 // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half
9293 // coded INTRA inside an inter frame. `size_group_lookup` (common_data.h:61)
9294 // puts BLOCK_128X64/64X128/128X128 in group 3 and
9295 // `max_txsize_rect_lookup` caps them at TX_64X64, i.e. the same
9296 // `tx_size_cat3` row [`decode_block_128rect`] already reads -- so the whole
9297 // block decodes through the very body the KEY FRAME path proves for this
9298 // shape (square 64x64 luma units, one TX_32X32 chroma unit per 64x64 mu
9299 // chunk on the offset-10 txb_skip rows, per-TU prediction, the mu-chunk
9300 // `Reach` rule and the frame-edge write clip). The only inter-frame
9301 // differences live inside that body: the mode-info read
9302 // ([`INTRA_IN_INTER_MODE`] -> `y_mode[3]` plus the `skip` this caller
9303 // already read), the `tx_depth` context (the real TXFM_CONTEXT bands) and
9304 // the `set_txfm_ctxs` publication. CfL (>32), filter intra (>32) and
9305 // palette (>64) do not exist at this size and are refused by name there.
9306 // lane-t900 r18: the opt-in is LIFTED -- the arm has a witness.
9307 // `intra128_in_inter_witness2.obu` (gate
9308 // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`)
9309 // fires it 3x 128x64 + 6x 64x128 and decodes byte-exact on every plane of
9310 // all 15 frames, so the hits are counted out of exact frames (class
9311 // `counter-from-refused-stream`). What r16/r17 could not find, and what
9312 // that recipe exploits: libaom's RD essentially never PICKS a 128-root
9313 // HORZ/VERT in the interior -- the 512x512 r16 witness and a textured
9314 // 640x384 sweep code 128 roots as NONE or SPLIT only. The shape appears
9315 // where the frame EDGE forces it: a partial last superblock row has
9316 // `has_rows128 == false`, so the 128x64 top half is implied, and a
9317 // partial last column implies the 64x128 left half. Put content no
9318 // reference holds (a fresh smooth ramp) in exactly those two bands of an
9319 // inter frame and the encoder codes those forced halves INTRA.
9320 if bw.max(bh) == 128 {
9321 // lane-t900 r32: no screen-content refusal here. `av1_allow_palette`
9322 // rejects every footprint with a 128-pixel side (`bw > 64 || bh > 64`,
9323 // enumerated by `no_block_footprint_with_a_128_pixel_side_can_carry_\
9324 // palette_syntax`), so a 128-root half consumes no palette syntax and
9325 // a screen-content frame's half is syntactically identical to the
9326 // non-screen one this arm already decodes byte-exact.
9327 if coeff_trace_on() {
9328 // lane-t900 r16: which decode-order frame this arm fires in --
9329 // interleaved with the `EC_COEFF_FRAME` markers, this is what
9330 // proves the hit is counted out of a frame that compares exact
9331 // (class `counter-from-refused-stream`).
9332 eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}");
9333 }
9334 fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip))));
9335 let res = decode_block_128rect(
9336 dec,
9337 cdfs,
9338 neighbours,
9339 (r, c),
9340 bw,
9341 bh,
9342 y,
9343 u,
9344 v,
9345 base_q_idx,
9346 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
9347 allow_screen_content_tools,
9348 fctx.tx_select_inter.with(std::cell::Cell::get),
9349 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
9350 );
9351 fctx.intra_in_inter_mode.with(|c| c.set(None));
9352 return res;
9353 }
9354 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {
9355 if crate::envflags::env_flag!("EC_OBMCREC") {
9356 eprintln!(
9357 "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}"
9358 );
9359 }
9360 // lane-obmcrec r1: the message used to name a 16x4/4x16 strip
9361 // (class refusal-names-a-correlate). lane-t900 r20: the shapes that
9362 // can arrive here are enumerated against the measured block-shape
9363 // census ([`INTER_BLOCK_SHAPES`]) by
9364 // [`every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`]
9365 // -- every one of them has a row, so this arm names a shape no stream
9366 // has been able to present.
9367 return Err(unsupported(format!(
9368 "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"
9369 )));
9370 };
9371 // lane-t900 r21: this arm used to refuse EVERY rect strip of a
9372 // screen-content frame ("palette syntax is consumed for square blocks
9373 // only"). It is not: [`read_intra_mode_rect`] generalised the palette read
9374 // to rect blocks on the key-frame path, and the 1:4 arm below goes through
9375 // it, while the 2:1 reader inlined further down now codes the same syntax
9376 // itself. A real `--tune-content=screen` inter stream reached this refusal
9377 // on 8x16 / 16x8 strips (gate
9378 // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`).
9379 // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY
9380 // FRAME path already proves for this shape ([`decode_block_rect4`] at the
9381 // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4
9382 // luma/chroma transform tables, the per-unit split walk and the strip's
9383 // own neighbour records). The ONLY difference on an inter frame is the
9384 // mode-info read, which [`INTRA_IN_INTER_MODE`] switches to
9385 // `read_intra_block_mode_info`'s `y_mode[size_group]` plus the `skip`
9386 // this caller already read. `tx_cat` above is the same category those
9387 // readers hardcode (cat 2 in `decode_block_rect4`, cat 3 in
9388 // `decode_block_rect64`), asserted here so a future shape cannot drift.
9389 if bw.max(bh) == 4 * bw.min(bh) {
9390 debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 });
9391 fctx.intra_in_inter_mode.with(|c| c.set(Some((size_group, skip))));
9392 let res = if bw.max(bh) == 64 {
9393 decode_block_rect64(
9394 dec,
9395 cdfs,
9396 neighbours,
9397 (mi_r / (SUB / MI), mi_c / (SUB / MI)),
9398 bw,
9399 bh,
9400 y,
9401 u,
9402 v,
9403 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
9404 allow_screen_content_tools,
9405 base_q_idx,
9406 fctx.tx_select_inter.with(std::cell::Cell::get),
9407 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
9408 )
9409 } else {
9410 decode_block_rect4(
9411 dec,
9412 cdfs,
9413 neighbours,
9414 (mi_r, mi_c),
9415 bw,
9416 bh,
9417 None,
9418 y,
9419 u,
9420 v,
9421 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
9422 allow_screen_content_tools,
9423 base_q_idx,
9424 fctx.tx_select_inter.with(std::cell::Cell::get), fctx,
9425 )
9426 .map(|_| ())
9427 };
9428 fctx.intra_in_inter_mode.with(|c| c.set(None));
9429 res?;
9430 let shape = match (bw, bh) {
9431 (64, 16) => 0,
9432 (16, 64) => 1,
9433 (32, 8) => 2,
9434 _ => 3,
9435 };
9436 INTRA_RECT4_IN_INTER_HITS.with(|h| {
9437 let mut v = h.get();
9438 v[shape] += 1;
9439 h.set(v);
9440 });
9441 return Ok(());
9442 }
9443 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
9444 // lane-t900 r1: this arm read six mode symbols with no ladder rung of its
9445 // own, so a cross-decoder bisection could only see the block's first
9446 // coefficient. Same names/format as [`read_tx_size`]'s rung.
9447 let step_trace = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
9448 if step_trace {
9449 eprintln!(
9450 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}",
9451 dec.debug_state().0
9452 );
9453 }
9454 if mode >= 13 {
9455 return Err(unsupported(
9456 "an intra mode this decoder does not code (round 2)",
9457 ));
9458 }
9459 // lane-angleinter (merged on main for the square intra-in-inter arm):
9460 // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the
9461 // directional predictor; this arm refused a nonzero one before the merge.
9462 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
9463 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
9464 } else {
9465 0
9466 };
9467 if angle_delta_y != 0 {
9468 INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.set(c.get() + 1));
9469 }
9470 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
9471 // superblock-level strip reads the no-CFL alphabet -- the same split
9472 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
9473 let cfl_allowed = bw.max(bh) <= 32;
9474 let uv_mode = if cfl_allowed {
9475 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
9476 } else {
9477 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
9478 };
9479 if step_trace {
9480 eprintln!(
9481 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}",
9482 u8::from(cfl_allowed),
9483 dec.debug_state().0
9484 );
9485 }
9486 if (9..=12).contains(&uv_mode) {
9487 SMOOTH_UV_HITS.with(|h| h.set(h.get() + 1));
9488 }
9489 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
9490 Some(read_cfl_alphas(dec, cdfs))
9491 } else {
9492 None
9493 };
9494 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
9495 DC_PRED
9496 } else {
9497 uv_mode
9498 };
9499 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
9500 DIRECTIONAL_UV_HITS.with(|h| h.set(h.get() + 1));
9501 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
9502 } else {
9503 0
9504 };
9505 if angle_delta_uv != 0 {
9506 UV_ANGLE_DELTA_HITS.with(|h| h.set(h.get() + 1));
9507 INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|h| h.set(h.get() + 1));
9508 }
9509 // `read_palette_mode_info` (spec 5.11.13), in the position
9510 // `read_intra_block_mode_info` writes it: after the chroma mode and
9511 // before `filter_intra`. lane-t900 r21: a `--tune-content=screen` inter
9512 // frame writes `palette_y_mode`/`palette_uv_mode` for every block whose
9513 // shape [`palette_bsize_ctx_wh`] admits, intra strips included, so
9514 // skipping the syntax here desynced the tile at the strip's own symbol.
9515 // lane-t900 r22: reconstructed, not refused -- the strip's real mode
9516 // context and colour cache at its own mi position, and the two
9517 // colour-index maps decoded after `filter_intra` (`av1_visit_palette`),
9518 // exactly as [`read_intra_mode_rect`] does on the key-frame path.
9519 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi((mi_r, mi_c));
9520 let palette_uv_cache = neighbours.palette_uv_cache_mi((mi_r, mi_c));
9521 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
9522 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
9523 if allow_screen_content_tools
9524 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
9525 {
9526 INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(c.get() + 1));
9527 let use_palette_y =
9528 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0;
9529 if use_palette_y {
9530 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
9531 palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx)));
9532 }
9533 // A 2:1 strip of at least 8x8 is always a chroma reference, so
9534 // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here.
9535 let use_palette_uv =
9536 uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
9537 if crate::envflags::env_flag!("EC_PALSYN") {
9538 eprintln!("EC_PALSYN rect mi={mi_r},{mi_c} bw={bw} bh={bh} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}", use_palette_y as i32, use_palette_uv as i32, dec.debug_state().0);
9539 }
9540 if use_palette_uv {
9541 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
9542 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);
9543 palette_uv_pending = Some((n, u_colors, v_colors));
9544 }
9545 }
9546 // lane-fiinter (merged on main for the square intra-in-inter arm):
9547 // `read_filter_intra_mode_info` is the tail of
9548 // `read_intra_block_mode_info`, after the palette syntax (refused whole
9549 // above for this shape), and `av1_filter_intra_allowed_bsize` admits the
9550 // 2:1 strips with both sides <= 32 -- their own CDF rows
9551 // ([`filter_intra_size_class_rect`]).
9552 let mut filter_intra = None;
9553 if mode == DC_PRED
9554 && fctx.enable_filter_intra_inter.with(std::cell::Cell::get)
9555 // `av1_filter_intra_allowed` excludes a palette-Y block.
9556 && palette_y_pending.is_none()
9557 && let Some(class) = filter_intra_size_class_rect(bw, bh)
9558 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
9559 {
9560 FILTER_INTRA_HITS.with(|h| h.set(h.get() + 1));
9561 INTRA_IN_INTER_FILTER_INTRA_HITS.with(|h| h.set(h.get() + 1));
9562 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
9563 }
9564 // `av1_visit_palette`: Y's colour-index map then the shared chroma one.
9565 let palette_y = palette_y_pending.map(|(n, colors)| {
9566 let map = decode_color_index_map_wh(dec, cdfs, n, bw, bh, false);
9567 PALETTE_HITS.with(|c| c.set(c.get() + 1));
9568 PALETTE_RECT_HITS.with(|c| c.set(c.get() + 1));
9569 INTRA_IN_INTER_PALETTE_Y_HITS.with(|c| c.set(c.get() + 1));
9570 PaletteY { size: n, colors, map }
9571 });
9572 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
9573 let (cw, ch) = ((bw / 2).max(4), (bh / 2).max(4));
9574 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, true);
9575 PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
9576 INTRA_IN_INTER_PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
9577 PaletteUv { size: n, u_colors, v_colors, map }
9578 });
9579 // The intra-edge filter type is the NEIGHBOUR's mode (libaom
9580 // `get_filt_type`), luma's off the luma neighbours and chroma's off the
9581 // chroma ones -- [`decode_block_rect`]'s own pair.
9582 // lane-t900 r4: the coarse pair is keyed on the 16x16 cell's OWN top-left
9583 // mi, so both 8x16 halves of a VERT split read the neighbours of the FIRST
9584 // half. libaom's `above_mbmi`/`left_mbmi` are this block's own
9585 // (`mi[-mi_stride]` / `mi[-1]`) -- take the mi-exact pair over the coarse
9586 // one exactly as [`decode_leaf8`] already does (class
9587 // context-read-from-one-cell).
9588 let coarse_pair = neighbours.modes_above_left(r, c);
9589 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, coarse_pair);
9590 if (nb_above_mode, nb_left_mode) != coarse_pair {
9591 EDGE_FILTER_MI_FIX_HITS.with(|c| c.set(c.get() + 1));
9592 }
9593 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
9594 if smooth_neighbor {
9595 SMOOTH_LUMA_HITS.with(|h| h.set(h.get() + 1));
9596 }
9597 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
9598 let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) {
9599 // The INTER frame's own `TXFM_CONTEXT` bands, not the key frame's
9600 // deblock-grid approximation -- [`tx_size_context_txfm_rect`].
9601 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
9602 let d = match tx_cat {
9603 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
9604 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
9605 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
9606 };
9607 if step_trace {
9608 eprintln!(
9609 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}",
9610 dec.debug_state().0
9611 );
9612 }
9613 d
9614 } else {
9615 0
9616 };
9617 if depth != 0 {
9618 TX_DEPTH_HITS.with(|h| h.set(h.get() + 1));
9619 // lane-intrasplit r1: a split intra strip in an inter frame walks the
9620 // key frame's own per-TU path ([`decode_rect_split`] below); what was
9621 // wrong when this refusal was written was the depth SYMBOL, not the walk.
9622 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(|h| {
9623 let mut v = h.get();
9624 v[depth.min(2)] += 1;
9625 h.set(v);
9626 });
9627 }
9628 // lane-intrasplit r3: print EVERY intra strip with its depth, not only the
9629 // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and
9630 // the two are indistinguishable when the diagnostic fires on splits alone.
9631 if crate::envflags::env_flag!("EC_SPLITSTRIP") {
9632 eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}");
9633 }
9634 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
9635 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,
9636 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block
9637 // of an inter frame, intra ones included -- with the skip term 0 it
9638 // memsets `above_txfm_context` to `tx_size_wide` over the block's width
9639 // and `left_txfm_context` to `tx_size_high` over its height. This strip
9640 // wrote neither, so the next block's var-tx `txfm_partition` context read
9641 // a stale band: on a 192x128 8-bit stream the 16x8 intra strip at
9642 // mi(14,0) left 8 where libaom has 16, giving ctx 13 instead of 12 at
9643 // mi(16,0) and desyncing the tile at that symbol.
9644 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
9645 let modes = RectStripModes {
9646 skip,
9647 mode,
9648 angle_delta_y,
9649 uv_predict_mode,
9650 angle_delta_uv,
9651 alpha,
9652 filter_intra,
9653 smooth_neighbor,
9654 smooth_neighbor_uv,
9655 palette_y: palette_y
9656 .as_ref()
9657 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
9658 palette_uv: palette_uv.as_ref().map(|p| {
9659 (
9660 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
9661 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
9662 )
9663 }),
9664 };
9665 decode_rect_split(
9666 dec,
9667 cdfs,
9668 neighbours,
9669 (mi_r, mi_c),
9670 bw,
9671 bh,
9672 tx_w,
9673 tx_h,
9674 &modes,
9675 y,
9676 u,
9677 v,
9678 base_q_idx,
9679 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
9680 )?;
9681 // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of
9682 // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in
9683 // both `TXFM_CONTEXT` bands -- the above row over the block's width, the
9684 // left column over its height. This arm wrote neither before lane-intrasplit
9685 // r1, so every later block in the frame read a stale `tx_size`/`txfm_split`
9686 // context across the strip's footprint.
9687 for i in 0..bw / MI {
9688 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
9689 *cell = tx_w as u8;
9690 }
9691 }
9692 for i in 0..bh / MI {
9693 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
9694 *cell = tx_h as u8;
9695 }
9696 }
9697 // The strip's own palette state into the mi-granular neighbour bands, so
9698 // the next block's colour cache and `palette_y_mode` context are libaom's.
9699 record_strip_palette(
9700 neighbours,
9701 (mi_r, mi_c),
9702 bw,
9703 bh,
9704 palette_y.as_ref().map_or(0, |p| p.size),
9705 palette_y.as_ref().map_or([0u16; 8], |p| p.colors),
9706 palette_uv.as_ref().map_or(0, |p| p.size),
9707 palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors),
9708 );
9709 let class = match bw.max(bh) {
9710 64 => 0,
9711 32 => 1,
9712 _ => 2,
9713 };
9714 INTRA_RECT_IN_INTER_HITS.with(|h| {
9715 let mut v = h.get();
9716 v[class] += 1;
9717 h.set(v);
9718 });
9719 Ok(())
9720}
9721
9722/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
9723/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
9724/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
9725/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
9726/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
9727/// has no rectangular-transform coefficient reader, and a chroma plane here
9728/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
9729/// with no depth-based square-tiling escape the way luma's own resolved
9730/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
9731/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
9732#[allow(clippy::too_many_arguments)]
9733fn decode_block_rect(
9734 dec: &mut SymbolDecoder,
9735 cdfs: &mut Cdfs,
9736 neighbours: &mut Neighbours,
9737 at: (usize, usize),
9738 bw: usize,
9739 bh: usize,
9740 y: &mut PlaneBuf<'static>,
9741 u: &mut PlaneBuf<'static>,
9742 v: &mut PlaneBuf<'static>,
9743 enable_filter_intra: bool,
9744 allow_screen_content_tools: bool,
9745 base_q_idx: u8,
9746 tx_select: bool,
9747 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
9748) -> Result<()> {
9749 let (r, c) = at;
9750 let (px, py) = (c * SUB, r * SUB);
9751 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
9752 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
9753 let palette_uv_cache = neighbours.palette_uv_cache(at);
9754 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
9755 read_intra_mode_rect(
9756 dec,
9757 cdfs,
9758 nb_above_mode,
9759 nb_left_mode,
9760 true,
9761 true,
9762 bw,
9763 bh,
9764 enable_filter_intra,
9765 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
9766 allow_screen_content_tools,
9767 Some((palette_ctx, &palette_cache)),
9768 &palette_uv_cache,
9769 r * (SUB / MI),
9770 c * (SUB / MI), fctx,
9771 )?;
9772 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
9773 if smooth_neighbor {
9774 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
9775 }
9776 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
9777 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
9778 // `uv_mode`, not the luma one.
9779 let smooth_neighbor_uv =
9780 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
9781 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
9782 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
9783 // rectangle just as happily), so a `use_filter_intra` strip at this level
9784 // predicts instead of refusing. The below-16x16 leaf arm
9785 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
9786 if filter_intra.is_some() {
9787 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
9788 }
9789 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
9790 DC_PRED
9791 } else {
9792 uv_mode
9793 };
9794 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
9795 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
9796 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
9797 // one did not, so with `--enable-tx-size-search=0` -- which several gate
9798 // recipes use -- the decoder consumed a symbol the encoder never wrote and
9799 // desynced the tile from that point on. That is why both strips of the
9800 // pinned HORZ quadrant were wrong from their very first pixel, and why our
9801 // range after the read equalled the oracle's range for the whole block.
9802 let depth = if tx_select {
9803 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
9804 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
9805 // the 16x4 intra-in-inter strips already do); the key frame's
9806 // deblock-grid approximation is only right where those bands were never
9807 // written. Measured on the 10-bit 1920x792 128-superblock stream,
9808 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
9809 // `tx_size_cat2` row 1 where libaom reads row 2.
9810 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
9811 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
9812 } else {
9813 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
9814 };
9815 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
9816 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
9817 eprintln!(
9818 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
9819 dec.debug_state().0
9820 );
9821 }
9822 d
9823 } else {
9824 0
9825 };
9826 if depth != 0 {
9827 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
9828 // lane-rectsplit r1: a split transform is predicted and reconstructed
9829 // per transform unit, each unit taking its edges from the previous
9830 // unit's reconstruction inside this same strip (spec 5.11.36) --
9831 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
9832 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
9833 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
9834 eprintln!(
9835 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
9836 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
9837 angle_y={angle_delta_y}"
9838 );
9839 }
9840 let modes = RectStripModes {
9841 skip,
9842 mode,
9843 angle_delta_y,
9844 uv_predict_mode,
9845 angle_delta_uv,
9846 alpha,
9847 filter_intra,
9848 smooth_neighbor,
9849 smooth_neighbor_uv,
9850 palette_y: palette_y
9851 .as_ref()
9852 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
9853 palette_uv: palette_uv.as_ref().map(|p| {
9854 (
9855 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
9856 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
9857 )
9858 }),
9859 };
9860 if palette_y.is_some() || palette_uv.is_some() {
9861 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
9862 }
9863 decode_rect_split(
9864 dec,
9865 cdfs,
9866 neighbours,
9867 (mi_r, mi_c),
9868 bw,
9869 bh,
9870 tx_w,
9871 tx_h,
9872 &modes,
9873 y,
9874 u,
9875 v,
9876 base_q_idx,
9877 reduced_tx_set, fctx,
9878 )?;
9879 // This early return skips this fn's own tail, so the palette
9880 // neighbour state has to be stamped HERE too: without it a split-tx
9881 // strip left the above/left palette arrays holding a DEAD block's
9882 // colours, and the next block's colour cache
9883 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
9884 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
9885 // and only those pixels were wrong (lane-palette2 r10).
9886 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
9887 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
9888 let (puv_size, puv_colors) =
9889 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
9890 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
9891 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
9892 return Ok(());
9893 }
9894 let (tx_w, tx_h) = (bw, bh);
9895 let (cpx, cpy) = (px / 2, py / 2);
9896 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
9897 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
9898 if crate::envflags::env_flag!("EC_AV1_TRACE") {
9899 let (rng, _) = dec.debug_state();
9900 eprintln!(
9901 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
9902 skip={} tx={depth} rng={rng}",
9903 skip as i32
9904 );
9905 }
9906 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
9907 // block's prediction is the reconstructed colour-index map, set fresh
9908 // right before each `reconstruct_rect` call below (lane-palette2 r4).
9909 if let Some(ref pyv) = palette_y {
9910 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
9911 set_palette_pred(buf, fctx);
9912 }
9913 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
9914 (
9915 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
9916 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
9917 )
9918 });
9919 if skip {
9920 push_intra_rect(0,
9921 px,
9922 py,
9923 bw,
9924 bh,
9925 mode,
9926 angle_delta_y,
9927 reach,
9928 &vec![0i32; bw * bh],
9929 None,
9930 filter_intra,
9931 smooth_neighbor, fctx,
9932 );
9933 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
9934 if let Some((ub, _)) = &palette_uv_bufs {
9935 set_palette_pred(ub.clone(), fctx);
9936 }
9937 push_intra_rect(1,
9938 cpx,
9939 cpy,
9940 chroma_w,
9941 chroma_h,
9942 uv_predict_mode,
9943 angle_delta_uv,
9944 reach,
9945 &vec![0i32; chroma_w * chroma_h],
9946 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
9947 None,
9948 smooth_neighbor_uv, fctx,
9949 );
9950 if let Some((_, vb)) = &palette_uv_bufs {
9951 set_palette_pred(vb.clone(), fctx);
9952 }
9953 push_intra_rect(2,
9954 cpx,
9955 cpy,
9956 chroma_w,
9957 chroma_h,
9958 uv_predict_mode,
9959 angle_delta_uv,
9960 reach,
9961 &vec![0i32; chroma_w * chroma_h],
9962 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
9963 None,
9964 smooth_neighbor_uv, fctx,
9965 );
9966 neighbours.record_rect(
9967 at,
9968 bw,
9969 bh,
9970 mode,
9971 uv_predict_mode,
9972 &[
9973 vec![0i32; bw * bh],
9974 vec![0i32; chroma_w * chroma_h],
9975 vec![0i32; chroma_w * chroma_h],
9976 ],
9977 );
9978 } else {
9979 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
9980 // reduces both size pairs to their square-up CDF sets
9981 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
9982 // doc comments); the scan order and 2D context tables are the real
9983 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
9984 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 32 {
9985 (&SCAN_32X16, &SCAN_16X8)
9986 } else {
9987 (&SCAN_16X32, &SCAN_8X16)
9988 };
9989 // lane-rectwire r3: real coefficients desync a pixel-exact gate
9990 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
9991 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
9992 // pixel (not a subtle context-table off-by-one), while the sibling
9993 // non-rect quadrants of the same frame match. Range-ladder bisection
9994 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
9995 // but the intra key-frame path has no traced symbol between the
9996 // partition read and the first coefficient block (mode/skip/tx_depth
9997 // reads are all untraced in libaom's decodeframe.c intra path, unlike
9998 // the inter EC_TRACE_MODE this round added), so a same-length range
9999 // comparison wasn't reachable within budget -- see
10000 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
10001 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
10002 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
10003 // libaom and match). lane-rectwire r4: range-ladder against the
10004 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
10005 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
10006 // both confirmed in sync -- rng=58692 on both sides right after
10007 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
10008 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
10009 // immediately after: ours moves rng 58692 -> 43570, which cannot be
10010 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
10011 // its own tx_size read) unless oracle's tx symbol is a near-certainty
10012 // CDF that barely narrows the range -- i.e. this decoder's
10013 // `tx_size_context_rect` ctx or `cdfs.tx_size_cat2` CDF selection for
10014 // a 32x16/16x32 strip is the first diverging symbol, not the
10015 // coefficient-context math r3 already cleared. Not confirmed byte-
10016 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
10017 // `read_tx_size`'s own rng, not attempted this round -- budget), so
10018 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
10019 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
10020 // it unconditionally where both square paths gate on `tx_select`. With
10021 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
10022 // decoder consumed one that was never there.
10023 {
10024 let around = neighbours.around_rect(at, bw, bh);
10025 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
10026 let (luma_levels, luma_tx_type) = read_coeffs_rect(
10027 dec,
10028 &mut luma_coding,
10029 luma_scan,
10030 bw,
10031 bh,
10032 0,
10033 dc_sign_ctx(around[0].2),
10034 TxType::DctDct,
10035 )?;
10036 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10037 let (rng, _) = dec.debug_state();
10038 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
10039 }
10040 let luma_residual = dequant_and_inverse_typed_wh(
10041 &luma_levels,
10042 bw,
10043 bh,
10044 crate::decode::bit_depth(fctx),
10045 block_q_idx(fctx),
10046 plane_q_delta(0, fctx).0,
10047 plane_q_delta(0, fctx).1,
10048 luma_tx_type,
10049 );
10050 push_intra_rect(0,
10051 px,
10052 py,
10053 bw,
10054 bh,
10055 mode,
10056 angle_delta_y,
10057 reach,
10058 &luma_residual,
10059 None,
10060 filter_intra,
10061 smooth_neighbor, fctx,
10062 );
10063 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
10064 if let Some((ub, _)) = &palette_uv_bufs {
10065 set_palette_pred(ub.clone(), fctx);
10066 }
10067 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
10068 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
10069 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
10070 let (u_levels, u_tx_type) = read_coeffs_rect(
10071 dec,
10072 &mut u_coding,
10073 chroma_scan,
10074 chroma_w,
10075 chroma_h,
10076 u_skip_ctx,
10077 dc_sign_ctx(around[1].2),
10078 u_default_tx,
10079 )?;
10080 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10081 let (rng, _) = dec.debug_state();
10082 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
10083 }
10084 let u_residual = dequant_and_inverse_typed_wh(
10085 &u_levels,
10086 chroma_w,
10087 chroma_h,
10088 crate::decode::bit_depth(fctx),
10089 block_q_idx(fctx),
10090 plane_q_delta(1, fctx).0,
10091 plane_q_delta(1, fctx).1,
10092 u_tx_type,
10093 );
10094 push_intra_rect(1,
10095 cpx,
10096 cpy,
10097 chroma_w,
10098 chroma_h,
10099 uv_predict_mode,
10100 angle_delta_uv,
10101 reach,
10102 &u_residual,
10103 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
10104 None,
10105 smooth_neighbor_uv, fctx,
10106 );
10107 if let Some((_, vb)) = &palette_uv_bufs {
10108 set_palette_pred(vb.clone(), fctx);
10109 }
10110 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
10111 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
10112 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
10113 let (v_levels, v_tx_type) = read_coeffs_rect(
10114 dec,
10115 &mut v_coding,
10116 chroma_scan,
10117 chroma_w,
10118 chroma_h,
10119 v_skip_ctx,
10120 dc_sign_ctx(around[2].2),
10121 v_default_tx,
10122 )?;
10123 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10124 let (rng, _) = dec.debug_state();
10125 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
10126 }
10127 let v_residual = dequant_and_inverse_typed_wh(
10128 &v_levels,
10129 chroma_w,
10130 chroma_h,
10131 crate::decode::bit_depth(fctx),
10132 block_q_idx(fctx),
10133 plane_q_delta(2, fctx).0,
10134 plane_q_delta(2, fctx).1,
10135 v_tx_type,
10136 );
10137 push_intra_rect(2,
10138 cpx,
10139 cpy,
10140 chroma_w,
10141 chroma_h,
10142 uv_predict_mode,
10143 angle_delta_uv,
10144 reach,
10145 &v_residual,
10146 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
10147 None,
10148 smooth_neighbor_uv, fctx,
10149 );
10150 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
10151 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
10152 }
10153 }
10154 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
10155 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
10156 let (puv_size, puv_colors) =
10157 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
10158 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
10159 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
10160 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
10161 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
10162 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10163 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
10164 }
10165 Ok(())
10166}
10167
10168/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
10169/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
10170/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
10171/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
10172/// the second strip of a HORZ/VERT split sits offset by half the 16x16
10173/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
10174/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
10175/// previous strip is directly above (same column, `mi_h` rows up) or
10176/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
10177/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
10178/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
10179/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
10180/// this strip's real position, never the coarse `record_rect` (which the
10181/// caller uses once, after both strips, exactly like the `VERT_B` arm next
10182/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
10183/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
10184/// chroma half (`TxbSet::ChromaRect8x4`), the two size classes one level
10185/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
10186#[allow(clippy::too_many_arguments)]
10187fn decode_leaf_rect(
10188 dec: &mut SymbolDecoder,
10189 cdfs: &mut Cdfs,
10190 neighbours: &mut Neighbours,
10191 outer_at: (usize, usize),
10192 leaf_mi: (usize, usize),
10193 bw: usize,
10194 bh: usize,
10195 prev_leaf: Option<((usize, usize), usize)>,
10196 y: &mut PlaneBuf<'static>,
10197 u: &mut PlaneBuf<'static>,
10198 v: &mut PlaneBuf<'static>,
10199 enable_filter_intra: bool,
10200 allow_screen_content_tools: bool,
10201 base_q_idx: u8,
10202 tx_select: bool,
10203 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
10204) -> Result<usize> {
10205 let _ = base_q_idx;
10206 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
10207 eprintln!(
10208 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
10209 dec.debug_state().0
10210 );
10211 }
10212 let (r, c) = outer_at;
10213 let mut above_mode = neighbours.above_mode[c];
10214 let mut left_mode = neighbours.left_mode[r];
10215 let (mi_w, mi_h) = (bw / MI, bh / MI);
10216 if let Some(((pr, pc), pmode)) = prev_leaf {
10217 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
10218 above_mode = pmode;
10219 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
10220 left_mode = pmode;
10221 }
10222 }
10223 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
10224 // cannot hold the modes a split (or a pair of strips) leaves behind, so
10225 // when the map holds the block at exactly this strip's above/left mi it
10226 // is the neighbour libaom's `above_mi`/`left_mi` reads.
10227 // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND
10228 // availability-correct -- four 16x8 strips share one coarse 16x16
10229 // `left_mode` cell too, so the fallback must not stand in for an absent
10230 // tile-edge neighbour.
10231 let (above_mode, left_mode) =
10232 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
10233 let smooth_neighbor =
10234 is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
10235 if smooth_neighbor {
10236 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
10237 }
10238 // The palette-Y mode CDF row is picked by the neighbours' palette use
10239 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
10240 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
10241 // a palette narrows the wrong interval and desyncs the tile even when the
10242 // decoded bit is the same. The cell is the 16px-SUB cell containing the
10243 // leaf (the palette neighbour arrays have no finer granularity).
10244 // lane-kf900 r6: the leaf's REAL mi position -- the second leaf of a 16x8
10245 // pair sits 8 px into the 16px cell, and both the cache's superblock-top-row
10246 // exclusion and the neighbour palette lookup itself are mi-granular
10247 // (see [`Neighbours::palette_ctx_and_cache_mi`]).
10248 let pal_at = leaf_mi;
10249 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
10250 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
10251 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
10252 read_intra_mode_rect(
10253 dec,
10254 cdfs,
10255 above_mode,
10256 left_mode,
10257 true,
10258 true,
10259 bw,
10260 bh,
10261 enable_filter_intra,
10262 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
10263 allow_screen_content_tools,
10264 Some((palette_ctx, &palette_cache)),
10265 &palette_uv_cache,
10266 leaf_mi.0,
10267 leaf_mi.1, fctx,
10268 )?;
10269 // lane-kf900 r4: palette prediction on this shape, the same colour-index
10270 // map -> base colours buffer [`decode_block_rect`] hands each
10271 // `reconstruct_rect` through [`set_palette_pred`].
10272 if palette_y.is_some() || palette_uv.is_some() {
10273 RECT4_PALETTE_HITS.with(|c| c.set(c.get() + 1));
10274 }
10275 let palette_y_buf: Option<Vec<u16>> = palette_y
10276 .as_ref()
10277 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
10278 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
10279 (
10280 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
10281 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
10282 )
10283 });
10284 let (pal_y_size, pal_y_colors) =
10285 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
10286 let (pal_uv_size, pal_uv_colors) =
10287 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
10288 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
10289 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
10290 }
10291 if filter_intra.is_some() {
10292 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
10293 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
10294 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
10295 // below already makes; this refusal was square-only prose.
10296 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
10297 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.set(c.get() + 1));
10298 }
10299 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
10300 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
10301 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
10302 // a constant `false`.
10303 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
10304 let depth = if tx_select {
10305 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read
10306 // every other rect reader now does -- a no-op on a key frame.
10307 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
10308 tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx)
10309 } else {
10310 tx_size_context_rect(neighbours, leaf_mi, bw, bh)
10311 };
10312 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
10313 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
10314 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
10315 // count (3), different CDF row: a wrong-table read of a real symbol,
10316 // the class that cost lane-rectsplit r1 its 64x32 depth.
10317 // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's
10318 // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and
10319 // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this
10320 // function also decodes) sit at depth 2, so they read
10321 // `tx_size_cdf[1]` -- the same table a 16x16 square block reads --
10322 // while `tx_size_cat2` belongs to the 32-level shapes
10323 // ([`decode_block_rect`]). Both tables carry three symbols, so the
10324 // wrong one decodes a plausible depth from the wrong probabilities:
10325 // the range diverges silently at the first such leaf and every later
10326 // symbol in the tile is read from the wrong place (class
10327 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
10328 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
10329 } else {
10330 0
10331 };
10332 if depth != 0 {
10333 // The same per-transform-unit walk the bigger strips take
10334 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
10335 // depth 2), addressed at this leaf's own mi position.
10336 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
10337 SUB16_SPLIT_HITS.with(|c| c.set(c.get() + 1));
10338 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
10339 let modes = RectStripModes {
10340 skip,
10341 mode,
10342 angle_delta_y,
10343 uv_predict_mode,
10344 angle_delta_uv,
10345 alpha,
10346 filter_intra,
10347 smooth_neighbor,
10348 // lane-rectsplitx r3: the split arm hard-coded `false` here while
10349 // the unsplit arm below passes the real neighbour answer -- chroma
10350 // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type.
10351 smooth_neighbor_uv,
10352 palette_y: palette_y_buf.clone(),
10353 palette_uv: palette_uv_bufs.clone(),
10354 };
10355 if palette_y.is_some() || palette_uv.is_some() {
10356 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
10357 }
10358 decode_rect_split(
10359 dec,
10360 cdfs,
10361 neighbours,
10362 leaf_mi,
10363 bw,
10364 bh,
10365 tx_w,
10366 tx_h,
10367 &modes,
10368 y,
10369 u,
10370 v,
10371 base_q_idx,
10372 reduced_tx_set, fctx,
10373 )?;
10374 record_strip_palette(
10375 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
10376 );
10377 return Ok(mode);
10378 }
10379 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
10380 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
10381 let (cpx, cpy) = (px / 2, py / 2);
10382 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
10383 let (luma_levels, u_levels, v_levels);
10384 if skip {
10385 luma_levels = vec![0i32; bw * bh];
10386 u_levels = vec![0i32; chroma_w * chroma_h];
10387 v_levels = vec![0i32; chroma_w * chroma_h];
10388 if let Some(b) = &palette_y_buf {
10389 set_palette_pred(b.clone(), fctx);
10390 }
10391 push_intra_rect(0,
10392 px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra,
10393 smooth_neighbor, fctx,
10394 );
10395 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
10396 if let Some((ub, _)) = &palette_uv_bufs {
10397 set_palette_pred(ub.clone(), fctx);
10398 }
10399 push_intra_rect(1,
10400 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels,
10401 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx,
10402 );
10403 if let Some((_, vb)) = &palette_uv_bufs {
10404 set_palette_pred(vb.clone(), fctx);
10405 }
10406 push_intra_rect(2,
10407 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels,
10408 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx,
10409 );
10410 } else {
10411 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
10412 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
10413 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
10414 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
10415 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
10416 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
10417 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 16 {
10418 (&SCAN_16X8, &SCAN_8X4)
10419 } else {
10420 (&SCAN_8X16, &SCAN_4X8)
10421 };
10422 let around = neighbours.around_mi_rect(leaf_mi, bw, bh);
10423 let luma_set = if reduced_tx_set {
10424 TxbSet::LumaRect16x8
10425 } else {
10426 TxbSet::LumaRect16x8Set1
10427 };
10428 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
10429 let (l_levels, luma_tx_type) = read_coeffs_rect(
10430 dec, &mut luma_coding, luma_scan, bw, bh, 0, dc_sign_ctx(around[0].2), TxType::DctDct,
10431 )?;
10432 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
10433 let nz: Vec<(usize, i32)> = l_levels.iter().copied().enumerate().filter(|(_, v)| *v != 0).collect();
10434 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
10435 }
10436 luma_levels = l_levels;
10437 let luma_residual = dequant_and_inverse_typed_wh(
10438 &luma_levels, bw, bh, crate::decode::bit_depth(fctx),
10439 fctx.current_q_idx.with(|c| c.get()), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, luma_tx_type,
10440 );
10441 if let Some(b) = &palette_y_buf {
10442 set_palette_pred(b.clone(), fctx);
10443 }
10444 push_intra_rect(0,
10445 px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra,
10446 smooth_neighbor, fctx,
10447 );
10448 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
10449 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
10450 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
10451 let mut u_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
10452 let (u_l, u_tx_type) = read_coeffs_rect(
10453 dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx,
10454 dc_sign_ctx(around[1].2), u_default_tx,
10455 )?;
10456 u_levels = u_l;
10457 let u_residual = dequant_and_inverse_typed_wh(
10458 &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx),
10459 fctx.current_q_idx.with(|c| c.get()), plane_q_delta(1, fctx).0, plane_q_delta(1, fctx).1, u_tx_type,
10460 );
10461 if let Some((ub, _)) = &palette_uv_bufs {
10462 set_palette_pred(ub.clone(), fctx);
10463 }
10464 push_intra_rect(1,
10465 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual,
10466 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx,
10467 );
10468 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
10469 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
10470 let mut v_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
10471 let (v_l, v_tx_type) = read_coeffs_rect(
10472 dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx,
10473 dc_sign_ctx(around[2].2), v_default_tx,
10474 )?;
10475 v_levels = v_l;
10476 let v_residual = dequant_and_inverse_typed_wh(
10477 &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx),
10478 fctx.current_q_idx.with(|c| c.get()), plane_q_delta(2, fctx).0, plane_q_delta(2, fctx).1, v_tx_type,
10479 );
10480 if let Some((_, vb)) = &palette_uv_bufs {
10481 set_palette_pred(vb.clone(), fctx);
10482 }
10483 push_intra_rect(2,
10484 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual,
10485 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx,
10486 );
10487 RECT_LEAF_COEFF_HITS.with(|c| c.set(c.get() + 1));
10488 }
10489 neighbours.record_mi_rect(leaf_mi, bw, bh, &[luma_levels, u_levels, v_levels]);
10490 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
10491 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
10492 // The leaf's own palette state (`0` clears, as this site always did
10493 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT
10494 // AXIS only until the pair's closing leaf: the coarse cell holds one
10495 // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the
10496 // real left neighbour leaf 1 reads (lane-kf900 r4).
10497 record_strip_palette(
10498 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
10499 );
10500 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
10501 // rows -- record the whole span, not one cell.
10502 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
10503 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
10504 Ok(mode)
10505}
10506
10507/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
10508/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
10509/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
10510/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
10511/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
10512/// strip's mode so this one's mode context sees its true above/left
10513/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
10514///
10515/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
10516/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
10517/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
10518/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
10519/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
10520/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
10521/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
10522///
10523/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
10524/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
10525/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
10526/// unexamined.
10527#[allow(clippy::too_many_arguments)]
10528fn decode_block_rect4(
10529 dec: &mut SymbolDecoder,
10530 cdfs: &mut Cdfs,
10531 neighbours: &mut Neighbours,
10532 strip_mi: (usize, usize),
10533 bw: usize,
10534 bh: usize,
10535 prev_strip: Option<((usize, usize), usize)>,
10536 y: &mut PlaneBuf<'static>,
10537 u: &mut PlaneBuf<'static>,
10538 v: &mut PlaneBuf<'static>,
10539 enable_filter_intra: bool,
10540 allow_screen_content_tools: bool,
10541 base_q_idx: u8,
10542 tx_select: bool, fctx: &crate::decode::FrameCtx,
10543) -> Result<(usize, usize)> {
10544 let _ = base_q_idx;
10545 let (mi_r, mi_c) = strip_mi;
10546 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
10547 let (mi_w, mi_h) = (bw / MI, bh / MI);
10548 let mut above_mode = neighbours.above_mode[c];
10549 let mut left_mode = neighbours.left_mode[r];
10550 if let Some(((pr, pc), pmode)) = prev_strip {
10551 if pc == mi_c && mi_r == pr + mi_h {
10552 above_mode = pmode;
10553 } else if pr == mi_r && mi_c == pc + mi_w {
10554 left_mode = pmode;
10555 }
10556 }
10557 // lane-rectsplitx r2, ROOT CAUSE of the 1:4 mismatch: mi-exact +
10558 // availability-correct neighbour modes (see
10559 // [`Neighbours::modes_above_left_mi`]). The coarse 16x16 bands alias every
10560 // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell.
10561 let (above_mode, left_mode) =
10562 neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode));
10563 // lane-kf900 r4: this strip's own palette-Y mode ctx and colour cache.
10564 // Passing `None`/`&[]` read `palette_y_mode` off CDF row 0 and every
10565 // `palette_colors_y` cache hit off an EMPTY cache -- right symbol count,
10566 // wrong interval, so a screen-content tile desynced at the first strip
10567 // whose neighbour used a palette (class [[cdf-row-held-constant]]).
10568 let pal_at = (mi_r, mi_c);
10569 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
10570 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
10571 let (
10572 skip,
10573 mode,
10574 angle_delta_y,
10575 uv_mode,
10576 angle_delta_uv,
10577 alpha,
10578 filter_intra,
10579 palette_y,
10580 palette_uv,
10581 ) = read_intra_mode_rect(
10582 dec,
10583 cdfs,
10584 above_mode,
10585 left_mode,
10586 true,
10587 true,
10588 bw,
10589 bh,
10590 enable_filter_intra,
10591 neighbours.skip_txfm_ctx(mi_r, mi_c),
10592 allow_screen_content_tools,
10593 Some((palette_ctx, &palette_cache)),
10594 &palette_uv_cache,
10595 mi_r,
10596 mi_c, fctx,
10597 )?;
10598 // lane-kf900 r4: palette prediction on this shape, exactly as
10599 // [`decode_block_rect`] does one aspect ratio up -- the colour-index map
10600 // mapped through the base colours IS the prediction (it reads no edge
10601 // pixels), handed to each `reconstruct_rect` through [`set_palette_pred`].
10602 if palette_y.is_some() || palette_uv.is_some() {
10603 RECT4_PALETTE_HITS.with(|c| c.set(c.get() + 1));
10604 }
10605 let palette_y_buf: Option<Vec<u16>> = palette_y
10606 .as_ref()
10607 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
10608 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
10609 (
10610 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
10611 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
10612 )
10613 });
10614 let (pal_y_size, pal_y_colors) =
10615 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
10616 let (pal_uv_size, pal_uv_colors) =
10617 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
10618 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
10619 if smooth_neighbor {
10620 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
10621 }
10622 // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's
10623 // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so
10624 // `r * (SUB / MI)` names a different mi column and the chroma
10625 // edge-filter strength was read from the wrong neighbour (measured:
10626 // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch
10627 // with luma bit-exact).
10628 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
10629 if filter_intra.is_some() {
10630 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
10631 if bw > bh {
10632 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.set(c.get() + 1));
10633 } else {
10634 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.set(c.get() + 1));
10635 }
10636 }
10637 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
10638 DC_PRED
10639 } else {
10640 uv_mode
10641 };
10642 let depth = if tx_select {
10643 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
10644 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
10645 // the 16x4 intra-in-inter strips already do); the key frame's
10646 // deblock-grid approximation is only right where those bands were never
10647 // written. Measured on the 10-bit 1920x792 128-superblock stream,
10648 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
10649 // `tx_size_cat2` row 1 where libaom reads row 2.
10650 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
10651 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
10652 } else {
10653 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
10654 };
10655 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
10656 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
10657 eprintln!(
10658 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
10659 dec.debug_state().0
10660 );
10661 }
10662 d
10663 } else {
10664 0
10665 };
10666 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
10667 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
10668 publish_txfm_bands_if_in_inter(
10669 neighbours,
10670 (mi_r, mi_c),
10671 depth_to_tx_wh(bw, bh, depth),
10672 (bw, bh), fctx,
10673 );
10674 if depth != 0 {
10675 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
10676 // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a
10677 // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16
10678 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8;
10679 // both interleave in every real stream.
10680 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
10681 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
10682 // lane-rectsplitx r2: both depths ship together, as the r1 handoff
10683 // predicted -- depth 1 fires FIRST in every attempt that splits at
10684 // all, so a depth-2-only lift could never be gated. The r1 mismatch
10685 // was never the rect unit: it was the neighbour MODE the strip reads
10686 // (see `modes_above_left_mi`).
10687 let which = if depth == 1 {
10688 &RECT4_SPLIT_DEPTH1_HITS
10689 } else {
10690 &RECT4_SPLIT_DEPTH2_HITS
10691 };
10692 which.with(|c| c.set(c.get() + 1));
10693 let modes = RectStripModes {
10694 skip,
10695 mode,
10696 angle_delta_y,
10697 uv_predict_mode,
10698 angle_delta_uv,
10699 alpha,
10700 filter_intra,
10701 smooth_neighbor,
10702 smooth_neighbor_uv,
10703 palette_y: palette_y_buf.clone(),
10704 palette_uv: palette_uv_bufs.clone(),
10705 };
10706 if palette_y.is_some() || palette_uv.is_some() {
10707 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
10708 }
10709 decode_rect_split(
10710 dec,
10711 cdfs,
10712 neighbours,
10713 (mi_r, mi_c),
10714 bw,
10715 bh,
10716 tx_w,
10717 tx_h,
10718 &modes,
10719 y,
10720 u,
10721 v,
10722 base_q_idx,
10723 false, fctx,
10724 )?;
10725 record_strip_palette(
10726 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
10727 pal_uv_colors,
10728 );
10729 if bw > bh {
10730 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
10731 } else {
10732 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
10733 }
10734 if !skip {
10735 RECT4_COEFF_HITS.with(|c| c.set(c.get() + 1));
10736 }
10737 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
10738 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
10739 // frame, so this 1:4 strip -- which is also the INTER frame's reader
10740 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
10741 // transform size in both TXFM_CONTEXT bands. Without it the next block
10742 // reads the row's stale value.
10743 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
10744 return Ok((mode, uv_predict_mode));
10745 }
10746 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
10747 // that is 8 px tall, so each strip stamps every cell it touches and the
10748 // LAST strip wins -- which is the right answer for the block below/right
10749 // of the 32x32, the only reader outside it. Written after this strip's
10750 // own context read above, never before.
10751 for cell in 0..bw.div_ceil(SUB) {
10752 neighbours.above_mode[c + cell] = mode;
10753 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
10754 neighbours.above_side[c + cell] = bw;
10755 }
10756 for cell in 0..bh.div_ceil(SUB) {
10757 neighbours.left_mode[r + cell] = mode;
10758 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
10759 neighbours.left_side[r + cell] = bh;
10760 }
10761 // ...and the mi-EXACT maps the coarse cells alias away, exactly as
10762 // [`decode_leaf_rect`] does (the split arm above records these through
10763 // `record_mi_luma_rect`). Without this an unsplit 32x8 strip left
10764 // `sub8_mode_row` holding the previous block, and the next 32x32's
10765 // strips read a stale `kf_y_mode` row (measured: mi(4,8) on the band
10766 // fixture).
10767 neighbours.record_mode_mi(mi_r, mi_c, mi_w, mi_h, mode);
10768 neighbours.record_uv_mode_mi(mi_r, mi_c, mi_w, mi_h, uv_predict_mode);
10769 let (px, py) = (mi_c * MI, mi_r * MI);
10770 let (cpx, cpy) = (px / 2, py / 2);
10771 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
10772 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
10773 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw > bh {
10774 (&SCAN_32X8, &SCAN_16X4)
10775 } else {
10776 (&SCAN_8X32, &SCAN_4X16)
10777 };
10778 let (luma_levels, u_levels, v_levels) = if skip {
10779 (
10780 vec![0i32; bw * bh],
10781 vec![0i32; chroma_w * chroma_h],
10782 vec![0i32; chroma_w * chroma_h],
10783 )
10784 } else {
10785 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
10786 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
10787 let (luma_levels, luma_tx_type) = read_coeffs_rect(
10788 dec,
10789 &mut luma_coding,
10790 luma_scan,
10791 bw,
10792 bh,
10793 0,
10794 dc_sign_ctx(around[0].2),
10795 TxType::DctDct,
10796 )?;
10797 let mut planes = Vec::with_capacity(2);
10798 for plane in 1..3 {
10799 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
10800 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
10801 let mut coding = cdfs.txb(TxbSet::Chroma8, uv_predict_mode);
10802 let (levels, tx_type) = read_coeffs_rect(
10803 dec,
10804 &mut coding,
10805 chroma_scan,
10806 chroma_w,
10807 chroma_h,
10808 skip_ctx,
10809 dc_sign_ctx(around[plane].2),
10810 default_tx,
10811 )?;
10812 planes.push((levels, tx_type));
10813 }
10814 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
10815 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
10816 RECT4_COEFF_HITS.with(|c| c.set(c.get() + 1));
10817 let luma_residual = dequant_and_inverse_typed_wh(
10818 &luma_levels,
10819 bw,
10820 bh,
10821 crate::decode::bit_depth(fctx),
10822 block_q_idx(fctx),
10823 plane_q_delta(0, fctx).0,
10824 plane_q_delta(0, fctx).1,
10825 luma_tx_type,
10826 );
10827 if let Some(b) = &palette_y_buf {
10828 set_palette_pred(b.clone(), fctx);
10829 }
10830 push_intra_rect(0,
10831 px,
10832 py,
10833 bw,
10834 bh,
10835 mode,
10836 angle_delta_y,
10837 reach,
10838 &luma_residual,
10839 None,
10840 filter_intra,
10841 smooth_neighbor, fctx,
10842 );
10843 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
10844 for (plane, _buf, levels, tx_type) in [
10845 (1usize, &mut *u, &u_levels, u_tx_type),
10846 (2, &mut *v, &v_levels, v_tx_type),
10847 ] {
10848 let residual = dequant_and_inverse_typed_wh(
10849 levels,
10850 chroma_w,
10851 chroma_h,
10852 crate::decode::bit_depth(fctx),
10853 block_q_idx(fctx),
10854 plane_q_delta(plane, fctx).0,
10855 plane_q_delta(plane, fctx).1,
10856 tx_type,
10857 );
10858 if let Some((ub, vb)) = &palette_uv_bufs {
10859 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
10860 }
10861 push_intra_rect(plane,
10862 cpx,
10863 cpy,
10864 chroma_w,
10865 chroma_h,
10866 uv_predict_mode,
10867 angle_delta_uv,
10868 reach,
10869 &residual,
10870 alpha
10871 .zip(ac)
10872 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
10873 None,
10874 smooth_neighbor_uv, fctx,
10875 );
10876 }
10877 neighbours.record_mi_rect(
10878 (mi_r, mi_c),
10879 bw,
10880 bh,
10881 &[luma_levels, u_levels, v_levels],
10882 );
10883 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
10884 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
10885 record_strip_palette(
10886 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
10887 pal_uv_colors,
10888 );
10889 if bw > bh {
10890 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
10891 } else {
10892 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
10893 }
10894 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
10895 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
10896 // frame, so this 1:4 strip -- which is also the INTER frame's reader
10897 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
10898 // transform size in both TXFM_CONTEXT bands. Without it the next block
10899 // reads the row's stale value.
10900 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
10901 return Ok((mode, uv_predict_mode));
10902 };
10903 if let Some(b) = &palette_y_buf {
10904 set_palette_pred(b.clone(), fctx);
10905 }
10906 push_intra_rect(0,
10907 px,
10908 py,
10909 bw,
10910 bh,
10911 mode,
10912 angle_delta_y,
10913 reach,
10914 &luma_levels,
10915 None,
10916 filter_intra,
10917 smooth_neighbor, fctx,
10918 );
10919 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
10920 if let Some((ub, _)) = &palette_uv_bufs {
10921 set_palette_pred(ub.clone(), fctx);
10922 }
10923 push_intra_rect(1,
10924 cpx,
10925 cpy,
10926 chroma_w,
10927 chroma_h,
10928 uv_predict_mode,
10929 angle_delta_uv,
10930 reach,
10931 &u_levels,
10932 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
10933 None,
10934 smooth_neighbor_uv, fctx,
10935 );
10936 if let Some((_, vb)) = &palette_uv_bufs {
10937 set_palette_pred(vb.clone(), fctx);
10938 }
10939 push_intra_rect(2,
10940 cpx,
10941 cpy,
10942 chroma_w,
10943 chroma_h,
10944 uv_predict_mode,
10945 angle_delta_uv,
10946 reach,
10947 &v_levels,
10948 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
10949 None,
10950 smooth_neighbor_uv, fctx,
10951 );
10952 neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[luma_levels.to_vec(), u_levels, v_levels]);
10953 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
10954 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
10955 record_strip_palette(
10956 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
10957 );
10958 if bw > bh {
10959 RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1));
10960 } else {
10961 RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1));
10962 }
10963 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
10964 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
10965 // frame, so this 1:4 strip -- which is also the INTER frame's reader
10966 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
10967 // transform size in both TXFM_CONTEXT bands. Without it the next block
10968 // reads the row's stale value.
10969 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
10970 Ok((mode, uv_predict_mode))
10971}
10972
10973/// Decodes the four 16x4 / 4x16 strips of a 16x16-level `PARTITION_HORZ_4` /
10974/// `PARTITION_VERT_4` (lane-r14) -- [`decode_block_rect4`]'s pair one level
10975/// down, and the first shape here whose luma block is a single mi row (or
10976/// column).
10977///
10978/// What is new at this size is CHROMA. `is_chroma_reference`
10979/// (`av1_common_int.h`) is false for a 4:2:0 block one mi tall (wide) on an
10980/// EVEN mi row (column), so strips 0 and 2 read no `uv_mode`/`cfl_alpha`/
10981/// `angle_delta_uv` at all and code no chroma residual; strips 1 and 3 close
10982/// the pair and carry the chroma of the whole 16x8 (8x16) luma pair --
10983/// `setup_pred_plane`'s own `if (subsampling_y && (mi_row & 1) &&
10984/// mi_size_high[bsize] == 1) mi_row -= 1` offset, i.e. an 8x4 (4x8) chroma
10985/// transform at the PAIR's origin, with CfL averaging over the pair's luma.
10986///
10987/// Tables: LUMA `TX_16X4`/`TX_4X16` averages to the 8x8 entropy context
10988/// ((0 + 2 + 1) >> 1 = 1) with 64 coded positions, so its CDF set is
10989/// [`TxbSet::LumaRect16x4`] (`Luma8`'s tables, the `TX_4X4` `tx_type` row);
10990/// scans are [`SCAN_16X4`]/[`SCAN_4X16`]. CHROMA `TX_8X4`/`TX_4X8` is
10991/// [`TxbSet::ChromaRect8x4`] with [`SCAN_8X4`]/[`SCAN_4X8`]. Angle deltas ARE
10992/// coded (`av1_use_angle_delta` compares the BLOCK_SIZES_ALL enum index, and
10993/// BLOCK_16X4 is 17), and so is `use_filter_intra` (both sides <= 32) off this
10994/// shape's own CDF row.
10995///
10996/// A split transform (`tx_depth != 0`, `sub_tx_size_map[TX_16X4] == TX_8X4`)
10997/// refuses by name rather than guess-decode.
10998#[allow(clippy::too_many_arguments)]
10999fn decode_rect4_16(
11000 dec: &mut SymbolDecoder,
11001 cdfs: &mut Cdfs,
11002 neighbours: &mut Neighbours,
11003 at16: (usize, usize),
11004 horz: bool,
11005 y: &mut PlaneBuf<'static>,
11006 u: &mut PlaneBuf<'static>,
11007 v: &mut PlaneBuf<'static>,
11008 enable_filter_intra: bool,
11009 allow_screen_content_tools: bool,
11010 base_q_idx: u8,
11011 tx_select: bool,
11012 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
11013) -> Result<()> {
11014 let (r, c) = at16;
11015 let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI));
11016 let (bw, bh) = if horz { (16, 4) } else { (4, 16) };
11017 let (_mi_w, _mi_h) = (bw / MI, bh / MI);
11018 let _scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
11019 let _chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
11020 let mut prev: Option<((usize, usize), usize)> = None;
11021 let mut last_mode = DC_PRED;
11022 let mut last_uv_mode = DC_PRED;
11023 for i in 0..4usize {
11024 let lmi = if horz {
11025 (mi_row0 + i, mi_col0)
11026 } else {
11027 (mi_row0, mi_col0 + i)
11028 };
11029 let has_chroma = i % 2 == 1;
11030 let (mode, uv, _tx) = decode_rect4_16_strip(
11031 dec,
11032 cdfs,
11033 neighbours,
11034 lmi,
11035 horz,
11036 has_chroma,
11037 prev,
11038 y,
11039 u,
11040 v,
11041 enable_filter_intra,
11042 allow_screen_content_tools,
11043 base_q_idx,
11044 tx_select,
11045 reduced_tx_set, fctx,
11046 )?;
11047 if let Some(m) = uv {
11048 last_uv_mode = m;
11049 }
11050 last_mode = mode;
11051 prev = Some((lmi, mode));
11052 }
11053 // The coarse 16-px cell holds one entry for the whole 16x16: the last
11054 // strip is what a block below (right) sees through it, the mi-exact maps
11055 // above answering everything finer.
11056 neighbours.above_mode[c] = last_mode;
11057 neighbours.left_mode[r] = last_mode;
11058 neighbours.above_uv_mode[c] = last_uv_mode;
11059 neighbours.left_uv_mode[r] = last_uv_mode;
11060 neighbours.above_side[c] = bw;
11061 neighbours.left_side[r] = bh;
11062 Ok(())
11063}
11064
11065/// One 16x4 / 4x16 strip of a 16x16-level 1:4 partition, intra-coded --
11066/// [`decode_rect4_16`]'s per-strip body, lifted (lane-intra16x4) so the INTER
11067/// block path can decode a SINGLE intra strip of a partition whose other
11068/// strips are inter. `prev` is the previous strip's `(mi, mode)` (the
11069/// key-frame caller's coarse-cell stand-in; `None` on the inter path, where
11070/// every strip publishes its own mi-exact mode). Returns
11071/// `(y_mode, uv_predict_mode when this strip closes the 4:2:0 chroma pair)`.
11072#[allow(clippy::too_many_arguments)]
11073fn decode_rect4_16_strip(
11074 dec: &mut SymbolDecoder,
11075 cdfs: &mut Cdfs,
11076 neighbours: &mut Neighbours,
11077 lmi: (usize, usize),
11078 horz: bool,
11079 has_chroma: bool,
11080 prev: Option<((usize, usize), usize)>,
11081 y: &mut PlaneBuf<'static>,
11082 u: &mut PlaneBuf<'static>,
11083 v: &mut PlaneBuf<'static>,
11084 enable_filter_intra: bool,
11085 allow_screen_content_tools: bool,
11086 base_q_idx: u8,
11087 tx_select: bool,
11088 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
11089) -> Result<(usize, Option<usize>, (usize, usize))> {
11090 let (r, c) = (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI));
11091 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
11092 let (mi_w, mi_h) = (bw / MI, bh / MI);
11093 let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
11094 let chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
11095 let mut last_uv_mode: Option<usize> = None;
11096 // `decode_block_rect4`'s own neighbour rule: the coarse 16-px cell
11097 // aliases all four strips onto one entry, so the mi-exact map wins and
11098 // the previous strip stands in on the split axis.
11099 let mut above_mode = neighbours.above_mode[c];
11100 let mut left_mode = neighbours.left_mode[r];
11101 if let Some(((pr, pc), pmode)) = prev {
11102 if pc == lmi.1 && lmi.0 == pr + mi_h {
11103 above_mode = pmode;
11104 } else if pr == lmi.0 && lmi.1 == pc + mi_w {
11105 left_mode = pmode;
11106 }
11107 }
11108 let (above_mode, left_mode) =
11109 neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode));
11110 // lane-kf900 r4: the strip's real palette ctx + colour cache (see
11111 // [`decode_block_rect4`]); `None`/`&[]` here read `palette_y_mode`
11112 // off CDF row 0 and every cache hit off an empty cache.
11113 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(lmi);
11114 let palette_uv_cache = neighbours.palette_uv_cache_mi(lmi);
11115 let (
11116 skip,
11117 mode,
11118 angle_delta_y,
11119 uv_mode,
11120 angle_delta_uv,
11121 alpha,
11122 filter_intra,
11123 palette_y,
11124 palette_uv,
11125 ) = read_intra_mode_rect(
11126 dec,
11127 cdfs,
11128 above_mode,
11129 left_mode,
11130 true,
11131 has_chroma,
11132 bw,
11133 bh,
11134 enable_filter_intra,
11135 neighbours.skip_txfm_ctx(lmi.0, lmi.1),
11136 allow_screen_content_tools,
11137 Some((palette_ctx, &palette_cache)),
11138 &palette_uv_cache,
11139 lmi.0,
11140 lmi.1, fctx,
11141 )?;
11142 if palette_y.is_some() || palette_uv.is_some() {
11143 RECT4_PALETTE_HITS.with(|h| h.set(h.get() + 1));
11144 }
11145 // The colour-index map through the base colours IS the prediction.
11146 // Chroma's map is the PAIR's 8x4 (4x8) block, matching the one
11147 // chroma transform this closing strip codes.
11148 let palette_y_buf: Option<Vec<u16>> = palette_y
11149 .as_ref()
11150 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
11151 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
11152 (
11153 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
11154 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
11155 )
11156 });
11157 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
11158 if smooth_neighbor {
11159 SMOOTH_LUMA_HITS.with(|h| h.set(h.get() + 1));
11160 }
11161 if filter_intra.is_some() {
11162 FILTER_INTRA_RECT_HITS.with(|h| h.set(h.get() + 1));
11163 }
11164 // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is
11165 // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the
11166 // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol
11167 // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does.
11168 let depth = if tx_select {
11169 // lane-intra16x4: on an INTER frame `get_tx_size_context` reads the
11170 // real `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what
11171 // the 2:1 intra-in-inter strip already does); the key frame's
11172 // deblock-grid approximation is only right where those bands were
11173 // never written.
11174 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
11175 tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx)
11176 } else {
11177 tx_size_context_rect(neighbours, lmi, bw, bh)
11178 };
11179 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
11180 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
11181 eprintln!(
11182 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
11183 lmi.0,
11184 lmi.1,
11185 dec.debug_state().0
11186 );
11187 }
11188 d
11189 } else {
11190 0
11191 };
11192 if depth != 0 {
11193 TX_DEPTH_HITS.with(|h| h.set(h.get() + 1));
11194 RECT4_16_SPLIT_HITS.with(|h| h.set(h.get() + 1));
11195 }
11196 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
11197 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
11198 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
11199 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode);
11200 if depth != 0 {
11201 // [`decode_rect_split`]'s per-unit walk, inlined because the
11202 // CHROMA of this shape belongs to the strip's 4:2:0 pair, not to
11203 // the strip (that function codes one chroma transform per block).
11204 // depth 1 is the 2:1 rect unit TX_8X4/TX_4X8
11205 // (`sub_tx_size_map[TX_16X4]`), depth 2 the square TX_4X4; each
11206 // unit predicts off the units before it in raster order.
11207 let rect_unit = tx_w != tx_h;
11208 let zero_tu = vec![0i32; tx_w * tx_h];
11209 for tu_row in 0..bh / tx_h {
11210 for tu_col in 0..bw / tx_w {
11211 let tu_mi = (lmi.0 + tu_row * (tx_h / MI), lmi.1 + tu_col * (tx_w / MI));
11212 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
11213 let tu_reach = Reach::of_tu(
11214 bw,
11215 bh,
11216 tu_col * tx_w,
11217 tu_row * tx_h,
11218 tx_w,
11219 tx_h,
11220 reach,
11221 );
11222 if let Some(b) = &palette_y_buf {
11223 let tu_buf: Vec<u16> = (0..tx_h)
11224 .flat_map(|i| {
11225 let base = (tu_row * tx_h + i) * bw + tu_col * tx_w;
11226 b[base..base + tx_w].iter().copied()
11227 })
11228 .collect();
11229 set_palette_pred(tu_buf, fctx);
11230 }
11231 if skip {
11232 push_intra_rect(0,
11233 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &zero_tu,
11234 None, filter_intra, smooth_neighbor, fctx,
11235 );
11236 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
11237 } else if rect_unit {
11238 // `get_txsize_entropy_ctx(TX_8X4)` is the 8x8 class with
11239 // 32 coded positions and the `TX_4X4` `tx_type` row:
11240 // exactly [`TxbSet::LumaRect4x8`].
11241 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
11242 let tu_skip_ctx =
11243 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI);
11244 let set = if reduced_tx_set {
11245 TxbSet::LumaRect4x8
11246 } else {
11247 TxbSet::LumaRect4x8Set1
11248 };
11249 let tu_scan: &[u16] = if tx_w > tx_h { &SCAN_8X4 } else { &SCAN_4X8 };
11250 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
11251 let (tu_grid, tu_tx_type) = read_coeffs_rect(
11252 dec,
11253 &mut coding,
11254 tu_scan,
11255 tx_w,
11256 tx_h,
11257 tu_skip_ctx,
11258 dc_sign_ctx(tu_around.2),
11259 TxType::DctDct,
11260 )?;
11261 let residual = dequant_and_inverse_typed_wh(
11262 &tu_grid,
11263 tx_w,
11264 tx_h,
11265 crate::decode::bit_depth(fctx),
11266 block_q_idx(fctx),
11267 plane_q_delta(0, fctx).0,
11268 plane_q_delta(0, fctx).1,
11269 tu_tx_type,
11270 );
11271 push_intra_rect(0,
11272 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &residual,
11273 None, filter_intra, smooth_neighbor, fctx,
11274 );
11275 if tu_grid.iter().any(|&l| l != 0) {
11276 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));
11277 }
11278 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
11279 } else {
11280 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
11281 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
11282 let tu_grid = read_plane(
11283 dec,
11284 cdfs,
11285 txbset_for(tx_w, reduced_tx_set),
11286 default_scan(tx_w),
11287 0,
11288 tu_around,
11289 mode,
11290 mode,
11291 angle_delta_y,
11292 tu_reach,
11293 y,
11294 tu_px,
11295 tu_py,
11296 tx_w,
11297 tx_w,
11298 base_q_idx,
11299 None,
11300 filter_intra,
11301 Some(tu_skip_ctx),
11302 smooth_neighbor, fctx,
11303 )?;
11304 if tu_grid.iter().any(|&l| l != 0) {
11305 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));
11306 }
11307 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
11308 }
11309 }
11310 }
11311 } else {
11312 let levels = if skip {
11313 let zeros = vec![0i32; bw * bh];
11314 if let Some(b) = &palette_y_buf {
11315 set_palette_pred(b.clone(), fctx);
11316 }
11317 push_intra_rect(0,
11318 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
11319 smooth_neighbor, fctx,
11320 );
11321 zeros
11322 } else {
11323 // The strip's luma TU *is* the strip (`plane_bsize ==
11324 // txsize_to_bsize[tx_size]`), so `get_txb_ctx` fixes
11325 // `txb_skip_ctx` at 0.
11326 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
11327 let set = if reduced_tx_set {
11328 TxbSet::LumaRect16x4
11329 } else {
11330 TxbSet::LumaRect16x4Set1
11331 };
11332 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
11333 let (levels, tx_type) = read_coeffs_rect(
11334 dec,
11335 &mut coding,
11336 scan,
11337 bw,
11338 bh,
11339 0,
11340 dc_sign_ctx(around.2),
11341 TxType::DctDct,
11342 )?;
11343 let residual = dequant_and_inverse_typed_wh(
11344 &levels,
11345 bw,
11346 bh,
11347 crate::decode::bit_depth(fctx),
11348 block_q_idx(fctx),
11349 plane_q_delta(0, fctx).0,
11350 plane_q_delta(0, fctx).1,
11351 tx_type,
11352 );
11353 if let Some(b) = &palette_y_buf {
11354 set_palette_pred(b.clone(), fctx);
11355 }
11356 push_intra_rect(0,
11357 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
11358 smooth_neighbor, fctx,
11359 );
11360 RECT4_16_COEFF_HITS.with(|h| h.set(h.get() + 1));
11361 levels
11362 };
11363 neighbours.record_mi_luma_rect(lmi, bw, bh, &levels);
11364 }
11365 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
11366 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
11367 // `update_partition_context` writes `partition_context_lookup[
11368 // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on
11369 // the left (mirrored under VERT_4).
11370 for cell in 0..mi_w {
11371 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
11372 *slot = bw;
11373 }
11374 }
11375 for cell in 0..mi_h {
11376 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
11377 *slot = bh;
11378 }
11379 }
11380 if has_chroma {
11381 RECT4_16_CHROMA_HITS.with(|h| h.set(h.get() + 1));
11382 let pair_mi = if horz {
11383 (lmi.0 - 1, lmi.1)
11384 } else {
11385 (lmi.0, lmi.1 - 1)
11386 };
11387 let (pw, ph) = if horz { (16, 8) } else { (8, 16) };
11388 let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI);
11389 let (cpx, cpy) = (ppx / 2, ppy / 2);
11390 let (cw, ch) = (pw / 2, ph / 2);
11391 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
11392 if (V_PRED..=D67_PRED).contains(&uv_predict_mode) {
11393 RECT4_16_CHROMA_DIR_HITS.with(|h| h.set(h.get() + 1));
11394 }
11395 let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height, fctx);
11396 // lane-kf1200 r1: the chroma edge-filter type reads the neighbours
11397 // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s
11398 // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/
11399 // `chroma_left_mbmi` from `mi[-((mi_row & ss_y) * stride + (mi_col
11400 // & ss_x))]` (`set_mi_offsets`, av1/common/blockd.h ~1050), i.e.
11401 // the pair's top-left luma mi, never this leaf's odd row/column.
11402 // Reading `lmi` here named the leaf directly above (a non-chroma
11403 // -reference 4-row block, `uv_mode == UV_DC_PRED`) and so lost a
11404 // SMOOTH neighbour: filt_type 0 instead of 1 turned
11405 // `av1_use_intra_edge_upsample` on (blk_wh 12 <= 16) for a
11406 // directional chroma strip, moving 4 samples by 1.
11407 let smooth_neighbor_uv =
11408 neighbours.smooth_uv_neighbour(pair_mi.0, pair_mi.1, r, c);
11409 if smooth_neighbor_uv != neighbours.smooth_uv_neighbour_unsnapped(lmi.0, lmi.1, r, c)
11410 {
11411 RECT4_16_UV_PAIR_FILT_HITS.with(|h| h.set(h.get() + 1));
11412 }
11413 let (u_levels, v_levels) = if skip {
11414 let zeros = vec![0i32; cw * ch];
11415 // libaom `predict_and_reconstruct_intra_block` (decodeframe.c
11416 // ~1000) predicts EVERY plane and only guards the residual on
11417 // `mbmi->skip_txfm`, so a skipped `UV_CFL_PRED` block is still
11418 // DC + alpha * luma-AC. Dropping the CfL term here left a
11419 // chroma-only bounded box on ReelC's key frames.
11420 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
11421 if alpha.is_some() {
11422 CHROMA_SKIP_CFL_HITS.with(|h| h.set(h.get() + 1));
11423 }
11424 for (_buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] {
11425 if let Some((ub, vb)) = &palette_uv_bufs {
11426 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
11427 }
11428 push_intra_rect(plane,
11429 cpx,
11430 cpy,
11431 cw,
11432 ch,
11433 uv_predict_mode,
11434 angle_delta_uv,
11435 pair_reach,
11436 &zeros,
11437 alpha
11438 .zip(ac)
11439 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
11440 None,
11441 smooth_neighbor_uv, fctx,
11442 );
11443 }
11444 (zeros.clone(), zeros)
11445 } else {
11446 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
11447 let mut planes = Vec::with_capacity(2);
11448 for plane in 1..3 {
11449 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
11450 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
11451 let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
11452 let (levels, tx_type) = read_coeffs_rect(
11453 dec,
11454 &mut coding,
11455 chroma_scan,
11456 cw,
11457 ch,
11458 skip_ctx,
11459 dc_sign_ctx(around[plane].2),
11460 default_tx,
11461 )?;
11462 planes.push((levels, tx_type));
11463 }
11464 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
11465 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
11466 // CfL averages the luma of the WHOLE pair, the region this one
11467 // chroma transform covers.
11468 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
11469 for (plane, _buf, levels, tx_type) in [
11470 (1usize, &mut *u, &u_levels, u_tx_type),
11471 (2, &mut *v, &v_levels, v_tx_type),
11472 ] {
11473 let residual = dequant_and_inverse_typed_wh(
11474 levels,
11475 cw,
11476 ch,
11477 crate::decode::bit_depth(fctx),
11478 block_q_idx(fctx),
11479 plane_q_delta(plane, fctx).0,
11480 plane_q_delta(plane, fctx).1,
11481 tx_type,
11482 );
11483 if let Some((ub, vb)) = &palette_uv_bufs {
11484 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
11485 }
11486 push_intra_rect(plane,
11487 cpx,
11488 cpy,
11489 cw,
11490 ch,
11491 uv_predict_mode,
11492 angle_delta_uv,
11493 pair_reach,
11494 &residual,
11495 alpha
11496 .zip(ac)
11497 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
11498 None,
11499 smooth_neighbor_uv, fctx,
11500 );
11501 }
11502 (u_levels, v_levels)
11503 };
11504 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, uv_predict_mode);
11505 // The chroma planes' coefficient context, over the PAIR's mi span
11506 // (`decode_leaf_rect8`'s own rule: a subsampled plane's bound is
11507 // the luma one rounded up to its 4x4 unit).
11508 let u_state = neighbour_state(&u_levels);
11509 let v_state = neighbour_state(&v_levels);
11510 let round_up_even = |n: usize| n.div_ceil(2) * 2;
11511 let bound_h = round_up_even(neighbours.mi_rows);
11512 let bound_w = round_up_even(neighbours.mi_cols);
11513 for cell in 0..(ph / MI) {
11514 if pair_mi.0 + cell < bound_h
11515 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
11516 {
11517 slot[1] = u_state;
11518 slot[2] = v_state;
11519 }
11520 }
11521 for cell in 0..(pw / MI) {
11522 if pair_mi.1 + cell < bound_w
11523 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
11524 {
11525 slot[1] = u_state;
11526 slot[2] = v_state;
11527 }
11528 }
11529 last_uv_mode = Some(uv_predict_mode);
11530 }
11531 if horz {
11532 RECT4_16_HORZ_HITS.with(|h| h.set(h.get() + 1));
11533 } else {
11534 RECT4_16_VERT_HITS.with(|h| h.set(h.get() + 1));
11535 }
11536 let (pal_y_size, pal_y_colors) =
11537 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
11538 let (pal_uv_size, pal_uv_colors) =
11539 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
11540 record_strip_palette(
11541 neighbours, lmi, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
11542 );
11543 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
11544 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
11545 // frame): the above row records `tx_size_wide` over the block's width and
11546 // the left column `tx_size_high` over its height. This 1:4 strip reader is
11547 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
11548 // and it published neither band -- so the block after a 64x16 strip read
11549 // the row's init value 64 as its left transform height and took
11550 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
11551 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
11552 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
11553 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
11554 Ok((mode, last_uv_mode, (tx_w, tx_h)))
11555}
11556
11557
11558/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
11559/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
11560/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
11561/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
11562/// cap, so LUMA needs the same corner truncation [`decode_block`] already
11563/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
11564/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
11565/// this function's own charter/report), so both strips read a real 32x32
11566/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
11567/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
11568/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
11569/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
11570/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
11571/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
11572/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
11573/// that function, only the single-transform-unit (`tx_depth == 0`) case is
11574/// supported: a split transform refuses by name rather than guess-decode.
11575#[allow(clippy::too_many_arguments)]
11576fn decode_block_rect64(
11577 dec: &mut SymbolDecoder,
11578 cdfs: &mut Cdfs,
11579 neighbours: &mut Neighbours,
11580 at: (usize, usize),
11581 bw: usize,
11582 bh: usize,
11583 y: &mut PlaneBuf<'static>,
11584 u: &mut PlaneBuf<'static>,
11585 v: &mut PlaneBuf<'static>,
11586 enable_filter_intra: bool,
11587 allow_screen_content_tools: bool,
11588 base_q_idx: u8,
11589 tx_select: bool,
11590 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
11591) -> Result<()> {
11592 let (r, c) = at;
11593 let (px, py) = (c * SUB, r * SUB);
11594 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
11595 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
11596 let palette_uv_cache = neighbours.palette_uv_cache(at);
11597 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
11598 read_intra_mode_rect(
11599 dec,
11600 cdfs,
11601 nb_above_mode,
11602 nb_left_mode,
11603 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
11604 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
11605 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
11606 // correct), CFL must never be offered here -- passing `true`
11607 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
11608 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
11609 // from this block's very first symbol (lane-sbpart r3 bisect).
11610 false,
11611 true,
11612 bw,
11613 bh,
11614 enable_filter_intra,
11615 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
11616 allow_screen_content_tools,
11617 Some((palette_ctx, &palette_cache)),
11618 &palette_uv_cache,
11619 r * (SUB / MI),
11620 c * (SUB / MI), fctx,
11621 )?;
11622 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
11623 // lane-t900 r34: a non-skip palette block on a superblock-level strip
11624 // -- counted so its gate cannot go vacuous (this was a refusal until
11625 // r34; see the gate `a_real_aomenc_palette_stream_with_8x8_leaves_
11626 // decodes_pixel_exact`).
11627 PALETTE_SB_STRIP_HITS.with(|c| c.set(c.get() + 1));
11628 }
11629 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
11630 if smooth_neighbor {
11631 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
11632 }
11633 let smooth_neighbor_uv =
11634 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
11635 if filter_intra.is_some() {
11636 // `filter_intra_size_class_rect` already returns `None` for both
11637 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
11638 // 32 on both axes), so this symbol is never read at this level --
11639 // kept only as the same defensive refusal [`decode_block_rect`] has.
11640 return Err(unsupported(
11641 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
11642 av1_filter_intra_allowed_bsize caps at 32x32)",
11643 ));
11644 }
11645 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
11646 DC_PRED
11647 } else {
11648 uv_mode
11649 };
11650 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
11651 let depth = if tx_select {
11652 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
11653 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
11654 // the 16x4 intra-in-inter strips already do); the key frame's
11655 // deblock-grid approximation is only right where those bands were never
11656 // written. Measured on the 10-bit 1920x792 128-superblock stream,
11657 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
11658 // `tx_size_cat2` row 1 where libaom reads row 2.
11659 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
11660 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
11661 } else {
11662 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
11663 };
11664 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
11665 // counts `sub_tx_size_map` steps from the block's own max rect
11666 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
11667 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
11668 // steps, so this level's category is 3 (the same one a 64x64 square
11669 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
11670 // here was a wrong-table read of a real symbol.
11671 let d = dec.symbol(&mut cdfs.tx_size_cat3[ctx]);
11672 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
11673 eprintln!(
11674 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=3 rng={}",
11675 dec.debug_state().0
11676 );
11677 }
11678 d
11679 } else {
11680 0
11681 };
11682 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
11683 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
11684 publish_txfm_bands_if_in_inter(
11685 neighbours,
11686 (mi_r, mi_c),
11687 depth_to_tx_wh(bw, bh, depth),
11688 (bw, bh), fctx,
11689 );
11690 if depth != 0 {
11691 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
11692 // lane-rectsplit r1/r4: the superblock-level strip splits its
11693 // transform through the very same per-unit path as its 32x32-level
11694 // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64
11695 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
11696 // measured the old square formula mis-tiling exactly that strip).
11697 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth);
11698 if bw.max(bh) / bw.min(bh) == 4 {
11699 let which = if depth == 1 {
11700 &RECT4_SPLIT_DEPTH1_HITS
11701 } else {
11702 &RECT4_SPLIT_DEPTH2_HITS
11703 };
11704 which.with(|c| c.set(c.get() + 1));
11705 }
11706 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
11707 eprintln!(
11708 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
11709 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
11710 angle_y={angle_delta_y}"
11711 );
11712 }
11713 let modes = RectStripModes {
11714 skip,
11715 mode,
11716 angle_delta_y,
11717 uv_predict_mode,
11718 angle_delta_uv,
11719 alpha,
11720 filter_intra,
11721 smooth_neighbor,
11722 smooth_neighbor_uv,
11723 palette_y: palette_y
11724 .as_ref()
11725 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
11726 palette_uv: palette_uv.as_ref().map(|p| {
11727 (
11728 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
11729 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
11730 )
11731 }),
11732 };
11733 if palette_y.is_some() || palette_uv.is_some() {
11734 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
11735 }
11736 decode_rect_split(
11737 dec,
11738 cdfs,
11739 neighbours,
11740 (mi_r, mi_c),
11741 bw,
11742 bh,
11743 tx_w,
11744 tx_h,
11745 &modes,
11746 y,
11747 u,
11748 v,
11749 base_q_idx,
11750 reduced_tx_set, fctx,
11751 )?;
11752 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
11753 // (lane-palette2 r10): this return skips the fn's own tail, so a
11754 // split-tx superblock strip would otherwise leave the above/left
11755 // palette arrays holding a dead block's colours.
11756 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
11757 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
11758 let (puv_size, puv_colors) =
11759 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
11760 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
11761 // lane-frame36 r2: `set_txfm_ctxs` runs for EVERY block and this early
11762 // return skips the fn's own tail, so a SPLIT superblock-level strip
11763 // published no TXFM_CONTEXT band and the next block read the row's init
11764 // value 64 as its left transform height. Measured on the 10-bit
11765 // 3840x1608 stream, decode-order frame 33: after the split 16x64 strip
11766 // at mi(192,140) (`tx_depth=1` -> TX_16X32) the 32x64 block at
11767 // mi(192,144) took `tx_size_cat3` row 2 where libaom takes row 1. The
11768 // bands carry the SPLIT unit's size, not the block's.
11769 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
11770 RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.set(c.get() + 1));
11771 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
11772 return Ok(());
11773 }
11774 let (tx_w, tx_h) = (bw, bh);
11775 let (cpx, cpy) = (px / 2, py / 2);
11776 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
11777 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
11778 if let Some(ref pyv) = palette_y {
11779 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
11780 set_palette_pred(buf, fctx);
11781 }
11782 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
11783 (
11784 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
11785 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
11786 )
11787 });
11788 if skip {
11789 push_intra_rect(0,
11790 px,
11791 py,
11792 bw,
11793 bh,
11794 mode,
11795 angle_delta_y,
11796 reach,
11797 &vec![0i32; bw * bh],
11798 None,
11799 filter_intra,
11800 smooth_neighbor, fctx,
11801 );
11802 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
11803 if let Some((ub, _)) = &palette_uv_bufs {
11804 set_palette_pred(ub.clone(), fctx);
11805 }
11806 push_intra_rect(1,
11807 cpx,
11808 cpy,
11809 chroma_w,
11810 chroma_h,
11811 uv_predict_mode,
11812 angle_delta_uv,
11813 reach,
11814 &vec![0i32; chroma_w * chroma_h],
11815 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
11816 None,
11817 smooth_neighbor_uv, fctx,
11818 );
11819 if let Some((_, vb)) = &palette_uv_bufs {
11820 set_palette_pred(vb.clone(), fctx);
11821 }
11822 push_intra_rect(2,
11823 cpx,
11824 cpy,
11825 chroma_w,
11826 chroma_h,
11827 uv_predict_mode,
11828 angle_delta_uv,
11829 reach,
11830 &vec![0i32; chroma_w * chroma_h],
11831 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
11832 None,
11833 smooth_neighbor_uv, fctx,
11834 );
11835 neighbours.record_rect(
11836 at,
11837 bw,
11838 bh,
11839 mode,
11840 uv_predict_mode,
11841 &[
11842 vec![0i32; bw * bh],
11843 vec![0i32; chroma_w * chroma_h],
11844 vec![0i32; chroma_w * chroma_h],
11845 ],
11846 );
11847 } else {
11848 let around = neighbours.around_rect(at, bw, bh);
11849 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
11850 // (see this function's own doc comment). A 64-length axis codes only
11851 // its low 32 coefficients, so the corner is `min(bw, 32)` x
11852 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
11853 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
11854 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
11855 let scan32 = default_scan(TX32);
11856 if coeff_trace_on() {
11857 let (rng, _) = dec.debug_state();
11858 eprintln!("EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}");
11859 }
11860 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
11861 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
11862 read_coeffs(
11863 dec,
11864 &mut luma_coding,
11865 &scan32,
11866 0,
11867 dc_sign_ctx(around[0].2),
11868 TxType::DctDct,
11869 Some((bw, bh)),
11870 )?
11871 } else {
11872 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
11873 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
11874 // (`scan.c`) gives both the very same `default_scan_32x16` /
11875 // `default_scan_16x32` the 2:1 sizes use ("Half of the
11876 // coefficients of tx64 at higher frequencies are set to zeros. So
11877 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
11878 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
11879 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
11880 // 512-position eob group) -- BOTH identical to TX_32X16, so the
11881 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
11882 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
11883 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
11884 // what `base_ctx_rect` computes at (32, 16).
11885 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
11886 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
11887 read_coeffs_rect(
11888 dec,
11889 &mut luma_coding,
11890 luma_scan,
11891 luma_cw,
11892 luma_ch,
11893 0,
11894 dc_sign_ctx(around[0].2),
11895 TxType::DctDct,
11896 )?
11897 };
11898 if coeff_trace_on() {
11899 let (rng, _) = dec.debug_state();
11900 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
11901 }
11902 let mut luma_levels = vec![0i32; bw * bh];
11903 for row in 0..luma_ch {
11904 luma_levels[row * bw..][..luma_cw]
11905 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
11906 }
11907 {
11908 let cur = block_q_idx(fctx);
11909 if cur != i32::from(base_q_idx) {
11910 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
11911 }
11912 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11913 eprintln!(
11914 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
11915 );
11916 }
11917 }
11918 let luma_residual = dequant_and_inverse_typed_wh(
11919 &luma_levels,
11920 bw,
11921 bh,
11922 crate::decode::bit_depth(fctx),
11923 block_q_idx(fctx),
11924 plane_q_delta(0, fctx).0,
11925 plane_q_delta(0, fctx).1,
11926 luma_tx_type,
11927 );
11928 push_intra_rect(0,
11929 px,
11930 py,
11931 bw,
11932 bh,
11933 mode,
11934 angle_delta_y,
11935 reach,
11936 &luma_residual,
11937 None,
11938 filter_intra,
11939 smooth_neighbor, fctx,
11940 );
11941 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
11942 let leftcol: Vec<u16> = if px > 0 {
11943 (py..py + bh).map(|row| y.data[row * y.width + px - 1]).collect()
11944 } else {
11945 vec![]
11946 };
11947 eprintln!(
11948 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
11949 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
11950 luma_corner.iter().any(|&v| v != 0),
11951 &y.data[py * y.width + px..][..bw],
11952 leftcol,
11953 );
11954 }
11955 // CHROMA: a real, untruncated chroma_w x chroma_h transform -- no
11956 // corner crop needed (see doc comment).
11957 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
11958 // The chroma plane is never truncated (both axes <= 32 after
11959 // subsampling). Under a 1:4 strip it is a true 32x8/8x32:
11960 // `get_txsize_entropy_ctx(TX_32X8)` = (TX_8X8 + TX_32X32 + 1) >> 1 =
11961 // TX_16X16 and `txsize_log2_minus4[TX_32X8]` = 4 (256 positions),
11962 // both identical to TX_16X16 -- so [`TxbSet::Chroma16`] is the exact
11963 // set, and only the scan is new (lane-tx64x16).
11964 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (bw, bh) {
11965 (64, 16) => (TxbSet::Chroma16, &SCAN_32X8),
11966 (16, 64) => (TxbSet::Chroma16, &SCAN_8X32),
11967 (64, _) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
11968 _ => (TxbSet::ChromaRect32x16, &SCAN_16X32),
11969 };
11970 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
11971 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
11972 if coeff_trace_on() {
11973 let (rng, _) = dec.debug_state();
11974 eprintln!("EC_COEFF plane=1 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
11975 }
11976 let (u_levels, u_tx_type) = read_coeffs_rect(
11977 dec,
11978 &mut u_coding,
11979 chroma_scan,
11980 chroma_w,
11981 chroma_h,
11982 u_skip_ctx,
11983 dc_sign_ctx(around[1].2),
11984 TxType::DctDct,
11985 )?;
11986 if coeff_trace_on() {
11987 let (rng, _) = dec.debug_state();
11988 eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}");
11989 }
11990 {
11991 let cur = block_q_idx(fctx);
11992 if cur != i32::from(base_q_idx) {
11993 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
11994 }
11995 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11996 eprintln!(
11997 "TRACE rect64_dequant plane=1 base_q_idx={base_q_idx} current_q_idx={cur}"
11998 );
11999 }
12000 }
12001 let u_residual = dequant_and_inverse_typed_wh(
12002 &u_levels,
12003 chroma_w,
12004 chroma_h,
12005 crate::decode::bit_depth(fctx),
12006 block_q_idx(fctx),
12007 plane_q_delta(1, fctx).0,
12008 plane_q_delta(1, fctx).1,
12009 u_tx_type,
12010 );
12011 // lane-t900 r34: the UV-palette prediction override, exactly as the
12012 // `skip` arm above installs it. The [`PALETTE_PRED`] slot is a
12013 // set-then-take, so it must be filled again right before each plane's
12014 // own reconstruct; leaving this out of the non-skip arm predicted a
12015 // palette block's chroma off its block edges (measured: testsrc2
12016 // 128x128 10-bit cq55 `--tile-columns=1`, the 32x64 strip at px=96 --
12017 // luma exact, both chroma planes wrong over its whole 16x32).
12018 if let Some((ub, _)) = &palette_uv_bufs {
12019 set_palette_pred(ub.clone(), fctx);
12020 }
12021 push_intra_rect(1,
12022 cpx,
12023 cpy,
12024 chroma_w,
12025 chroma_h,
12026 uv_predict_mode,
12027 angle_delta_uv,
12028 reach,
12029 &u_residual,
12030 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
12031 None,
12032 smooth_neighbor_uv, fctx,
12033 );
12034 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
12035 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
12036 if coeff_trace_on() {
12037 let (rng, _) = dec.debug_state();
12038 eprintln!("EC_COEFF plane=2 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
12039 }
12040 let (v_levels, v_tx_type) = read_coeffs_rect(
12041 dec,
12042 &mut v_coding,
12043 chroma_scan,
12044 chroma_w,
12045 chroma_h,
12046 v_skip_ctx,
12047 dc_sign_ctx(around[2].2),
12048 TxType::DctDct,
12049 )?;
12050 if coeff_trace_on() {
12051 let (rng, _) = dec.debug_state();
12052 eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}");
12053 }
12054 {
12055 let cur = block_q_idx(fctx);
12056 if cur != i32::from(base_q_idx) {
12057 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
12058 }
12059 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12060 eprintln!(
12061 "TRACE rect64_dequant plane=2 base_q_idx={base_q_idx} current_q_idx={cur}"
12062 );
12063 }
12064 }
12065 let v_residual = dequant_and_inverse_typed_wh(
12066 &v_levels,
12067 chroma_w,
12068 chroma_h,
12069 crate::decode::bit_depth(fctx),
12070 block_q_idx(fctx),
12071 plane_q_delta(2, fctx).0,
12072 plane_q_delta(2, fctx).1,
12073 v_tx_type,
12074 );
12075 if let Some((_, vb)) = &palette_uv_bufs {
12076 set_palette_pred(vb.clone(), fctx);
12077 }
12078 push_intra_rect(2,
12079 cpx,
12080 cpy,
12081 chroma_w,
12082 chroma_h,
12083 uv_predict_mode,
12084 angle_delta_uv,
12085 reach,
12086 &v_residual,
12087 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
12088 None,
12089 smooth_neighbor_uv, fctx,
12090 );
12091 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
12092 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
12093 }
12094 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12095 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
12096 let (puv_size, puv_colors) =
12097 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12098 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
12099 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
12100 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
12101 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
12102 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
12103 // frame): the above row records `tx_size_wide` over the block's width and
12104 // the left column `tx_size_high` over its height. This 1:4 strip reader is
12105 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
12106 // and it published neither band -- so the block after a 64x16 strip read
12107 // the row's init value 64 as its left transform height and took
12108 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
12109 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
12110 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
12111 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
12112 SB_RECT_HITS.with(|c| c.set(c.get() + 1));
12113 match (bw, bh) {
12114 (64, 16) => SB_RECT4_HORZ_HITS.with(|c| c.set(c.get() + 1)),
12115 (16, 64) => SB_RECT4_VERT_HITS.with(|c| c.set(c.get() + 1)),
12116 _ => {}
12117 }
12118 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12119 let (rng, _) = dec.debug_state();
12120 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
12121 }
12122 Ok(())
12123}
12124
12125/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
12126/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
12127/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
12128/// it lands away from zero, for gate tests to prove a real stream fired one.
12129fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
12130 let symbol = dec.symbol(cdf);
12131 if symbol != ANGLE_DELTA_ZERO {
12132 ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
12133 }
12134 symbol as i32 - ANGLE_DELTA_ZERO as i32
12135}
12136
12137#[allow(clippy::too_many_arguments)]
12138fn read_intra_mode(
12139 dec: &mut SymbolDecoder,
12140 cdfs: &mut Cdfs,
12141 above_mode: usize,
12142 left_mode: usize,
12143 cfl: bool,
12144 side: usize,
12145 enable_filter_intra: bool,
12146 skip_ctx: usize,
12147 allow_screen_content_tools: bool,
12148 allow_intrabc: bool,
12149 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
12150 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
12151 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
12152 // `None` at the excluded call sites (the 8x8-leaf path), which still read
12153 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
12154 // decoder reads either way -- but refuse by name the moment it fires,
12155 // exactly the old behaviour.
12156 palette: Option<(usize, &[u16])>,
12157 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
12158 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
12159 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
12160 // `use_palette_y`, not a neighbour lookup).
12161 palette_uv_cache: &[u16],
12162 mi_r: usize,
12163 mi_c: usize, fctx: &crate::decode::FrameCtx,
12164) -> Result<(
12165 bool,
12166 usize,
12167 i32,
12168 usize,
12169 i32,
12170 Option<(i32, i32)>,
12171 Option<usize>,
12172 Option<PaletteY>,
12173 Option<PaletteUv>,
12174)> {
12175 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
12176 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
12177 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
12178 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
12179 // line against the instrumented aomdec, not just `tell()`.
12180 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
12181 if ec_istep {
12182 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
12183 // (decodemv.c:818), printed at the same point: before the first
12184 // mode-info symbol of the block, so a cross-decoder range ladder can
12185 // be keyed on the BLOCK, not just on the symbol sequence.
12186 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}", dec.debug_state().0);
12187 }
12188 macro_rules! istep {
12189 ($name:literal, $val:expr) => {
12190 if ec_istep {
12191 let (rng, _) = dec.debug_state();
12192 eprintln!(
12193 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
12194 $name, $val
12195 );
12196 }
12197 };
12198 }
12199 // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single
12200 // point every square caller routes through (see `read_intra_mode_rect`).
12201 let cfl = if cfl && side > 32 {
12202 NOCFL_UV_MODE_HITS.with(|c| c.set(c.get() + 1));
12203 false
12204 } else {
12205 cfl
12206 };
12207 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
12208 // `skip` when `SegIdPreSkip`, and after it otherwise.
12209 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
12210 if seg_id_pre_skip(fctx) {
12211 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
12212 }
12213 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
12214 if trace {
12215 eprintln!("TRACE skip value={} rng={}", skip as i32, dec.debug_state().0);
12216 }
12217 istep!("skip", skip as i32);
12218 if !seg_id_pre_skip(fctx) {
12219 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
12220 }
12221 // spec order (see the comment below on `read_intrabc_info`): `skip`,
12222 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
12223 maybe_read_cdef_idx(dec, mi_r, mi_c, skip, fctx);
12224 istep!("cdef", 0);
12225 // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not
12226 // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole
12227 // superblock and skips `delta_q` exactly like a 64 one under a 64 root.
12228 let whole_sb = side == sb_mi_cur(fctx) as usize * 4;
12229 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
12230 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
12231 istep!("dq", 0);
12232 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
12233 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
12234 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
12235 // intra frame whose header set `allow_intrabc`. Actual intra block copy
12236 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
12237 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
12238 // draws the line at consuming this one flag symbol and refusing by name
12239 // when it fires, so the arithmetic decoder still resyncs for a stream
12240 // that merely allows (but never uses) intrabc.
12241 if allow_intrabc {
12242 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
12243 if trace {
12244 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
12245 }
12246 if use_intrabc {
12247 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, side, fctx);
12248 if trace {
12249 eprintln!("TRACE intrabc dv={dv:?}");
12250 }
12251 fctx.intrabc_dv.with(|c| c.set(Some(dv)));
12252 INTRABC_HITS.with(|c| c.set(c.get() + 1));
12253 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
12254 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
12255 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
12256 // `DC_PRED` (which is also what the neighbour mode contexts and
12257 // the loop filter then see).
12258 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
12259 }
12260 }
12261 let above_ctx = INTRA_MODE_CTX[above_mode];
12262 let left_ctx = INTRA_MODE_CTX[left_mode];
12263 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
12264 if trace {
12265 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
12266 }
12267 istep!("mode", mode as i32);
12268 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
12269 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
12270 if trace {
12271 eprintln!(
12272 "TRACE angle_delta value={}",
12273 delta + ANGLE_DELTA_ZERO as i32
12274 );
12275 }
12276 delta
12277 } else {
12278 0
12279 };
12280 istep!("angle_y", angle_delta_y);
12281 // lane-sb128c r3 (class sweep): `is_cfl_allowed` on the luma bsize, decided
12282 // here so every `decode_block` caller (64x64 and 128x128 roots included)
12283 // picks the right alphabet -- see [`read_intra_mode_rect`]'s twin.
12284 let cfl = cfl && side <= 32;
12285 let uv_mode = if cfl {
12286 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
12287 } else {
12288 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
12289 };
12290 if trace {
12291 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}", dec.debug_state().0);
12292 }
12293 istep!("uv_mode", uv_mode as i32);
12294 let alpha = if cfl && uv_mode == UV_CFL_PRED {
12295 Some(read_cfl_alphas(dec, cdfs))
12296 } else {
12297 None
12298 };
12299 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
12300 // from this lane's directional chroma: a corner block with neither
12301 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
12302 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
12303 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
12304 // bug in that fallback this lane's own scope does not cover. Keep it
12305 // refused here rather than ship a silently-wrong decode.
12306 if (9..=12).contains(&uv_mode) {
12307 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
12308 }
12309 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
12310 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
12311 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
12312 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
12313 // the `else` branch below and never reads one either way.
12314 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
12315 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
12316 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
12317 } else {
12318 0
12319 };
12320 istep!("angle_uv", angle_delta_uv);
12321 if angle_delta_uv != 0 {
12322 UV_ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
12323 }
12324 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
12325 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
12326 // gated by `av1_allow_palette` (blockd.h -- size bound only,
12327 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
12328 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
12329 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
12330 // read the same CDF row whenever every neighbour really is non-palette).
12331 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
12332 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
12333 // neighbour lookup at all), so it is exact even at the excluded call
12334 // sites once Y decodes real syntax there too.
12335 //
12336 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
12337 // inline from `read_palette_mode_info` -- it runs later, from
12338 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
12339 // after the WHOLE mode-info read for the block, including UV palette
12340 // mode_info (`read_palette_mode_info`'s own second half, right below)
12341 // and `read_filter_intra_mode_info`. So this branch now only reads
12342 // mode/size/colours for both planes (deferring the two colour-index-map
12343 // decodes to after `filter_intra`, below) -- r6's range trace pinned
12344 // this exact ordering bug (`compare-range-not-tell`: ranges matched
12345 // bit-for-bit through the Y colours, diverged only at the old inline
12346 // `decode_color_index_map` call).
12347 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
12348 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
12349 if allow_screen_content_tools
12350 && let Some(bsize_ctx) = palette_bsize_ctx(side)
12351 {
12352 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
12353 if mode == DC_PRED {
12354 if trace {
12355 let (rng, _) = dec.debug_state();
12356 eprintln!(
12357 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
12358 );
12359 }
12360 }
12361 let use_palette_y =
12362 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
12363 if mode == DC_PRED && trace {
12364 let (rng, _) = dec.debug_state();
12365 eprintln!("TRACE palette_y_mode value={} rng={rng}", use_palette_y as i32);
12366 }
12367 if use_palette_y {
12368 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
12369 if trace {
12370 let (rng, _) = dec.debug_state();
12371 eprintln!("TRACE palette_y_size n={n} rng={rng}");
12372 }
12373 let colors = read_palette_colors_y(dec, n, cache, fctx);
12374 if trace {
12375 let (rng, _) = dec.debug_state();
12376 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
12377 }
12378 palette_y_pending = Some((n, colors));
12379 }
12380 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
12381 // unconditionally at this bit position whenever `uv_mode ==
12382 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
12383 // scope always reconstructs chroma alongside luma (`decode_block`
12384 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
12385 // is always true here and does not need threading in.
12386 let palette_uv_mode_ctx = usize::from(use_palette_y);
12387 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
12388 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
12389 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
12390 palette_uv_pending = Some((n, u_colors, v_colors));
12391 }
12392 }
12393 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
12394 // `use_filter_intra` symbol this decoder never read at all until
12395 // lane-av1real r10 -- silently skipping it left every bit past a
12396 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
12397 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
12398 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
12399 // symbol's bits were never consumed).
12400 let mut filter_intra = None;
12401 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
12402 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
12403 // `use_filter_intra` symbol for a Y-palette block, and reading one here
12404 // desynced every screen-content stream from the first palette block on
12405 // (it surfaced as a bogus "partition below 8x8" refusal further down the
12406 // tile).
12407 if mode == DC_PRED
12408 && enable_filter_intra
12409 && palette_y_pending.is_none()
12410 && let Some(class) = filter_intra_size_class(side)
12411 {
12412 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
12413 if trace {
12414 eprintln!(
12415 "TRACE use_filter_intra side={side} rng={} value={}", dec.debug_state().0,
12416 use_filter_intra as i32
12417 );
12418 }
12419 istep!("use_filter_intra", use_filter_intra as i32);
12420 if use_filter_intra {
12421 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
12422 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
12423 if trace {
12424 eprintln!("TRACE filter_intra_mode value={fi_mode}");
12425 }
12426 istep!("filter_intra_mode", fi_mode as i32);
12427 filter_intra = Some(fi_mode);
12428 }
12429 }
12430 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
12431 // shared U/V map) -- the same order libaom's own loop visits them in.
12432 let palette_y = palette_y_pending.map(|(n, colors)| {
12433 let map = decode_color_index_map(dec, cdfs, n, side, false);
12434 PALETTE_HITS.with(|c| c.set(c.get() + 1));
12435 if trace {
12436 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
12437 }
12438 PaletteY { size: n, colors, map }
12439 });
12440 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
12441 let map = decode_color_index_map(dec, cdfs, n, side / 2, true);
12442 PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
12443 if trace {
12444 eprintln!(
12445 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
12446 &u_colors[..n],
12447 &v_colors[..n]
12448 );
12449 }
12450 PaletteUv { size: n, u_colors, v_colors, map }
12451 });
12452 Ok((
12453 skip,
12454 mode,
12455 angle_delta_y,
12456 uv_mode,
12457 angle_delta_uv,
12458 alpha,
12459 filter_intra,
12460 palette_y,
12461 palette_uv,
12462 ))
12463}
12464
12465/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
12466/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
12467/// intra modes.
12468const UV_CFL_PRED: usize = 13;
12469
12470/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
12471/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
12472/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
12473/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
12474/// joint sign the same way. Returns each plane's final signed `alpha_q3`
12475/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
12476fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
12477 CFL_BLOCK_HITS.with(|c| c.set(c.get() + 1));
12478 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
12479 let sign_u = ((joint_sign + 1) * 11) >> 5;
12480 let sign_v = (joint_sign + 1) - 3 * sign_u;
12481 let alpha_u = if sign_u == 0 {
12482 0
12483 } else {
12484 let ctx_u = (joint_sign + 1 - 3) as usize;
12485 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
12486 if sign_u == 2 { mag } else { -mag }
12487 };
12488 let alpha_v = if sign_v == 0 {
12489 0
12490 } else {
12491 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
12492 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
12493 if sign_v == 2 { mag } else { -mag }
12494 };
12495 (alpha_u, alpha_v)
12496}
12497
12498/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
12499/// the reconstructed luma samples under a `side`-square block, subsampled
12500/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
12501/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
12502/// to give the AC values [`cfl_scaled`] scales by alpha.
12503fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec<i32> {
12504 let cside = side / 2;
12505 let mut ac = vec![0i32; cside * cside];
12506 let mut sum = 0i32;
12507 for cy in 0..cside {
12508 for cx in 0..cside {
12509 let (lx, ly) = (px + cx * 2, py + cy * 2);
12510 let q3 = (i32::from(y.data[ly * y.width + lx])
12511 + i32::from(y.data[ly * y.width + lx + 1])
12512 + i32::from(y.data[(ly + 1) * y.width + lx])
12513 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
12514 << 1;
12515 ac[cy * cside + cx] = q3;
12516 sum += q3;
12517 }
12518 }
12519 let num_pel = (cside * cside) as i32;
12520 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
12521 ac.iter_mut().for_each(|v| *v -= avg);
12522 ac
12523}
12524
12525/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
12526/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
12527/// ties away from zero on the shifted-out sign).
12528fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
12529 let v = alpha_q3 * ac_q3;
12530 if v >= 0 {
12531 (v + 32) >> 6
12532 } else {
12533 -((-v + 32) >> 6)
12534 }
12535}
12536
12537/// One plane's reconstruction buffer, `width * height` samples, and the
12538/// prediction/residual reads and writes into it — the decode-side twin of
12539/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
12540/// (own-edge and reach clamps both), passing what it gathers straight to
12541/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
12542/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
12543/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
12544/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of
12545/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) --
12546/// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE).
12547/// lane-mc64 r1: the decode-order index the stage dumps below key their file
12548/// name on. `PREFILT_PICTURE_IDX` is bumped once per frame just BEFORE the
12549/// deblock/CDEF stages run, so the frame being dumped here is `idx - 1` --
12550/// without this every frame overwrote `.f0` and a per-frame bisection silently
12551/// compared the LAST decoded frame (ledger, class stale-output-faked-measurement).
12552#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
12553fn stage_dump_idx() -> usize {
12554 PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst).saturating_sub(1)
12555}
12556
12557fn dump_stage16(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>, fw: usize, fh: usize) {
12558 use std::io::Write;
12559 // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by
12560 // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed
12561 // `.f0` name kept only the LAST frame, so a mid-sequence divergence could
12562 // not be read out at all.
12563 if let Ok(path) = crate::envflags::var(var)
12564 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
12565 {
12566 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))] {
12567 for row in 0..h {
12568 let mut bytes = Vec::with_capacity(w * 2);
12569 for &s in &p.data[row * p.width..][..w] {
12570 bytes.extend_from_slice(&s.to_le_bytes());
12571 }
12572 let _ = f.write_all(&bytes);
12573 }
12574 }
12575 }
12576}
12577
12578/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a
12579/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so
12580/// every frame overwrote the previous one and only the LAST frame survived,
12581/// which silently defeats any per-frame filter-stage bisection.
12582fn dump_stage_idx(var: &str) -> usize {
12583 use std::collections::HashMap;
12584 use std::sync::{Mutex, OnceLock};
12585 static IDX: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new();
12586 let mut m = IDX.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap();
12587 let e = m.entry(var.to_string()).or_insert(0);
12588 let i = *e;
12589 *e += 1;
12590 i
12591}
12592
12593fn dump_stage(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
12594 use std::io::Write;
12595 if let Ok(path) = crate::envflags::var(var)
12596 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
12597 {
12598 for p in [y, u, v] {
12599 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
12600 let _ = f.write_all(&narrow);
12601 }
12602 }
12603}
12604
12605#[derive(Clone)]
12606struct PlaneBuf<'a> {
12607 data: std::borrow::Cow<'a, [u16]>,
12608 width: usize,
12609 height: usize,
12610 /// The frame's true, decodable extent in this plane's own units — past
12611 /// this, samples are the padded coding surface's invented tail, never a
12612 /// real decoder's edge or reach reads.
12613 true_width: usize,
12614 true_height: usize,
12615 /// This plane's own tile's top-left pixel origin (spec: intra prediction
12616 /// never reaches across a tile boundary even though an earlier-decoded
12617 /// tile's real pixels sit right there in the shared buffer) — set via
12618 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
12619 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
12620 /// is threaded (the two-tile column-split stage 1 fixture's tile always
12621 /// ends at the frame's own right/bottom edge); a non-last tile's own
12622 /// right/bottom reach bound is still open, tracked in the report.
12623 tile_x0: usize,
12624 tile_y0: usize,
12625 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
12626 /// (exclusive) -- a non-last tile column/row's own reach must stop at
12627 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
12628 /// full padded extent) for the single-tile/last-tile case, matching the
12629 /// old unclipped behaviour exactly.
12630 tile_x1: usize,
12631 tile_y1: usize,
12632}
12633
12634/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
12635/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
12636/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
12637/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
12638/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
12639/// `ALTREF2`/`ALTREF`).
12640type RefSlots<'a> = [Option<(&'a PlaneBuf<'a>, &'a PlaneBuf<'a>, &'a PlaneBuf<'a>)>; 8];
12641
12642impl PlaneBuf<'_> {
12643 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
12644 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
12645 /// are already in this plane's own units (luma pixels for `y`, chroma
12646 /// pixels — halved — for `u`/`v`).
12647 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
12648 self.tile_x0 = x0;
12649 self.tile_y0 = y0;
12650 self.tile_x1 = x1;
12651 self.tile_y1 = y1;
12652 }
12653
12654 fn edges(
12655 &self,
12656 x: usize,
12657 y: usize,
12658 side: usize,
12659 reach: Reach,
12660 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
12661 let own_across = x + side.min(self.true_width.saturating_sub(x));
12662 let across = if reach.above_right {
12663 own_across + side.min(self.true_width.saturating_sub(own_across))
12664 } else {
12665 own_across
12666 }
12667 .min(self.width)
12668 .min(self.tile_x1);
12669 let own_down = y + side.min(self.true_height.saturating_sub(y));
12670 let down = if reach.below_left {
12671 own_down + side.min(self.true_height.saturating_sub(own_down))
12672 } else {
12673 own_down
12674 }
12675 .min(self.height)
12676 .min(self.tile_y1);
12677 let above = (y > self.tile_y0 && across > x)
12678 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
12679 let left = (x > self.tile_x0 && down > y).then(|| {
12680 (y..down)
12681 .map(|row| self.data[row * self.width + x - 1])
12682 .collect::<Vec<_>>()
12683 });
12684 let corner =
12685 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
12686 (above, left, corner)
12687 }
12688
12689 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
12690 /// the above/left reach each extend by their OWN axis (`bw` across,
12691 /// `bh` down), not one shared `side`.
12692 fn edges_rect(
12693 &self,
12694 x: usize,
12695 y: usize,
12696 bw: usize,
12697 bh: usize,
12698 reach: Reach,
12699 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
12700 let own_across = x + bw.min(self.true_width.saturating_sub(x));
12701 let across = if reach.above_right {
12702 own_across + bw.min(self.true_width.saturating_sub(own_across))
12703 } else {
12704 own_across
12705 }
12706 .min(self.width)
12707 .min(self.tile_x1);
12708 let own_down = y + bh.min(self.true_height.saturating_sub(y));
12709 let down = if reach.below_left {
12710 own_down + bh.min(self.true_height.saturating_sub(own_down))
12711 } else {
12712 own_down
12713 }
12714 .min(self.height)
12715 .min(self.tile_y1);
12716 let above = (y > self.tile_y0 && across > x)
12717 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
12718 let left = (x > self.tile_x0 && down > y).then(|| {
12719 (y..down)
12720 .map(|row| self.data[row * self.width + x - 1])
12721 .collect::<Vec<_>>()
12722 });
12723 let corner =
12724 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
12725 if matches!((bw, bh), (16, 8) | (8, 16)) {
12726 RECT_STRIP_PRED_HITS.with(|h| h.set(h.get() + 1));
12727 if across > own_across || down > own_down {
12728 RECT_STRIP_REACH_HITS.with(|h| h.set(h.get() + 1));
12729 }
12730 }
12731 (above, left, corner)
12732 }
12733
12734 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
12735 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
12736 /// already-rect-capable `(bw, bh)` pair.
12737 #[allow(clippy::too_many_arguments)]
12738 #[track_caller]
12739 fn reconstruct_rect(
12740 &mut self,
12741 x: usize,
12742 y: usize,
12743 bw: usize,
12744 bh: usize,
12745 mode: usize,
12746 angle_delta: i32,
12747 reach: Reach,
12748 residual: &[i32],
12749 cfl: Option<(i32, &[i32])>,
12750 filter_intra: Option<usize>,
12751 smooth_neighbor: bool,
12752 // lane-wave1 step (i): the palette/intrabc prediction override, taken
12753 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
12754 // than by this replay.
12755 pred: Option<Vec<u16>>, fctx: &crate::decode::FrameCtx,
12756 ) {
12757 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
12758 // (lane-palette2 r4): a palette block's prediction is the
12759 // reconstructed colour-index map, needing no edge pixels at all.
12760 let prediction = if let Some(buf) = pred {
12761 buf
12762 } else {
12763 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
12764 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
12765 eprintln!(
12766 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
12767 above.as_ref().map(|a| (a.len(), a[0])),
12768 left.as_ref().map(|l| l.len()),
12769 left.as_ref().map(|l| l[0]),
12770 self.tile_x0, self.tile_y0, self.true_width, self.true_height
12771 );
12772 }
12773 let mut prediction = vec![0u16; bw * bh];
12774 if let Some(fi_mode) = filter_intra {
12775 crate::intra::predict_filter_intra(
12776 fi_mode,
12777 above.as_deref(),
12778 left.as_deref(),
12779 corner,
12780 bw,
12781 bh,
12782 &mut prediction, fctx,
12783 );
12784 } else {
12785 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
12786 predict(
12787 mode as u8,
12788 angle_delta,
12789 above.as_deref(),
12790 left.as_deref(),
12791 corner,
12792 bw,
12793 bh,
12794 enable_edge_filter,
12795 smooth_neighbor,
12796 &mut prediction, fctx,
12797 );
12798 }
12799 prediction
12800 };
12801 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
12802 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
12803 if crate::envflags::env_flag!("EC_PRED") {
12804 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
12805 let row0: Vec<u16> = prediction[..bw.min(8)].to_vec();
12806 let col0: Vec<u16> = (0..bh.min(8)).map(|r| prediction[r * bw]).collect();
12807 eprintln!(
12808 "@{} OUR_PRED x={x} y={y} bw={bw} bh={bh} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller(), i32::from(smooth_neighbor)
12809 );
12810 }
12811 for row in 0..bh {
12812 // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s
12813 // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame
12814 // whose padded width is not superblock aligned hangs past it.
12815 if y + row >= self.height {
12816 break;
12817 }
12818 for col in 0..bw {
12819 if x + col >= self.width {
12820 break;
12821 }
12822 let idx = row * bw + col;
12823 let mut base = i32::from(prediction[idx]);
12824 if let Some((alpha_q3, ac_q3)) = cfl {
12825 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
12826 }
12827 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
12828 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
12829 }
12830 }
12831 }
12832
12833 /// Predicts under `mode` then adds `residual` (side*side, raster),
12834 /// writing the clamped reconstruction back into the plane at `(x, y)`.
12835 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
12836 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
12837 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
12838 /// order (cfl.c).
12839 #[track_caller]
12840 fn reconstruct(
12841 &mut self,
12842 x: usize,
12843 y: usize,
12844 side: usize,
12845 mode: usize,
12846 angle_delta: i32,
12847 reach: Reach,
12848 residual: &[i32],
12849 cfl: Option<(i32, &[i32])>,
12850 filter_intra: Option<usize>,
12851 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
12852 // libaom `get_filt_type`): true when the block's above OR left
12853 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
12854 // Callers pass their own plane's neighbour-mode check
12855 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
12856 // callers until a smooth/paeth `uv_mode` can reach this call at all
12857 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
12858 // keeps `false` exact for chroma without this fn needing to know why.
12859 smooth_neighbor: bool,
12860 // lane-wave1 step (i): the palette/intrabc prediction override, taken
12861 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
12862 // than by this replay.
12863 pred: Option<Vec<u16>>, fctx: &crate::decode::FrameCtx,
12864 ) {
12865 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
12866 // takes priority over `predict()`/`predict_filter_intra` entirely --
12867 // palette prediction needs no edge pixels at all.
12868 let prediction = if let Some(buf) = pred {
12869 buf
12870 } else {
12871 let (above, left, corner) = self.edges(x, y, side, reach);
12872 let mut prediction = vec![0u16; side * side];
12873 if let Some(fi_mode) = filter_intra {
12874 crate::intra::predict_filter_intra(
12875 fi_mode,
12876 above.as_deref(),
12877 left.as_deref(),
12878 corner,
12879 side,
12880 side,
12881 &mut prediction, fctx,
12882 );
12883 } else {
12884 // `enable_intra_edge_filter` is the sequence header's own flag
12885 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
12886 // call, never per-block) -- threading it through every
12887 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
12888 // dozen sites for a value that never changes mid-decode, so it
12889 // rides a thread-local instead (this decoder is single-threaded
12890 // per stream).
12891 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
12892 predict(
12893 mode as u8,
12894 angle_delta,
12895 above.as_deref(),
12896 left.as_deref(),
12897 corner,
12898 side,
12899 side,
12900 enable_edge_filter,
12901 smooth_neighbor,
12902 &mut prediction, fctx,
12903 );
12904 }
12905 prediction
12906 };
12907 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
12908 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
12909 if crate::envflags::env_flag!("EC_PRED") {
12910 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
12911 let row0: Vec<u16> = prediction[..side.min(8)].to_vec();
12912 let col0: Vec<u16> = (0..side.min(8)).map(|r| prediction[r * side]).collect();
12913 eprintln!(
12914 "@{} OUR_PRED x={x} y={y} side={side} side={side} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller(), i32::from(smooth_neighbor)
12915 );
12916 }
12917 for row in 0..side {
12918 // lane-sb128c r8: libaom's frame buffer is superblock
12919 // aligned; ours is padded to 32 (`block_grid`), so a 64x64
12920 // transform unit of a 128x64 block at the BOTTOM frame edge
12921 // can hang past the last padded row (1920x792: a unit at
12922 // y=768 wants 832 rows of an 800-row buffer, which panicked
12923 // the film's key frames). Those samples are outside the
12924 // frame: never output, and no block below ever references
12925 // them.
12926 if y + row >= self.height {
12927 break;
12928 }
12929 for col in 0..side {
12930 if x + col >= self.width {
12931 break;
12932 }
12933 let idx = row * side + col;
12934 let mut base = i32::from(prediction[idx]);
12935 if let Some((alpha_q3, ac_q3)) = cfl {
12936 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
12937 }
12938 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
12939 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
12940 }
12941 }
12942 }
12943}
12944
12945/// Reads one plane's transform block, reconstructs it into `plane` at
12946/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
12947#[allow(clippy::too_many_arguments)]
12948fn read_plane(
12949 dec: &mut SymbolDecoder,
12950 cdfs: &mut Cdfs,
12951 set: TxbSet,
12952 scan: &[u16],
12953 plane_idx: usize,
12954 around: (bool, bool, i32),
12955 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
12956 // it for every plane's `txb` lookup (it is what an intra transform type's
12957 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
12958 tx_mode: usize,
12959 predict_mode: usize,
12960 angle_delta: i32,
12961 reach: Reach,
12962 // lane-wave1 step (i): unread -- this reader records its write
12963 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
12964 // stays in the signature so every call site still proves the plane is
12965 // exclusively held while its coefficients are parsed.
12966 _plane: &mut PlaneBuf<'static>,
12967 x: usize,
12968 y: usize,
12969 side: usize,
12970 tx_side: usize,
12971 base_q_idx: u8,
12972 cfl: Option<(i32, CflSrc)>,
12973 filter_intra: Option<usize>,
12974 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
12975 // smaller than its own block (spec `get_txb_ctx_general`'s
12976 // `plane_bsize != tx_size` branch), carrying the already-looked-up
12977 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
12978 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
12979 // formula below.
12980 luma_skip_ctx: Option<usize>,
12981 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
12982 smooth_neighbor: bool, fctx: &crate::decode::FrameCtx,
12983) -> Result<Vec<i32>> {
12984 let skip_ctx = if plane_idx == 0 {
12985 luma_skip_ctx.unwrap_or(0)
12986 } else {
12987 // libaom `get_txb_ctx`: a chroma unit's context is
12988 // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the
12989 // plane block is bigger than the transform. Our chroma tables hold the
12990 // offset-7 rows first, so the caller adds 3 for the bigger-block case
12991 // (only a 128x128 block's TX_32X32 chroma units, lane-sb128b r3).
12992 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
12993 };
12994 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
12995 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
12996 // not by the block's ordinary `mode` (which is always DC_PRED whenever
12997 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
12998 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
12999 // filter-intra in AV1).
13000 let tx_mode = if plane_idx == 0 { fi_tx_row(tx_mode, filter_intra) } else { tx_mode };
13001 let mut coding = cdfs.txb(set, tx_mode);
13002 // Luma's `default_tx_type` is only a fallback for the sizes whose
13003 // `TxbSet` carries no symbol at all (32-point and up), which the spec
13004 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
13005 // *never* its own coded symbol (`coding.tx_type` is always `None` for
13006 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
13007 // the plane's own predicted mode (`default_intra_tx_type`) -- except
13008 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
13009 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
13010 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
13011 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
13012 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
13013 // narrows there — only `Chroma32` and up do).
13014 let default_tx_type = if plane_idx == 0 || side >= 32 {
13015 TxType::DctDct
13016 } else if let Some(inherited) = fctx.intrabc_chroma_tx.with(std::cell::Cell::get) {
13017 // See [`INTRABC_CHROMA_TX`]: an intrabc block is an inter block for
13018 // `av1_get_tx_type`, so chroma inherits luma's coded type (the
13019 // `side >= 32` arm above is already libaom's `EXT_TX_SET_DCTONLY`
13020 // clamp at `tx_size_sqr_up >= TX_32X32`, matching
13021 // [`read_inter_plane`]'s own `side < 32` guard).
13022 inherited
13023 } else {
13024 default_intra_tx_type(predict_mode as u8)
13025 };
13026 let (grid, tx_type) = read_coeffs(
13027 dec,
13028 &mut coding,
13029 scan,
13030 skip_ctx,
13031 dc_sign_ctx(around.2),
13032 default_tx_type,
13033 None,
13034 )?;
13035 note_chroma_class1(plane_idx, tx_type);
13036 if plane_idx == 0 {
13037 fctx.luma_tx_type.with(|c| c.set(tx_type));
13038 }
13039 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
13040 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
13041 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
13042 // guard also assumes.
13043 let levels = if tx_side == side {
13044 grid
13045 } else {
13046 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
13047 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
13048 // keyed by that true size, not the coded corner's -- so the corner
13049 // goes into the top-left of a `side`-sized grid, not the reverse.
13050 let mut full = vec![0i32; side * side];
13051 for row in 0..tx_side {
13052 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
13053 }
13054 full
13055 };
13056 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
13057 let tx = TxParams {
13058 w: side, h: side, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta,
13059 ac_delta, tx_type, stride: 0,
13060 };
13061 if crate::envflags::env_flag!("EC_AV1_TRACE") {
13062 let residual = tx.run(&levels);
13063 eprintln!(
13064 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={levels:?} residual={residual:?}",
13065 );
13066 }
13067 push_intra_tx(
13068 plane_idx,
13069 x,
13070 y,
13071 side,
13072 side,
13073 false,
13074 predict_mode,
13075 angle_delta,
13076 reach,
13077 tx,
13078 &levels,
13079 cfl,
13080 filter_intra,
13081 smooth_neighbor, fctx,
13082 );
13083 Ok(if tx_side == side {
13084 residual_grid_placeholder(&levels, side)
13085 } else {
13086 levels
13087 })
13088}
13089
13090/// `record`'s neighbour state only reads whether *the coded grid* (not the
13091/// residual) has nonzero entries, so the levels this function already built
13092/// are what it wants back; this helper exists only to name that clearly at
13093/// the one call site where `tx_side == side`.
13094fn residual_grid_placeholder(levels: &[i32], _tx_side: usize) -> Vec<i32> {
13095 levels.to_vec()
13096}
13097
13098/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
13099/// three planes, reconstructing them into `y`/`u`/`v` and updating
13100/// `neighbours`.
13101#[allow(clippy::too_many_arguments)]
13102fn decode_block(
13103 dec: &mut SymbolDecoder,
13104 cdfs: &mut Cdfs,
13105 neighbours: &mut Neighbours,
13106 at: (usize, usize),
13107 side: usize,
13108 luma_set: TxbSet,
13109 chroma_set: TxbSet,
13110 luma_tx: usize,
13111 chroma_tx: usize,
13112 scans: (&[u16], &[u16]),
13113 cfl: bool,
13114 y: &mut PlaneBuf<'static>,
13115 u: &mut PlaneBuf<'static>,
13116 v: &mut PlaneBuf<'static>,
13117 base_q_idx: u8,
13118 enable_filter_intra: bool,
13119 allow_screen_content_tools: bool,
13120 allow_intrabc: bool,
13121 scan32: &[u16],
13122 scan16: &[u16],
13123 scan8: &[u16],
13124 scan4: &[u16],
13125 tx_select: bool,
13126 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
13127) -> Result<()> {
13128 let (r, c) = at;
13129 let (px, py) = (c * SUB, r * SUB);
13130 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
13131 let palette_uv_cache = neighbours.palette_uv_cache(at);
13132 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
13133 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
13134 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
13135 read_intra_mode(
13136 dec,
13137 cdfs,
13138 nb_above_mode,
13139 nb_left_mode,
13140 cfl,
13141 side,
13142 enable_filter_intra,
13143 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
13144 allow_screen_content_tools,
13145 allow_intrabc,
13146 Some((palette_ctx, &palette_cache)),
13147 &palette_uv_cache,
13148 r * (SUB / MI),
13149 c * (SUB / MI), fctx,
13150 )?;
13151 if at_tile_left && palette_y.is_some() {
13152 PALETTE_TILE_LEFT_HITS.with(|c| c.set(c.get() + 1));
13153 }
13154 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
13155 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
13156 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
13157 // actual chroma-from-luma correlation, same as this decoder always did.
13158 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
13159 DC_PRED
13160 } else {
13161 uv_mode
13162 };
13163 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
13164 if smooth_neighbor {
13165 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
13166 }
13167 let smooth_neighbor_uv =
13168 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
13169 if crate::envflags::env_flag!("EC_AV1_TRACE") {
13170 eprintln!(
13171 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
13172 angle_delta_uv={angle_delta_uv}"
13173 );
13174 }
13175 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
13176 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
13177 // block, skipped or not. `logical_tx` is what the loop filter's edge
13178 // lookup and the next block's own `tx_size_context` want (the *nominal*
13179 // transform size -- 64 even for the 64x64 corner-scanned case, spec
13180 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
13181 // which only differs from it at that one corner case.
13182 // lane-t900 r32: spec 5.11.16 `read_block_tx_size` gates the `tx_depth`
13183 // symbol on `allowSelect = !skip || !is_inter`, and libaom's
13184 // `is_inter_block` counts an INTRABC block (`blockd.h:373`). So a SKIPPED
13185 // intrabc block reads NO tx-size symbol at all -- it takes
13186 // `maxRectTxSize` -- while every ordinary skipped intra block does read
13187 // one. Reading it anyway consumed a symbol libaom never wrote and desynced
13188 // the tile from that block on (class `equal-range-means-unread`).
13189 // lane-t900 r32: and an UNSKIPPED one reads the inter var-tx partition
13190 // tree instead (`read_var_tx_size`), the same syntax the inter block path
13191 // has always read -- libaom's `parse_decode_block` dispatches on
13192 // `is_inter_block`, so both branches of `read_block_tx_size` treat an
13193 // intrabc block as inter.
13194 let intrabc_skip_tx = intrabc_dv.is_some() && skip;
13195 let intrabc_vartx = intrabc_dv.is_some() && tx_select && !skip;
13196 let intrabc_leaves = if intrabc_vartx {
13197 let max_tx = side.min(64);
13198 // `max_block_wide`/`max_block_high`: the frame's own mi grid
13199 // (`av1_calc_mi_size`, 8-px aligned), so a block hanging over the
13200 // right/bottom edge reads no split symbol for the units outside it.
13201 let mi_cols = 2 * y.true_width.div_ceil(8);
13202 let mi_rows = 2 * y.true_height.div_ceil(8);
13203 let side_mi = side / MI;
13204 let max_w_mi = side_mi.min(mi_cols.saturating_sub(mi_c));
13205 let max_h_mi = side_mi.min(mi_rows.saturating_sub(mi_r));
13206 let mut leaves = Vec::new();
13207 for row in (0..side_mi).step_by(max_tx / MI) {
13208 for col in (0..side_mi).step_by(max_tx / MI) {
13209 read_var_tx_size(
13210 dec, cdfs, neighbours, (mi_r, mi_c), side,
13211 (max_w_mi, max_h_mi), (max_tx, max_tx), 0, row, col, &mut leaves,
13212 );
13213 }
13214 }
13215 INTRABC_VARTX_HITS.with(|c| c.set(c.get() + 1));
13216 // The luma reconstruct loop below is a UNIFORM grid of one square
13217 // transform (the intra `tx_depth` shape), so a tree that resolved to
13218 // mixed leaf sizes is refused by name rather than reconstructed at the
13219 // wrong stride.
13220 let uniform = leaves
13221 .first()
13222 .is_some_and(|f| leaves.iter().all(|l| (l.2, l.3) == (f.2, f.3) && l.2 == l.3));
13223 if !uniform {
13224 return Err(unsupported(
13225 "an intrabc block whose var-tx tree resolved to mixed leaf transform sizes",
13226 ));
13227 }
13228 Some(leaves[0].2)
13229 } else {
13230 None
13231 };
13232 let (logical_tx, coeff_tx_side) = if let Some(tx) = intrabc_leaves {
13233 (tx, if tx == 64 { 32 } else { tx })
13234 } else if tx_select && !intrabc_skip_tx {
13235 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, None);
13236 (resolved, if resolved == 64 { 32 } else { resolved })
13237 } else {
13238 // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is
13239 // TX_64X64, so a 128x128 block is always FOUR luma transform units
13240 // even with `tx_select` off -- the TU loop below, never the
13241 // single-unit path.
13242 (side.min(64), luma_tx)
13243 };
13244 if tx_select && logical_tx < side && uv_mode != DC_PRED {
13245 SQ_CHROMA_TX_HITS.with(|c| c.set(c.get() + 1));
13246 }
13247 let luma_set = if tx_select {
13248 txbset_for(logical_tx, reduced_tx_set)
13249 } else {
13250 luma_set
13251 };
13252 let luma_set = if intrabc_dv.is_some() {
13253 txbset_for_inter(logical_tx, reduced_tx_set)
13254 } else {
13255 luma_set
13256 };
13257 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
13258 let reach = Reach::of(side, px, py, y.width, y.height, fctx);
13259 let (cpx, cpy) = (px / 2, py / 2);
13260 let chroma_side = side / 2;
13261 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
13262 // frame's own pre-loop-filter reconstruction (all loop filters are off
13263 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
13264 // block vector, with the BILINEAR kernel libaom forces for intrabc --
13265 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
13266 // odd, which is exactly what the bilinear taps then interpolate.
13267 flush_recon(fctx, y, u, v);
13268 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
13269 let mut yb = vec![0u16; side * side];
13270 mc::predict_with_filter(
13271 &y.data, y.width, y.true_width, y.true_height,
13272 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
13273 side, side, mc::InterpFilterKind::Bilinear, &mut yb, fctx,
13274 );
13275 let mut ub = vec![0u16; chroma_side * chroma_side];
13276 mc::predict_with_filter(
13277 &u.data, u.width, u.true_width, u.true_height,
13278 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
13279 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut ub, fctx,
13280 );
13281 let mut vb = vec![0u16; chroma_side * chroma_side];
13282 mc::predict_with_filter(
13283 &v.data, v.width, v.true_width, v.true_height,
13284 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
13285 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut vb, fctx,
13286 );
13287 (yb, ub, vb)
13288 });
13289 // A palette-Y block's own prediction is the reconstructed colour-index
13290 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
13291 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
13292 // parameter through this function's dozen `y.reconstruct`/`read_plane`
13293 // sites. A split luma transform (`tx_select && logical_tx != side`)
13294 // would need the map sliced per-TU -- untested against a real
13295 // `--enable-palette=1` stream this round, so refuse by name rather than
13296 // guess at the slicing (charter's own named-acceptable fallback).
13297 let palette_y_buf: Option<Vec<u16>> = palette_y.as_ref().map(|py| {
13298 py.map
13299 .iter()
13300 .map(|&idx| py.colors[idx as usize])
13301 .collect()
13302 });
13303 // lane-t900 r32: the intrabc luma prediction rides the very same
13304 // whole-block override slot, so the multi-TU loop below windows it per
13305 // transform unit exactly like a palette map -- setting it once up front
13306 // handed the whole `side`x`side` buffer to the FIRST unit and left every
13307 // later one predicting off block edges (the var-tx tree above is what
13308 // first makes `logical_tx < side` reachable for an intrabc block).
13309 let palette_y_buf = match &intrabc_bufs {
13310 Some((yb, _, _)) => Some(yb.clone()),
13311 None => palette_y_buf,
13312 };
13313 // With one luma transform unit the whole `side`x`side` map is the
13314 // prediction; with several (`logical_tx != side`) each unit takes its own
13315 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
13316 // below (lane-palette2 r7) -- setting the full-block buffer here would be
13317 // taken by the FIRST unit and indexed at the wrong stride.
13318 if let Some(buf) = &palette_y_buf
13319 && logical_tx == side
13320 {
13321 set_palette_pred(buf.clone(), fctx);
13322 }
13323 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
13324 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
13325 // plane's own `reconstruct`/`read_plane` call below (never both planes at
13326 // once), since Y's own set-then-take already emptied the slot by the time
13327 // either of these run.
13328 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
13329 (
13330 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
13331 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
13332 )
13333 });
13334 // The chroma half of the intrabc prediction rides the same per-plane
13335 // override slot the UV-palette buffers do (set fresh before each plane's
13336 // own `reconstruct`/`read_plane` call below).
13337 let palette_uv_bufs = match &intrabc_bufs {
13338 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
13339 None => palette_uv_bufs,
13340 };
13341 if skip {
13342 // A skipped block codes no residual syntax at all (spec 5.11.34):
13343 // straight prediction, on every plane.
13344 //
13345 // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it
13346 // is skipped (only an INTER skip forces the largest transform), and
13347 // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts
13348 // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units
13349 // already written left/above of it inside this same block. Predicting
13350 // the whole `side`x`side` at once gives a different (uniformly off by
13351 // ~1) answer, which is exactly the residue this lane was chasing.
13352 // The palette/intrabc override path keeps the single-call shape (its
13353 // per-TU windowing is the non-skip loop's own `palette_y_buf` slice,
13354 // untested for skip and unreachable in these streams).
13355 // lane-sb128b r2: a 128x128 block's transform is TX_64X64 even with
13356 // `tx_select` off (`max_txsize_rect_lookup[BLOCK_128X128]`), so the
13357 // per-unit prediction is keyed on the transform being smaller than
13358 // the block, not on the tx-depth syntax. The counter keeps lane-hgkf's
13359 // narrower meaning (a READ split tx depth).
13360 let split_tx_skip =
13361 logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none();
13362 if split_tx_skip {
13363 if tx_select {
13364 SKIP_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
13365 }
13366 let n_axis = side / logical_tx;
13367 for tu_row in 0..n_axis {
13368 for tu_col in 0..n_axis {
13369 let tu_px = px + tu_col * logical_tx;
13370 let tu_py = py + tu_row * logical_tx;
13371 if tu_px >= y.true_width || tu_py >= y.true_height {
13372 continue;
13373 }
13374 let tu_reach = tu_reach(
13375 side,
13376 side,
13377 tu_col * logical_tx,
13378 tu_row * logical_tx,
13379 logical_tx,
13380 reach,
13381 px,
13382 py,
13383 y.width,
13384 y.height, fctx,
13385 );
13386 push_intra(0,
13387 tu_px,
13388 tu_py,
13389 logical_tx,
13390 mode,
13391 angle_delta_y,
13392 tu_reach,
13393 &vec![0i32; logical_tx * logical_tx],
13394 None,
13395 filter_intra,
13396 smooth_neighbor, fctx,
13397 );
13398 }
13399 }
13400 } else {
13401 push_intra(0,
13402 px,
13403 py,
13404 side,
13405 mode,
13406 angle_delta_y,
13407 reach,
13408 &vec![0i32; side * side],
13409 None,
13410 filter_intra,
13411 smooth_neighbor, fctx,
13412 );
13413 }
13414 let ac = alpha.map(|_| cfl_src(px, py, side));
13415 let cn = (chroma_side / chroma_tx).max(1);
13416 for cu_row in 0..cn {
13417 for cu_col in 0..cn {
13418 let luma_span = chroma_tx * 2;
13419 let cu_r = if cn == 1 {
13420 reach
13421 } else {
13422 tu_reach(
13423 side, side,
13424 cu_col * luma_span, cu_row * luma_span, luma_span,
13425 reach, px, py, y.width, y.height, fctx,
13426 )
13427 };
13428 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
13429 if let Some((ub, _)) = &palette_uv_bufs {
13430 set_palette_pred(ub.clone(), fctx);
13431 }
13432 push_intra(1,
13433 cu_x,
13434 cu_y,
13435 chroma_tx,
13436 uv_predict_mode,
13437 angle_delta_uv,
13438 cu_r,
13439 &vec![0i32; chroma_tx * chroma_tx],
13440 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
13441 None,
13442 smooth_neighbor_uv, fctx,
13443 );
13444 if let Some((_, vb)) = &palette_uv_bufs {
13445 set_palette_pred(vb.clone(), fctx);
13446 }
13447 push_intra(2,
13448 cu_x,
13449 cu_y,
13450 chroma_tx,
13451 uv_predict_mode,
13452 angle_delta_uv,
13453 cu_r,
13454 &vec![0i32; chroma_tx * chroma_tx],
13455 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
13456 None,
13457 smooth_neighbor_uv, fctx,
13458 );
13459 }
13460 }
13461 let luma_grid = vec![0i32; side * side];
13462 let u_grid = vec![0i32; chroma_side * chroma_side];
13463 let v_grid = vec![0i32; chroma_side * chroma_side];
13464 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
13465 } else if logical_tx == side {
13466 // lane-sb128b r1: the test used to be `!tx_select || logical_tx == side`.
13467 // Without `tx_select` `logical_tx` IS `side` at every size <= 64, so
13468 // that arm was redundant -- and wrong at 128, where
13469 // `max_txsize_rect_lookup` caps the block's transform at 64 and the
13470 // block is four units whether or not `tx_select` is on.
13471 // A single luma transform unit -- the old path, unchanged (including
13472 // the 64x64 corner case, `logical_tx == side == 64` with
13473 // `coeff_tx_side == 32`).
13474 let around = neighbours.around(at, side);
13475 let luma_grid = read_plane(
13476 dec,
13477 cdfs,
13478 luma_set,
13479 luma_scan,
13480 0,
13481 around[0],
13482 mode,
13483 mode,
13484 angle_delta_y,
13485 reach,
13486 y,
13487 px,
13488 py,
13489 side,
13490 coeff_tx_side,
13491 base_q_idx,
13492 None,
13493 filter_intra,
13494 None,
13495 smooth_neighbor, fctx,
13496 )?;
13497 let ac = alpha.map(|_| cfl_src(px, py, side));
13498 // Armed for exactly this block's two chroma reads (see
13499 // [`INTRABC_CHROMA_TX`]); the luma call above just set
13500 // [`LUMA_TX_TYPE`] to the type it coded.
13501 if intrabc_dv.is_some() {
13502 fctx.intrabc_chroma_tx.with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
13503 }
13504 if let Some((ub, _)) = &palette_uv_bufs {
13505 set_palette_pred(ub.clone(), fctx);
13506 }
13507 let u_grid = read_plane(
13508 dec,
13509 cdfs,
13510 chroma_set,
13511 scans.1,
13512 1,
13513 around[1],
13514 mode,
13515 uv_predict_mode,
13516 angle_delta_uv,
13517 reach,
13518 u,
13519 cpx,
13520 cpy,
13521 chroma_side,
13522 chroma_tx,
13523 base_q_idx,
13524 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
13525 None,
13526 None,
13527 smooth_neighbor_uv, fctx,
13528 )?;
13529 if crate::envflags::env_flag!("EC_AV1_TRACE") {
13530 eprintln!(
13531 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
13532 &u.data[cpy * u.width + cpx..][..chroma_side]
13533 );
13534 }
13535 if let Some((_, vb)) = &palette_uv_bufs {
13536 set_palette_pred(vb.clone(), fctx);
13537 }
13538 let v_grid = read_plane(
13539 dec,
13540 cdfs,
13541 chroma_set,
13542 scans.1,
13543 2,
13544 around[2],
13545 mode,
13546 uv_predict_mode,
13547 angle_delta_uv,
13548 reach,
13549 v,
13550 cpx,
13551 cpy,
13552 chroma_side,
13553 chroma_tx,
13554 base_q_idx,
13555 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
13556 None,
13557 None,
13558 smooth_neighbor_uv, fctx,
13559 )?;
13560 fctx.intrabc_chroma_tx.with(|c| c.set(None));
13561 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
13562 } else {
13563 // Several luma transform units, raster order (spec
13564 // `transform_block`'s loop): the block's resolved transform is
13565 // genuinely smaller than its own side, so each tile of it predicts
13566 // and codes independently, its own context read fresh off whatever
13567 // the earlier tiles in this same block already wrote -- the same
13568 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
13569 let n_axis = side / logical_tx;
13570 let cn = (chroma_side / chroma_tx).max(1);
13571 // libaom's transform-block loop is over 64x64 luma "mu" chunks
13572 // (`decode_token_recon_block`: `mu_blocks_wide/high` =
13573 // `mi_size_wide[BLOCK_64X64]`), and it codes EVERY PLANE of a chunk
13574 // before moving to the next one. Below 128 a block is a single chunk,
13575 // so this is byte-for-byte the all-luma-then-all-chroma order that has
13576 // always run; at 128 the four quadrants interleave Y,U,V per quadrant
13577 // and reading all four luma units first desyncs the tile at the second
13578 // one (lane-sb128b r3, measured against aomdec's `EC_TRACE_COEFF`).
13579 let nchunk = (side / 64).max(1);
13580 // `cn > 1` means the uv plane block is larger than the uv transform,
13581 // which moves libaom's chroma `txb_skip_ctx` offset from 7 to 10.
13582 let chroma_ctx_offset = if cn > 1 { Some(3) } else { None };
13583 let tpc = (n_axis / nchunk).max(1);
13584 let cpc = (cn / nchunk).max(1);
13585 let mut last_grids = [Vec::new(), Vec::new()];
13586 let mut units: Vec<((usize, usize), usize, Vec<i32>, Vec<i32>)> = Vec::new();
13587 for ch_row in 0..nchunk {
13588 for ch_col in 0..nchunk {
13589 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
13590 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
13591 let tu_mi = (
13592 mi_r + tu_row * (logical_tx / MI),
13593 mi_c + tu_col * (logical_tx / MI),
13594 );
13595 let tu_px = px + tu_col * logical_tx;
13596 let tu_py = py + tu_row * logical_tx;
13597 // Same libaom clip as `decode_rect_split`'s loop above; a
13598 // square block only hangs off the frame when the frame's mi
13599 // dimensions are odd at the block's own level.
13600 if tu_px >= y.true_width || tu_py >= y.true_height {
13601 continue;
13602 }
13603 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
13604 // A transform unit inside a block is NOT a block at that
13605 // position (lane-palette2 r12): `Reach::of` granted the
13606 // top-right 8x8 unit of a 16x16 D203 block bottom-left
13607 // pixels libaom refuses outright (`col_off > 0`), which is
13608 // the diagonal wedge seed 46 reconstructed wrong.
13609 let tu_reach = tu_reach(
13610 side,
13611 side,
13612 tu_col * logical_tx,
13613 tu_row * logical_tx,
13614 logical_tx,
13615 reach,
13616 px,
13617 py,
13618 y.width,
13619 y.height, fctx,
13620 );
13621 // This transform unit's own bsize (`logical_tx`) is smaller
13622 // than the block it sits in (`side`), so `txb_skip_ctx` is
13623 // the neighbour-magnitude table, not the lone-TU 0 (spec
13624 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
13625 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
13626 if let Some(buf) = &palette_y_buf {
13627 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
13628 let mut window = vec![0u16; logical_tx * logical_tx];
13629 for row in 0..logical_tx {
13630 let src = (tu_row * logical_tx + row) * side + tu_col * logical_tx;
13631 window[row * logical_tx..][..logical_tx]
13632 .copy_from_slice(&buf[src..][..logical_tx]);
13633 }
13634 set_palette_pred(window, fctx);
13635 }
13636 let tu_grid = read_plane(
13637 dec,
13638 cdfs,
13639 luma_set,
13640 luma_scan,
13641 0,
13642 tu_around,
13643 mode,
13644 mode,
13645 angle_delta_y,
13646 tu_reach,
13647 y,
13648 tu_px,
13649 tu_py,
13650 logical_tx,
13651 // The unit's own COEFFICIENT grid, half its side at
13652 // TX_64X64 (a 64-point transform codes nothing past 32);
13653 // identical to `logical_tx` at every smaller size
13654 // (lane-sb128b r1).
13655 coeff_tx_side,
13656 base_q_idx,
13657 None,
13658 filter_intra,
13659 Some(tu_skip_ctx),
13660 smooth_neighbor, fctx,
13661 )?;
13662 if crate::envflags::env_flag!("EC_AV1_TRACE") {
13663 eprintln!(
13664 "TRACE tu_bitpos mi=({},{}) tell={}",
13665 tu_mi.0,
13666 tu_mi.1,
13667 dec.debug_bitpos()
13668 );
13669 }
13670 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
13671 }
13672 }
13673 // CfL is only allowed up to 32x32, i.e. only at `nchunk == 1`, where
13674 // this still runs after every luma unit of the block.
13675 let ac = alpha.map(|_| cfl_src(px, py, side));
13676 // The block's uv plane block is `chroma_side` across but its uv
13677 // transform is `chroma_tx` (`av1_get_max_uv_txsize` =
13678 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[uv_plane_bsize])`):
13679 // identical at every size up to 64x64, but a 128x128 block's 64x64 uv
13680 // plane block adjusts TX_64X64 down to TX_32X32, so each plane is
13681 // FOUR units (lane-sb128b r2) -- one per mu chunk.
13682 for cu_row in ch_row * cpc..(ch_row + 1) * cpc {
13683 for cu_col in ch_col * cpc..(ch_col + 1) * cpc {
13684 // The chroma context arrays are indexed in LUMA mi, so this
13685 // unit's anchor is its own luma quadrant: `chroma_tx` chroma
13686 // pixels span `2 * chroma_tx` luma ones.
13687 let luma_span = chroma_tx * 2;
13688 let cu_mi = (
13689 mi_r + cu_row * (luma_span / MI),
13690 mi_c + cu_col * (luma_span / MI),
13691 );
13692 let cu_around = neighbours.around_mi(cu_mi, luma_span);
13693 let cu_reach = if cn == 1 {
13694 reach
13695 } else {
13696 tu_reach(
13697 side, side,
13698 cu_col * luma_span, cu_row * luma_span, luma_span,
13699 reach, px, py, y.width, y.height, fctx,
13700 )
13701 };
13702 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
13703 if let Some((ub, _)) = &palette_uv_bufs {
13704 set_palette_pred(ub.clone(), fctx);
13705 }
13706 let u_grid = read_plane(
13707 dec, cdfs, chroma_set, scans.1, 1, cu_around[1], mode,
13708 uv_predict_mode, angle_delta_uv, cu_reach, u, cu_x, cu_y,
13709 chroma_tx, chroma_tx, base_q_idx,
13710 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
13711 None, chroma_ctx_offset, smooth_neighbor_uv, fctx,
13712 )?;
13713 if let Some((_, vb)) = &palette_uv_bufs {
13714 set_palette_pred(vb.clone(), fctx);
13715 }
13716 let v_grid = read_plane(
13717 dec, cdfs, chroma_set, scans.1, 2, cu_around[2], mode,
13718 uv_predict_mode, angle_delta_uv, cu_reach, v, cu_x, cu_y,
13719 chroma_tx, chroma_tx, base_q_idx,
13720 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
13721 None, chroma_ctx_offset, smooth_neighbor_uv, fctx,
13722 )?;
13723 if cn > 1 {
13724 CHROMA_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
13725 // Immediately, so the NEXT unit of this same block reads
13726 // this one's coefficient context (libaom's chroma
13727 // `txb_skip_ctx` for the second quadrant is 11, i.e. base
13728 // 1 from this left neighbour -- measured against aomdec).
13729 // The same writes are replayed after `record_split_luma`
13730 // below, which would otherwise clobber them whole-block.
13731 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 1, &u_grid);
13732 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 2, &v_grid);
13733 units.push((cu_mi, luma_span, u_grid.clone(), v_grid.clone()));
13734 }
13735 last_grids = [u_grid, v_grid];
13736 }
13737 }
13738 }
13739 }
13740 // Mode/side bookkeeping plus, at `cn == 1`, the whole-plane chroma
13741 // context write; at `cn > 1` the per-unit writes above are what the
13742 // next block reads, so they run after this (last writer wins).
13743 neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&last_grids[0], &last_grids[1]]);
13744 for (cu_mi, luma_span, u_grid, v_grid) in &units {
13745 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 1, u_grid);
13746 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 2, v_grid);
13747 }
13748 }
13749 // Unconditional, `size == 0` for a non-palette block: clears any stale
13750 // neighbour palette state the same way [`Neighbours::record`] always
13751 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
13752 // (the split-luma-TU branch above always refuses before reaching here
13753 // when `palette_y` is `Some`, so it is never live for that branch).
13754 let (py_size, py_colors) = palette_y
13755 .as_ref()
13756 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
13757 neighbours.record_palette_y(at, side, py_size, py_colors);
13758 let (puv_size, puv_colors) = palette_uv
13759 .as_ref()
13760 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
13761 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
13762 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
13763 neighbours.fill_lf_grid(
13764 (r * (SUB / MI), c * (SUB / MI)),
13765 side / MI,
13766 logical_tx as u8,
13767 0, fctx,
13768 );
13769 // lane-t900 r32: libaom runs `set_txfm_ctxs` at the end of EVERY
13770 // `decode_block`, key frames included, and the intrabc var-tx read above
13771 // (`txfm_partition_ctx`) is the only intra-path reader of those bands --
13772 // left at `TXFM_CTX_INIT` it would take the split symbol off the wrong CDF
13773 // row. Armed by the frame's own `allow_intrabc` so every other key frame
13774 // (whose readers use the deblock-grid approximation) is untouched.
13775 if allow_intrabc {
13776 set_txfm_ctxs(
13777 neighbours,
13778 (mi_r, mi_c),
13779 logical_tx,
13780 side / MI,
13781 side / MI,
13782 skip && intrabc_dv.is_some(),
13783 );
13784 }
13785 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv, fctx);
13786 Ok(())
13787}
13788
13789thread_local! {
13790 /// lane-sb128c r8: INTRA (key-frame) 128x64 blocks decoded at the 128
13791 /// root's HORZ arm, and 64x128 ones at its VERT arm.
13792 pub(crate) static INTRA_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
13793 pub(crate) static INTRA_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
13794 /// Those blocks by resolved intra `tx_depth` (0 = TX_64X64 units,
13795 /// 1 = TX_32X32, 2 = TX_16X16) -- proof the depth symbol is really read.
13796 pub(crate) static INTRA_SB128_DEPTH_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
13797 /// lane-inter128intra r1: the same shapes decoded on the INTER block path
13798 /// (an intra-coded PARTITION_HORZ/VERT half of a 128 superblock inside an
13799 /// inter frame) -- (128x64, 64x128).
13800 pub(crate) static INTRA128_IN_INTER_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
13801 /// lane-t900 r17: skipped INTER blocks whose `read_block_tx_size` still
13802 /// handed back var-tx leaves, so the per-transform-unit luma publication
13803 /// loop never ran and the block has to clear its own luma coefficient
13804 /// contexts (libaom `av1_reset_entropy_context`). Every 128 root under
13805 /// `TX_MODE_LARGEST` is one; the counter is what keeps that reset's gate
13806 /// non-vacuous.
13807 pub(crate) static SKIP_VARTX_LUMA_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
13808}
13809
13810/// [`SKIP_VARTX_LUMA_RESET_HITS`], for a gate's own before/after delta.
13811pub fn skip_vartx_luma_reset_hits() -> usize {
13812 SKIP_VARTX_LUMA_RESET_HITS.with(std::cell::Cell::get)
13813}
13814
13815/// [`INTRA128_IN_INTER_HITS`], for a gate's own before/after delta.
13816pub(crate) fn intra128_in_inter_hits() -> [usize; 2] {
13817 INTRA128_IN_INTER_HITS.with(std::cell::Cell::get)
13818}
13819
13820/// [`INTRA_SB128_HORZ_HITS`] / [`INTRA_SB128_VERT_HITS`] /
13821/// [`INTRA_SB128_DEPTH_HITS`], for a gate's own before/after delta.
13822pub(crate) fn intra_sb128_hits() -> (usize, usize, [usize; 3]) {
13823 (
13824 INTRA_SB128_HORZ_HITS.with(std::cell::Cell::get),
13825 INTRA_SB128_VERT_HITS.with(std::cell::Cell::get),
13826 INTRA_SB128_DEPTH_HITS.with(std::cell::Cell::get),
13827 )
13828}
13829
13830/// The 128 root's HORZ/VERT arm on an INTRA frame: ONE 128x64 (HORZ) or
13831/// 64x128 (VERT) intra block (lane-sb128c r8; the inter twin is
13832/// `decode_inter_block`'s own rect path).
13833///
13834/// libaom `decode_block` -> `predict_and_reconstruct_intra_block` per
13835/// transform unit, with the 128-specific geometry:
13836/// * `max_txsize_rect_lookup[BLOCK_128X64]` is TX_64X64, so every luma unit
13837/// is SQUARE and there are at least two of them -- depth 0: 64x64 x2,
13838/// depth 1: 32x32 x8, depth 2: 16x16 x32 (`bsize_to_tx_size_cat` counts
13839/// the `sub_tx_size_map` chain TX_64X64->32->16->8->4, i.e. cat 3, the
13840/// same CDF a 64x64 square block reads).
13841/// * `av1_get_max_uv_txsize` = `av1_get_adjusted_tx_size(
13842/// max_txsize_rect_lookup[BLOCK_64X32])` caps at TX_32X32, so the block's
13843/// 64x32 uv plane block is TWO 32x32 chroma units per plane -- one per
13844/// 64x64 luma "mu" chunk, and `decode_token_recon_block` codes Y, U, V of
13845/// a chunk before moving to the next (the interleave lane-sb128b r3
13846/// measured at the 128x128 NONE root).
13847/// * `get_txb_ctx`: the uv plane block is bigger than the uv transform, so
13848/// chroma `txb_skip_ctx` takes the offset-10 rows (7 + 3).
13849/// No CfL, no filter intra (both cap at 32x32) and no palette
13850/// (`av1_allow_palette` caps at 64x64) exist at this size -- the mode
13851/// reader's own size gates already say so, and the guard below is defensive.
13852#[allow(clippy::too_many_arguments)]
13853fn decode_block_128rect(
13854 dec: &mut SymbolDecoder,
13855 cdfs: &mut Cdfs,
13856 neighbours: &mut Neighbours,
13857 at: (usize, usize),
13858 bw: usize,
13859 bh: usize,
13860 y: &mut PlaneBuf<'static>,
13861 u: &mut PlaneBuf<'static>,
13862 v: &mut PlaneBuf<'static>,
13863 base_q_idx: u8,
13864 enable_filter_intra: bool,
13865 allow_screen_content_tools: bool,
13866 tx_select: bool,
13867 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
13868) -> Result<()> {
13869 let (r, c) = at;
13870 let (px, py) = (c * SUB, r * SUB);
13871 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
13872 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
13873 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
13874 let palette_uv_cache = neighbours.palette_uv_cache(at);
13875 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
13876 read_intra_mode_rect(
13877 dec,
13878 cdfs,
13879 nb_above_mode,
13880 nb_left_mode,
13881 // `is_cfl_allowed` caps CFL at 32x32: `uv_mode` comes off the
13882 // 13-symbol no-CFL CDF here, never the 14-symbol one.
13883 false,
13884 true,
13885 bw,
13886 bh,
13887 enable_filter_intra,
13888 neighbours.skip_txfm_ctx(mi_r, mi_c),
13889 allow_screen_content_tools,
13890 Some((palette_ctx, &palette_cache)),
13891 &palette_uv_cache,
13892 mi_r,
13893 mi_c, fctx,
13894 )?;
13895 if alpha.is_some() || filter_intra.is_some() || palette_y.is_some() || palette_uv.is_some() {
13896 return Err(unsupported(
13897 "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of \
13898 their size gates caps at 64x64 or below, so none of these symbols exists there)",
13899 ));
13900 }
13901 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
13902 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
13903 if smooth_neighbor {
13904 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
13905 }
13906 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
13907 // spec 5.11.16 `read_tx_size`: read for every intra block, skipped or
13908 // not. `bsize_to_tx_size_cat(BLOCK_128X64)` is 3 (see this fn's doc).
13909 let in_inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some();
13910 let depth = if tx_select {
13911 // lane-inter128intra r1: on an INTER frame `get_tx_size_context` reads
13912 // the real `TXFM_CONTEXT` bands, and compares them against
13913 // `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` -- TX_64X64 for
13914 // every 128-axis block, hence the `min(64)`.
13915 let ctx = if in_inter {
13916 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx)
13917 } else {
13918 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
13919 };
13920 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
13921 } else {
13922 0
13923 };
13924 if depth != 0 {
13925 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
13926 }
13927 INTRA_SB128_DEPTH_HITS.with(|c| {
13928 let mut h = c.get();
13929 h[depth.min(2)] += 1;
13930 c.set(h);
13931 });
13932 let logical_tx = 64 >> depth;
13933 // A 64-point transform codes nothing past its low 32 coefficients.
13934 let coeff_tx_side = logical_tx.min(32);
13935 let luma_set = txbset_for(logical_tx, reduced_tx_set);
13936 let luma_scan = default_scan(coeff_tx_side);
13937 let chroma_tx = 32;
13938 let chroma_scan = default_scan(chroma_tx);
13939 let (cpx, cpy) = (px / 2, py / 2);
13940 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
13941 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
13942 let (nch_x, nch_y) = (bw / 64, bh / 64);
13943 // One 32x32 chroma unit per mu chunk, per plane.
13944 debug_assert_eq!((chroma_w / chroma_tx, chroma_h / chroma_tx), (nch_x, nch_y));
13945 let tpc = 64 / logical_tx;
13946 let zero_tu = vec![0i32; logical_tx * logical_tx];
13947 let zero_cu = vec![0i32; chroma_tx * chroma_tx];
13948 let mut last_grids = [Vec::new(), Vec::new()];
13949 let mut units: Vec<((usize, usize), Vec<i32>, Vec<i32>)> = Vec::new();
13950 for ch_row in 0..nch_y {
13951 for ch_col in 0..nch_x {
13952 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
13953 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
13954 let tu_mi = (
13955 mi_r + tu_row * (logical_tx / MI),
13956 mi_c + tu_col * (logical_tx / MI),
13957 );
13958 let (tu_px, tu_py) = (px + tu_col * logical_tx, py + tu_row * logical_tx);
13959 // libaom clips the transform loop to
13960 // `max_blocks_wide/high`: a unit whose top-left sample is
13961 // outside the frame is never coded.
13962 if tu_px >= y.true_width || tu_py >= y.true_height {
13963 continue;
13964 }
13965 // Edge availability of a unit INSIDE a block, with the
13966 // 128 geometry -- `has_top_right` is false for a block
13967 // whose largest side is > 64, which [`Reach::of_rect`]
13968 // already answered for the block and [`tu_reach`] carries
13969 // down to the units on its own top row.
13970 let tu_r = tu_reach(
13971 bw,
13972 bh,
13973 tu_col * logical_tx,
13974 tu_row * logical_tx,
13975 logical_tx,
13976 reach,
13977 px,
13978 py,
13979 y.width,
13980 y.height, fctx,
13981 );
13982 if skip {
13983 push_intra(0,
13984 tu_px, tu_py, logical_tx, mode, angle_delta_y, tu_r, &zero_tu, None,
13985 None, smooth_neighbor, fctx,
13986 );
13987 neighbours.record_mi_luma(tu_mi, logical_tx, &zero_tu);
13988 continue;
13989 }
13990 // The unit is smaller than its block, so `txb_skip_ctx`
13991 // is the neighbour-magnitude table, never the lone-TU 0.
13992 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
13993 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
13994 let tu_grid = read_plane(
13995 dec,
13996 cdfs,
13997 luma_set,
13998 &luma_scan,
13999 0,
14000 tu_around,
14001 mode,
14002 mode,
14003 angle_delta_y,
14004 tu_r,
14005 y,
14006 tu_px,
14007 tu_py,
14008 logical_tx,
14009 coeff_tx_side,
14010 base_q_idx,
14011 None,
14012 None,
14013 Some(tu_skip_ctx),
14014 smooth_neighbor, fctx,
14015 )?;
14016 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
14017 }
14018 }
14019 // The chroma context arrays are indexed in LUMA mi, so this
14020 // unit's anchor is its own 64x64 mu chunk.
14021 let luma_span = chroma_tx * 2;
14022 let cu_mi = (
14023 mi_r + ch_row * (luma_span / MI),
14024 mi_c + ch_col * (luma_span / MI),
14025 );
14026 let cu_r = tu_reach(
14027 bw,
14028 bh,
14029 ch_col * luma_span,
14030 ch_row * luma_span,
14031 luma_span,
14032 reach,
14033 px,
14034 py,
14035 y.width,
14036 y.height, fctx,
14037 );
14038 let (cu_x, cu_y) = (cpx + ch_col * chroma_tx, cpy + ch_row * chroma_tx);
14039 if skip {
14040 push_intra(1,
14041 cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r, &zero_cu, None,
14042 None, smooth_neighbor_uv, fctx,
14043 );
14044 push_intra(2,
14045 cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r, &zero_cu, None,
14046 None, smooth_neighbor_uv, fctx,
14047 );
14048 continue;
14049 }
14050 let cu_around = neighbours.around_mi(cu_mi, luma_span);
14051 let u_grid = read_plane(
14052 dec, cdfs, TxbSet::Chroma32, &chroma_scan, 1, cu_around[1], mode, uv_predict_mode,
14053 angle_delta_uv, cu_r, u, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, None, None,
14054 Some(3), smooth_neighbor_uv, fctx,
14055 )?;
14056 let v_grid = read_plane(
14057 dec, cdfs, TxbSet::Chroma32, &chroma_scan, 2, cu_around[2], mode, uv_predict_mode,
14058 angle_delta_uv, cu_r, v, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, None, None,
14059 Some(3), smooth_neighbor_uv, fctx,
14060 )?;
14061 CHROMA_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
14062 // Immediately, so the NEXT unit of this same block reads this
14063 // one's coefficient context; replayed after `record_split_luma_rect`
14064 // below, which would otherwise clobber them whole-block.
14065 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 1, &u_grid);
14066 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 2, &v_grid);
14067 units.push((cu_mi, u_grid.clone(), v_grid.clone()));
14068 last_grids = [u_grid, v_grid];
14069 }
14070 }
14071 if skip {
14072 neighbours.record_rect(
14073 at,
14074 bw,
14075 bh,
14076 mode,
14077 uv_predict_mode,
14078 &[
14079 vec![0i32; bw * bh],
14080 vec![0i32; chroma_w * chroma_h],
14081 vec![0i32; chroma_w * chroma_h],
14082 ],
14083 );
14084 } else {
14085 neighbours.record_split_luma_rect(
14086 at,
14087 bw,
14088 bh,
14089 mode,
14090 uv_predict_mode,
14091 [&last_grids[0], &last_grids[1]],
14092 );
14093 for (cu_mi, u_grid, v_grid) in &units {
14094 neighbours.record_mi_chroma(*cu_mi, 64, 64, 1, u_grid);
14095 neighbours.record_mi_chroma(*cu_mi, 64, 64, 2, v_grid);
14096 }
14097 }
14098 // No palette exists at this size; the unconditional stamp clears any
14099 // stale neighbour palette state, as every other block path does.
14100 neighbours.record_palette_y_rect(at, bw, bh, 0, [0u16; 8]);
14101 neighbours.record_palette_uv_rect(at, bw, bh, 0, [0u16; 8]);
14102 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
14103 neighbours.fill_lf_grid_rect(
14104 (mi_r, mi_c),
14105 bw / MI,
14106 bh / MI,
14107 logical_tx as u8,
14108 logical_tx as u8,
14109 0, fctx,
14110 );
14111 if in_inter {
14112 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)`
14113 // (libaom `decodeframe.c` `decode_block`) runs for EVERY block of an
14114 // inter frame, intra ones included: an intra block stamps its
14115 // TRANSFORM size over its own footprint in both TXFM_CONTEXT bands.
14116 // A key frame has no var-tx tree and its readers use the deblock grid,
14117 // so this is the inter path's alone.
14118 txfm_partition_update_rect(
14119 neighbours,
14120 (mi_r, mi_c),
14121 (logical_tx, logical_tx),
14122 (bw, bh),
14123 );
14124 INTRA128_IN_INTER_HITS.with(|c| {
14125 let mut h = c.get();
14126 h[usize::from(bw < bh)] += 1;
14127 c.set(h);
14128 });
14129 } else if bw > bh {
14130 INTRA_SB128_HORZ_HITS.with(|c| c.set(c.get() + 1));
14131 } else {
14132 INTRA_SB128_VERT_HITS.with(|c| c.set(c.get() + 1));
14133 }
14134 Ok(())
14135}
14136
14137
14138/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
14139/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
14140/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
14141/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
14142/// just-decoded mode, not the enclosing slot's stale one, is the true
14143/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
14144/// units, which is what its coefficient context (finer than [`SUB`]) is read
14145/// at. Returns the mode this leaf decoded, for the caller's own
14146/// `prev_leaf`/final mode-writeback bookkeeping.
14147#[allow(clippy::too_many_arguments)]
14148/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
14149/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
14150/// `above_mode[col]`, and its true above neighbour is the mi directly above
14151/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
14152/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
14153/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
14154/// (bottom-right) into both, as this path did, is right only when all four
14155/// leaves happen to share a mode. `done` may be short at the true frame edge
14156/// (the straddle caller filters positions off the frame), so each side falls
14157/// back to the last leaf actually decoded.
14158fn write_back_split_modes(
14159 neighbours: &mut Neighbours,
14160 done: &[((usize, usize), usize)],
14161 parent_mi: (usize, usize),
14162 slot: (usize, usize),
14163) {
14164 let (sr, sc) = slot;
14165 let Some(&(_, last)) = done.last() else {
14166 return;
14167 };
14168 let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m);
14169 neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last);
14170 neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last);
14171}
14172
14173fn decode_leaf8(
14174 dec: &mut SymbolDecoder,
14175 cdfs: &mut Cdfs,
14176 neighbours: &mut Neighbours,
14177 outer_at: (usize, usize),
14178 leaf_mi: (usize, usize),
14179 scans: (&[u16], &[u16]),
14180 prev_leaf: Option<((usize, usize), usize)>,
14181 y: &mut PlaneBuf<'static>,
14182 u: &mut PlaneBuf<'static>,
14183 v: &mut PlaneBuf<'static>,
14184 base_q_idx: u8,
14185 enable_filter_intra: bool,
14186 allow_screen_content_tools: bool,
14187 allow_intrabc: bool,
14188 tx_select: bool,
14189 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
14190) -> Result<usize> {
14191 let (r, c) = outer_at;
14192 // lane-modectx r1: the group's own availability-correct fallback pair, not
14193 // the raw coarse bands (which leak across a tile edge -- see
14194 // `modes_above_left`).
14195 let (mut above_mode, mut left_mode) = neighbours.modes_above_left(r, c);
14196 if let Some(((pr, pc), pmode)) = prev_leaf {
14197 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
14198 above_mode = pmode;
14199 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
14200 left_mode = pmode;
14201 }
14202 }
14203 // The mi-exact neighbour wins over both the coarse 16x16 slot and
14204 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
14205 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
14206 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
14207 // lane-rectsplitx r2 swept this arm into
14208 // [`Neighbours::modes_above_left_mi`]: the mi-exact map ALSO has to answer
14209 // "no neighbour" at a tile edge, where the coarse cell holds the block
14210 // above/left of it inside the same 16x16.
14211 let (above_mode, left_mode) =
14212 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
14213 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
14214 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
14215 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
14216 // this leaf's `smooth_neighbor` is built from -- passing `false` here
14217 // filtered a directional chroma block's edge at the wrong strength
14218 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
14219 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
14220 // with the coarse [`SUB`] slot as the fallback when no block recorded
14221 // that exact mi cell.
14222 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
14223 if smooth_neighbor {
14224 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
14225 }
14226 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
14227 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
14228 // `decode_block` caller at 16x16 and up.
14229 // lane-pal8 r1: this leaf's own palette-Y mode ctx and colour cache
14230 // (`av1_get_palette_mode_ctx` / `av1_get_palette_cache`, decodemv.c:567,
14231 // `read_palette_mode_info`), at its REAL mi position -- passing
14232 // `None`/`&[]` read `palette_y_mode` off CDF row 0 and refused by name the
14233 // moment a real 8x8 palette block fired, which is where every 8-bit
14234 // `--tune-content=screen --min-partition-size=8` stream stopped.
14235 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(leaf_mi);
14236 let palette_uv_cache = neighbours.palette_uv_cache_mi(leaf_mi);
14237 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
14238 read_intra_mode(
14239 dec,
14240 cdfs,
14241 above_mode,
14242 left_mode,
14243 true,
14244 8,
14245 enable_filter_intra,
14246 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
14247 allow_screen_content_tools,
14248 allow_intrabc,
14249 Some((palette_ctx, &palette_cache)),
14250 &palette_uv_cache,
14251 leaf_mi.0,
14252 leaf_mi.1, fctx,
14253 )?;
14254 // lane-kf900 r7: an 8x8 leaf consumed `use_intrabc` (and its DV) through
14255 // `read_intra_mode` and then decoded the block as if it were ordinary
14256 // intra. libaom's `is_inter_block` counts an intrabc block
14257 // (`blockd.h:373`), so its luma `tx_type` comes off the INTER ext-tx set
14258 // (`av1_get_ext_tx_set_type(TX_8X8, is_inter=1, 0)` = `EXT_TX_SET_ALL16`,
14259 // a 16-symbol CDF) while we read the 7-symbol `TX_SET_INTRA_1` row: the
14260 // same value with a different interval, so the tile desynced at the very
14261 // next symbol (class `wrong-alphabet-same-value`). Everything below
14262 // mirrors `decode_block`'s own intrabc handling at 16x16 and up.
14263 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
14264 if intrabc_dv.is_some() {
14265 LEAF8_INTRABC_HITS.with(|c| c.set(c.get() + 1));
14266 }
14267 // `av1_visit_palette`'s reconstruction (decodeframe.c:1135): the colour
14268 // index map, mapped through the base colours, IS the block's prediction --
14269 // carried to the next `reconstruct`/`read_plane` through the same
14270 // [`PALETTE_PRED`] slot [`decode_block`] uses at 16x16 and up.
14271 let palette_y_buf: Option<Vec<u16>> = palette_y
14272 .as_ref()
14273 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
14274 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
14275 (
14276 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
14277 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
14278 )
14279 });
14280 let (pal_y_size, pal_y_colors) =
14281 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
14282 let (pal_uv_size, pal_uv_colors) =
14283 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
14284 if palette_y.is_some() || palette_uv.is_some() {
14285 PALETTE_LEAF8_HITS.with(|c| c.set(c.get() + 1));
14286 }
14287 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
14288 DC_PRED
14289 } else {
14290 uv_mode
14291 };
14292 neighbours.above_uv_mode[c] = uv_predict_mode;
14293 neighbours.left_uv_mode[r] = uv_predict_mode;
14294 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
14295 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
14296 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
14297 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
14298 // transform units, same raster-order per-TU pattern `decode_block`'s
14299 // multi-TU branch runs).
14300 // ... and an intrabc leaf reads no intra `tx_depth` symbol at all: libaom
14301 // dispatches `read_block_tx_size` on `is_inter_block`, which counts an
14302 // intrabc block, so a SKIPPED one takes the largest transform and an
14303 // UNSKIPPED one reads the inter var-tx tree (lane-t900 r32). At 8x8 that
14304 // tree is one `txfm_split` symbol: TX_8X8, or TX_4X4 over all four mi
14305 // cells (`read_var_tx_size`'s `sub_txs == TX_4X4` early return).
14306 let resolved = if tx_select && intrabc_dv.is_some() && !skip {
14307 let mut leaves = Vec::new();
14308 let mi_cols = 2 * y.true_width.div_ceil(8);
14309 let mi_rows = 2 * y.true_height.div_ceil(8);
14310 read_var_tx_size(
14311 dec,
14312 cdfs,
14313 neighbours,
14314 leaf_mi,
14315 8,
14316 (
14317 2usize.min(mi_cols.saturating_sub(leaf_mi.1)),
14318 2usize.min(mi_rows.saturating_sub(leaf_mi.0)),
14319 ),
14320 (8, 8),
14321 0,
14322 0,
14323 0,
14324 &mut leaves,
14325 );
14326 INTRABC_VARTX_HITS.with(|c| c.set(c.get() + 1));
14327 leaves.first().map_or(8, |l| l.2)
14328 } else if tx_select && intrabc_dv.is_none() {
14329 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, None)
14330 } else {
14331 8
14332 };
14333 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
14334 let reach = Reach::of(8, px, py, y.width, y.height, fctx);
14335 let (cpx, cpy) = (px / 2, py / 2);
14336 // spec 7.11.3.4 with `use_intrabc`, same as `decode_block`: predict from
14337 // the CURRENT frame's own pre-loop-filter reconstruction (every loop
14338 // filter is off whenever `allow_intrabc`, frame.rs:194/210/252/272) at
14339 // the full-pel block vector, with the BILINEAR kernel libaom forces.
14340 flush_recon(fctx, y, u, v);
14341 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
14342 let mut yb = vec![0u16; 8 * 8];
14343 mc::predict_with_filter(
14344 &y.data, y.width, y.true_width, y.true_height,
14345 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
14346 8, 8, mc::InterpFilterKind::Bilinear, &mut yb, fctx,
14347 );
14348 let mut ub = vec![0u16; 4 * 4];
14349 mc::predict_with_filter(
14350 &u.data, u.width, u.true_width, u.true_height,
14351 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
14352 4, 4, mc::InterpFilterKind::Bilinear, &mut ub, fctx,
14353 );
14354 let mut vb = vec![0u16; 4 * 4];
14355 mc::predict_with_filter(
14356 &v.data, v.width, v.true_width, v.true_height,
14357 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
14358 4, 4, mc::InterpFilterKind::Bilinear, &mut vb, fctx,
14359 );
14360 (yb, ub, vb)
14361 });
14362 // The per-plane prediction override rides the same [`PALETTE_PRED`] slot
14363 // `decode_block` uses: set fresh right before each plane's own
14364 // `reconstruct`/`read_plane` call (the slot is taken, not copied).
14365 // lane-t900 r32: through `palette_y_buf`, so the 4x4 TU loop below windows
14366 // it per unit (an intrabc leaf whose var-tx tree split to TX_4X4 is the
14367 // first shape that reaches that loop with an override set).
14368 let palette_y_buf = match &intrabc_bufs {
14369 Some((yb, _, _)) => Some(yb.clone()),
14370 None => palette_y_buf,
14371 };
14372 let (luma_grid, u_grid, v_grid);
14373 if skip {
14374 // lane-hgkf r2 (same shape as `decode_block`'s own skip branch): an
14375 // 8x8 leaf whose `tx_depth` resolved to TX_4X4 predicts FOUR 4x4
14376 // transform units, each off the units already written left/above of
14377 // it inside this same leaf -- an intra block's transform size is read
14378 // whether or not it is skipped, and spec 7.11.2 predicts per unit.
14379 // A palette block's prediction is the whole-block index map, never
14380 // per-transform-unit edges ([`decode_block`]'s own `split_tx_skip`
14381 // rule) -- so a palette leaf takes the single 8x8 reconstruct below
14382 // even when `tx_depth` resolved to TX_4X4.
14383 if resolved == 4 && palette_y_buf.is_none() {
14384 SKIP_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
14385 for tu_row in 0..2 {
14386 for tu_col in 0..2 {
14387 let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4);
14388 if tu_px >= y.true_width || tu_py >= y.true_height {
14389 continue;
14390 }
14391 let tu_reach = tu_reach(
14392 8,
14393 8,
14394 tu_col * 4,
14395 tu_row * 4,
14396 4,
14397 reach,
14398 px,
14399 py,
14400 y.width,
14401 y.height, fctx,
14402 );
14403 push_intra(0,
14404 tu_px,
14405 tu_py,
14406 4,
14407 mode,
14408 angle_delta_y,
14409 tu_reach,
14410 &vec![0i32; 16],
14411 None,
14412 filter_intra,
14413 smooth_neighbor, fctx,
14414 );
14415 }
14416 }
14417 } else {
14418 if let Some(buf) = &palette_y_buf {
14419 set_palette_pred(buf.clone(), fctx);
14420 }
14421 push_intra(0,
14422 px,
14423 py,
14424 8,
14425 mode,
14426 angle_delta_y,
14427 reach,
14428 &vec![0i32; 64],
14429 None,
14430 filter_intra,
14431 smooth_neighbor, fctx,
14432 );
14433 }
14434 let ac = alpha.map(|_| cfl_src(px, py, 8));
14435 if let Some((_, ub, _)) = &intrabc_bufs {
14436 set_palette_pred(ub.clone(), fctx);
14437 } else if let Some((ub, _)) = &palette_uv_bufs {
14438 set_palette_pred(ub.clone(), fctx);
14439 }
14440 push_intra(1,
14441 cpx,
14442 cpy,
14443 4,
14444 uv_predict_mode,
14445 angle_delta_uv,
14446 reach,
14447 &vec![0i32; 16],
14448 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
14449 None,
14450 smooth_neighbor_uv, fctx,
14451 );
14452 if let Some((_, _, vb)) = &intrabc_bufs {
14453 set_palette_pred(vb.clone(), fctx);
14454 } else if let Some((_, vb)) = &palette_uv_bufs {
14455 set_palette_pred(vb.clone(), fctx);
14456 }
14457 push_intra(2,
14458 cpx,
14459 cpy,
14460 4,
14461 uv_predict_mode,
14462 angle_delta_uv,
14463 reach,
14464 &vec![0i32; 16],
14465 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
14466 None,
14467 smooth_neighbor_uv, fctx,
14468 );
14469 luma_grid = vec![0i32; 64];
14470 u_grid = vec![0i32; 16];
14471 v_grid = vec![0i32; 16];
14472 } else if resolved != 4 {
14473 let around = neighbours.around_mi(leaf_mi, 8);
14474 if let Some(buf) = &palette_y_buf {
14475 set_palette_pred(buf.clone(), fctx);
14476 }
14477 luma_grid = read_plane(
14478 dec,
14479 cdfs,
14480 if intrabc_dv.is_some() {
14481 txbset_for_inter(8, reduced_tx_set)
14482 } else if reduced_tx_set {
14483 TxbSet::Luma8
14484 } else {
14485 TxbSet::Luma8Set1
14486 },
14487 scans.0,
14488 0,
14489 around[0],
14490 mode,
14491 mode,
14492 angle_delta_y,
14493 reach,
14494 y,
14495 px,
14496 py,
14497 8,
14498 TX8,
14499 base_q_idx,
14500 None,
14501 filter_intra,
14502 None,
14503 smooth_neighbor, fctx,
14504 )?;
14505 // `av1_get_tx_type` branches `PLANE_TYPE_UV` on `is_inter_block`, so
14506 // an intrabc block's chroma tx_type is the colocated LUMA transform's
14507 // coded type (lane-kf900 r6's own fix, `decode_block`'s line).
14508 if intrabc_dv.is_some() {
14509 fctx.intrabc_chroma_tx.with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
14510 }
14511 let ac = alpha.map(|_| cfl_src(px, py, 8));
14512 if let Some((_, ub, _)) = &intrabc_bufs {
14513 set_palette_pred(ub.clone(), fctx);
14514 } else if let Some((ub, _)) = &palette_uv_bufs {
14515 set_palette_pred(ub.clone(), fctx);
14516 }
14517 u_grid = read_plane(
14518 dec,
14519 cdfs,
14520 TxbSet::Chroma4,
14521 scans.1,
14522 1,
14523 around[1],
14524 mode,
14525 uv_predict_mode,
14526 angle_delta_uv,
14527 reach,
14528 u,
14529 cpx,
14530 cpy,
14531 4,
14532 TX4,
14533 base_q_idx,
14534 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
14535 None,
14536 None,
14537 smooth_neighbor_uv, fctx,
14538 )?;
14539 if let Some((_, _, vb)) = &intrabc_bufs {
14540 set_palette_pred(vb.clone(), fctx);
14541 } else if let Some((_, vb)) = &palette_uv_bufs {
14542 set_palette_pred(vb.clone(), fctx);
14543 }
14544 v_grid = read_plane(
14545 dec,
14546 cdfs,
14547 TxbSet::Chroma4,
14548 scans.1,
14549 2,
14550 around[2],
14551 mode,
14552 uv_predict_mode,
14553 angle_delta_uv,
14554 reach,
14555 v,
14556 cpx,
14557 cpy,
14558 4,
14559 TX4,
14560 base_q_idx,
14561 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
14562 None,
14563 None,
14564 smooth_neighbor_uv, fctx,
14565 )?;
14566 // Disarm: `INTRABC_CHROMA_TX` is `Some` across exactly this block's
14567 // two chroma reads (`decode_block`'s own tail does the same) -- left
14568 // set, every later chroma block would inherit this luma tx_type,
14569 // which picks the scan and the inverse transform.
14570 fctx.intrabc_chroma_tx.with(|c| c.set(None));
14571 } else {
14572 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
14573 // grid of 4x4 transform units, each predicted from the leaf's own
14574 // 8x8 `mode` and reading its own fresh context off the earlier
14575 // units in this same leaf (the same per-TU pattern `decode_block`'s
14576 // multi-TU branch runs at bigger blocks).
14577 for tu_row in 0..2 {
14578 for tu_col in 0..2 {
14579 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
14580 let tu_px = px + tu_col * 4;
14581 let tu_py = py + tu_row * 4;
14582 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
14583 if crate::encode::Reach::in_vert_ab() {
14584 VERT_AB_TX4_HITS.with(|c| c.set(c.get() + 1));
14585 }
14586 let tu_reach = tu_reach(
14587 8,
14588 8,
14589 tu_col * 4,
14590 tu_row * 4,
14591 4,
14592 reach,
14593 px,
14594 py,
14595 y.width,
14596 y.height, fctx,
14597 );
14598 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
14599 // Each 4x4 unit predicts from its own window of the block's
14600 // 8x8 colour-index map ([`decode_block`]'s per-TU slice at
14601 // 16x16 and up) -- the whole-block buffer would be taken by
14602 // the FIRST unit and indexed at the wrong stride.
14603 if let Some(buf) = &palette_y_buf {
14604 PALETTE_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
14605 let mut window = vec![0u16; 16];
14606 for row in 0..4 {
14607 let src = (tu_row * 4 + row) * 8 + tu_col * 4;
14608 window[row * 4..][..4].copy_from_slice(&buf[src..][..4]);
14609 }
14610 set_palette_pred(window, fctx);
14611 }
14612 let tu_grid = read_plane(
14613 dec,
14614 cdfs,
14615 if intrabc_dv.is_some() {
14616 txbset_for_inter(4, reduced_tx_set)
14617 } else if reduced_tx_set {
14618 TxbSet::Luma4
14619 } else {
14620 TxbSet::Luma4Set1
14621 },
14622 scans.1,
14623 0,
14624 tu_around,
14625 mode,
14626 mode,
14627 angle_delta_y,
14628 tu_reach,
14629 y,
14630 tu_px,
14631 tu_py,
14632 4,
14633 4,
14634 base_q_idx,
14635 None,
14636 filter_intra,
14637 Some(tu_skip_ctx),
14638 smooth_neighbor, fctx,
14639 )?;
14640 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14641 eprintln!(
14642 "TRACE tu_bitpos mi=({},{}) tell={}",
14643 tu_mi.0,
14644 tu_mi.1,
14645 dec.debug_bitpos()
14646 );
14647 }
14648 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
14649 }
14650 }
14651 let ac = alpha.map(|_| cfl_src(px, py, 8));
14652 let chroma_around = neighbours.around_mi(leaf_mi, 8);
14653 if let Some((ub, _)) = &palette_uv_bufs {
14654 set_palette_pred(ub.clone(), fctx);
14655 }
14656 u_grid = read_plane(
14657 dec,
14658 cdfs,
14659 TxbSet::Chroma4,
14660 scans.1,
14661 1,
14662 chroma_around[1],
14663 mode,
14664 uv_predict_mode,
14665 angle_delta_uv,
14666 reach,
14667 u,
14668 cpx,
14669 cpy,
14670 4,
14671 TX4,
14672 base_q_idx,
14673 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
14674 None,
14675 None,
14676 smooth_neighbor_uv, fctx,
14677 )?;
14678 if let Some((_, vb)) = &palette_uv_bufs {
14679 set_palette_pred(vb.clone(), fctx);
14680 }
14681 v_grid = read_plane(
14682 dec,
14683 cdfs,
14684 TxbSet::Chroma4,
14685 scans.1,
14686 2,
14687 chroma_around[2],
14688 mode,
14689 uv_predict_mode,
14690 angle_delta_uv,
14691 reach,
14692 v,
14693 cpx,
14694 cpy,
14695 4,
14696 TX4,
14697 base_q_idx,
14698 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
14699 None,
14700 None,
14701 smooth_neighbor_uv, fctx,
14702 )?;
14703 // `record_split_luma` expects a `record`-style `(r, c)` position in
14704 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
14705 // already in mi units, so calling it here double-scaled the
14706 // position. Plane 0 is already correct per-TU from the
14707 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
14708 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
14709 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
14710 // leaf's own 8x8 side over `MI`).
14711 let side_mi = 2;
14712 for cell in 0..side_mi {
14713 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
14714 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
14715 }
14716 let round_up_even = |n: usize| n.div_ceil(2) * 2;
14717 let bound_h = round_up_even(neighbours.mi_rows);
14718 let bound_w = round_up_even(neighbours.mi_cols);
14719 let u_state = neighbour_state(&u_grid);
14720 let v_state = neighbour_state(&v_grid);
14721 for cell in 0..side_mi {
14722 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
14723 neighbours.left[leaf_mi.0 + cell][1] = u_state;
14724 neighbours.left[leaf_mi.0 + cell][2] = v_state;
14725 }
14726 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
14727 neighbours.above[leaf_mi.1 + cell][1] = u_state;
14728 neighbours.above[leaf_mi.1 + cell][2] = v_state;
14729 }
14730 }
14731 // This leaf's own palette state into the mi-granular above/left bands
14732 // (sizes 0 when it used none, which is what clears a previous block's
14733 // palette out of the next block's ctx and colour cache).
14734 {
14735 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
14736 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
14737 }
14738 neighbours.fill_skip_grid(leaf_mi, 2, skip);
14739 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0, fctx);
14740 // lane-t900 r32: `set_txfm_ctxs` for an 8x8 leaf -- see `decode_block`'s
14741 // own copy; only an intrabc var-tx read consumes these bands on the intra
14742 // path, so the write is armed by `allow_intrabc`.
14743 if allow_intrabc {
14744 set_txfm_ctxs(neighbours, leaf_mi, 4, 2, 2, skip && intrabc_dv.is_some());
14745 }
14746 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
14747 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, fctx);
14748 return Ok(mode);
14749 }
14750 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
14751 // This leaf's own palette state into the mi-granular above/left bands
14752 // (sizes 0 when it used none, which is what clears a previous block's
14753 // palette out of the next block's ctx and colour cache).
14754 {
14755 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
14756 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
14757 }
14758 INTER8_SKIP_BAND_HITS.with(|c| c.set(c.get() + 1));
14759 neighbours.fill_skip_grid(leaf_mi, 2, skip);
14760 // lane-kf900 r1: the leaf's own RESOLVED transform size, never the literal
14761 // block side. libaom calls `set_txfm_ctxs(mbmi->tx_size, ..., skip_txfm &&
14762 // is_inter_block(mbmi), xd)` (decodemv.c) -- for an INTRA block that skip
14763 // term is always 0, so a skipped 8x8 leaf whose `tx_depth` resolved to
14764 // TX_4X4 still publishes 4 to the next block's `get_tx_size_context`
14765 // (pred_common.h:342). Writing 8 here made the 8x16 strip below the leaf
14766 // read `tx_size_cat1` row 2 where libaom reads row 1 -- same alphabet,
14767 // wrong CDF row, so the msac range diverged mid-frame with no refusal
14768 // (class `wrong-alphabet-same-value`; the ReelB key frame at
14769 // -ss 900, first bad luma sample row 186 col 1803).
14770 neighbours.fill_lf_grid(leaf_mi, 2, resolved as u8, 0, fctx);
14771 // lane-t900 r32: `set_txfm_ctxs` for an 8x8 leaf -- see `decode_block`'s
14772 // own copy; only an intrabc var-tx read consumes these bands on the intra
14773 // path, so the write is armed by `allow_intrabc`.
14774 if allow_intrabc {
14775 set_txfm_ctxs(neighbours, leaf_mi, resolved, 2, 2, skip && intrabc_dv.is_some());
14776 }
14777 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
14778 // The DV predictor of a LATER intrabc block is the ordinary `INTRA_FRAME`
14779 // MV stack over this grid (`av1_find_mv_refs`), so an 8x8 leaf has to
14780 // publish its own cells exactly like `decode_block` does.
14781 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, fctx);
14782 Ok(mode)
14783}
14784
14785/// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf
14786/// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8`
14787/// bottom, where no partition symbol is read at all -- `decode_block` runs
14788/// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec
14789/// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always
14790/// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference`
14791/// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf
14792/// of the 2x2 4x4 group carries chroma syntax at all.
14793#[allow(clippy::too_many_arguments)]
14794fn read_intra_mode_sub8(
14795 dec: &mut SymbolDecoder,
14796 cdfs: &mut Cdfs,
14797 above_mode: usize,
14798 left_mode: usize,
14799 has_chroma: bool,
14800 enable_filter_intra: bool,
14801 // [`filter_intra_size_class_rect`] for the LEAF's own shape: 0 for a
14802 // `BLOCK_4X4` split leaf, 8/9 for a 4x8/8x4 rect leaf. Reading the flag
14803 // from the wrong row is the same VALUE with a different interval, so it
14804 // desyncs a block or two later, not here (class `wrong-alphabet-same-value`).
14805 fi_class: usize,
14806 skip_ctx: usize,
14807 allow_intrabc: bool,
14808 mi_r: usize,
14809 mi_c: usize, fctx: &crate::decode::FrameCtx,
14810) -> Result<(bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option<usize>)> {
14811 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
14812 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
14813 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sub8 rng={}", dec.debug_state().0);
14814 }
14815 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
14816 if trace {
14817 eprintln!("TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}", skip as i32, dec.debug_state().0);
14818 }
14819 maybe_read_cdef_idx(dec, mi_r, mi_c, skip, fctx);
14820 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
14821 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
14822 if allow_intrabc {
14823 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
14824 if use_intrabc {
14825 return Err(unsupported(
14826 "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)",
14827 ));
14828 }
14829 }
14830 let above_ctx = INTRA_MODE_CTX[above_mode];
14831 let left_ctx = INTRA_MODE_CTX[left_mode];
14832 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
14833 if trace {
14834 eprintln!("TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
14835 }
14836 // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/
14837 // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`,
14838 // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta
14839 // symbol. Reading one consumed a symbol the encoder never wrote and
14840 // desynced the tile at the very next element.
14841 let angle_delta_y = 0;
14842 let chroma = if has_chroma {
14843 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
14844 if trace {
14845 eprintln!("TRACE sub8 uv_mode value={uv_mode} rng={}", dec.debug_state().0);
14846 }
14847 if (9..=12).contains(&uv_mode) {
14848 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
14849 }
14850 let alpha = if uv_mode == UV_CFL_PRED {
14851 Some(read_cfl_alphas(dec, cdfs))
14852 } else {
14853 None
14854 };
14855 if (V_PRED..=D67_PRED).contains(&uv_mode) {
14856 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
14857 }
14858 // See the luma comment above: no angle delta below 8x8.
14859 let angle_delta_uv = 0;
14860 Some((uv_mode, angle_delta_uv, alpha))
14861 } else {
14862 None
14863 };
14864 let mut filter_intra = None;
14865 if mode == DC_PRED && enable_filter_intra {
14866 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0;
14867 if trace {
14868 eprintln!("TRACE sub8 use_filter_intra value={}", use_filter_intra as i32);
14869 }
14870 if use_filter_intra {
14871 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
14872 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
14873 filter_intra = Some(fi_mode);
14874 }
14875 }
14876 Ok((skip, mode, angle_delta_y, chroma, filter_intra))
14877}
14878
14879/// Decodes a `PARTITION_SPLIT` of one 8x8 block into four `BLOCK_4X4` leaves
14880/// (spec `decode_partition`'s recursion bottom), sharing [`decode_leaf8`]'s
14881/// own signature so its caller's `prev_leaf`/`above_mode`/`left_mode`
14882/// bookkeeping needs no change. Each leaf reads its own luma mode info,
14883/// neighboured off the *previously decoded leaf in this same group* on
14884/// whichever axis is adjacent (mirroring [`decode_leaf8`]'s own `prev_leaf`
14885/// pattern, one level deeper); chroma is read and reconstructed exactly
14886/// once, on the last (bottom-right) leaf, at the whole 8x8 group's own 4x4
14887/// chroma unit -- [`read_intra_mode_sub8`]'s doc has the `is_chroma_reference`
14888/// derivation.
14889#[allow(clippy::too_many_arguments)]
14890fn decode_leaf_split4(
14891 dec: &mut SymbolDecoder,
14892 cdfs: &mut Cdfs,
14893 neighbours: &mut Neighbours,
14894 outer_at: (usize, usize),
14895 leaf_mi: (usize, usize),
14896 scan4: &[u16],
14897 prev_leaf: Option<((usize, usize), usize)>,
14898 y: &mut PlaneBuf<'static>,
14899 u: &mut PlaneBuf<'static>,
14900 v: &mut PlaneBuf<'static>,
14901 base_q_idx: u8,
14902 enable_filter_intra: bool,
14903 allow_intrabc: bool,
14904 reduced_tx_set: bool,
14905 // Returns `(below_mode, right_mode)`: the mode a neighbour BELOW this 8x8
14906 // group sees (its bottom-left 4x4, libaom reads mi(row-1, col)) and the
14907 // one a neighbour to its RIGHT sees (its top-right 4x4, mi(row, col-1))., fctx: &crate::decode::FrameCtx
14908 fctx: &crate::decode::FrameCtx,
14909) -> Result<(usize, usize)> {
14910 SUB8_SPLIT_HITS.with(|c| c.set(c.get() + 1));
14911 let (r, c) = outer_at;
14912 let mut above_mode = neighbours.above_mode[c];
14913 let mut left_mode = neighbours.left_mode[r];
14914 if let Some(((pr, pc), pmode)) = prev_leaf {
14915 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
14916 above_mode = pmode;
14917 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
14918 left_mode = pmode;
14919 }
14920 }
14921 // See `decode_leaf8`'s own `smooth_neighbor_uv`: the chroma edge-filter
14922 // type is the chroma neighbours' `uv_mode`, mi-exact where recorded.
14923 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
14924 let mut leaf_modes = [0usize; 4];
14925 let mut leaf_skips = [false; 4];
14926 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
14927 for i in 0..4usize {
14928 let (dr, dc) = (i / 2, i % 2);
14929 let lmi = (leaf_mi.0 + dr, leaf_mi.1 + dc);
14930 // Neighbour modes at real mi granularity: inside the group the
14931 // sibling leaf, outside it the split-leaf map when the adjacent mi
14932 // was itself a 4x4 leaf, else the coarse 16x16 slot (see
14933 // `sub8_mode_col`'s doc).
14934 let leaf_above = if dr == 0 {
14935 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
14936 } else {
14937 leaf_modes[i - 2]
14938 };
14939 let leaf_left = if dc == 0 {
14940 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
14941 } else {
14942 leaf_modes[i - 1]
14943 };
14944 let has_chroma = i == 3;
14945 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
14946 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
14947 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
14948 filter_intra_size_class(4).expect("BLOCK_4X4 has its own filter_intra row"),
14949 skip_ctx, allow_intrabc, lmi.0, lmi.1, fctx,
14950 )?;
14951 leaf_modes[i] = mode;
14952 leaf_skips[i] = skip;
14953 neighbours.record_mode_mi(lmi.0, lmi.1, 1, 1, mode);
14954 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
14955 if smooth_neighbor {
14956 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
14957 }
14958 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
14959 let reach = Reach::of(4, px, py, y.width, y.height, fctx);
14960 if skip {
14961 push_intra(0, px, py, 4, mode, angle_delta_y, reach, &vec![0i32; 16], None, filter_intra, smooth_neighbor, fctx);
14962 neighbours.record_mi_luma(lmi, 4, &vec![0i32; 16]);
14963 } else {
14964 let tu_around = neighbours.around_mi(lmi, 4)[0];
14965 // A `BLOCK_4X4` leaf's luma TU *is* the whole block, so libaom's
14966 // `get_txb_ctx` takes its `plane_bsize == txsize_to_bsize[tx_size]`
14967 // branch: `txb_skip_ctx = 0`, never the neighbour-magnitude table
14968 // (`txb_common.h:400`). Reading the table here decoded `all_zero`
14969 // off the wrong CDF on the very first leaf and desynced the tile.
14970 let tu_grid = read_plane(
14971 dec,
14972 cdfs,
14973 if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 },
14974 scan4,
14975 0,
14976 tu_around,
14977 mode,
14978 mode,
14979 angle_delta_y,
14980 reach,
14981 y,
14982 px,
14983 py,
14984 4,
14985 4,
14986 base_q_idx,
14987 None,
14988 filter_intra,
14989 None,
14990 smooth_neighbor, fctx,
14991 )?;
14992 neighbours.record_mi_luma(lmi, 4, &tu_grid);
14993 }
14994 neighbours.fill_skip_grid(lmi, 1, skip);
14995 neighbours.fill_lf_grid(lmi, 1, 4, 0, fctx);
14996 if has_chroma {
14997 last_uv = chroma;
14998 }
14999 }
15000 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
15001 let (cpx, cpy) = (gpx / 2, gpy / 2);
15002 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx);
15003 let (uv_mode, angle_delta_uv, alpha) =
15004 last_uv.expect("i==3 always sets has_chroma, so chroma is always Some");
15005 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
15006 neighbours.above_uv_mode[c] = uv_predict_mode;
15007 neighbours.left_uv_mode[r] = uv_predict_mode;
15008 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
15009 let (u_grid, v_grid): (Vec<i32>, Vec<i32>) = if leaf_skips[3] {
15010 // A skipped chroma block still gets its CfL contribution: libaom's
15011 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
15012 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
15013 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
15014 // added -- `skip_txfm` only drops the residual, never the alpha.
15015 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
15016 // merge keeps one fix and feeds both lanes' counters so neither of
15017 // their gates goes vacuous.
15018 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
15019 if alpha.is_some() {
15020 CHROMA_SKIP_CFL_HITS.with(|h| h.set(h.get() + 1));
15021 SKIP_CFL_HITS.with(|c| c.set(c.get() + 1));
15022 }
15023 push_intra(1, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx);
15024 push_intra(2, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx);
15025 (vec![0i32; 16], vec![0i32; 16])
15026 } else {
15027 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
15028 let chroma_around = neighbours.around_mi(leaf_mi, 8);
15029 let ug = read_plane(
15030 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
15031 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
15032 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx,
15033 )?;
15034 let vg = read_plane(
15035 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
15036 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
15037 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx,
15038 )?;
15039 (ug, vg)
15040 };
15041 // Chroma neighbour bookkeeping for the whole 8x8 group -- mirrors
15042 // [`decode_leaf8`]'s own tx4-chroma section (`record_split_luma`'s
15043 // rescaling is wrong for an already-mi-unit position, so this inlines
15044 // its tail directly at `leaf_mi`, side_mi=2), EXCEPT for the partition
15045 // context value itself. Unlike `decode_leaf8`'s TX4 branch (still one
15046 // `BLOCK_8X8`, `PARTITION_NONE`, transform depth only), this group is
15047 // genuinely four `BLOCK_4X4` blocks (`PARTITION_SPLIT` at the 8x8
15048 // level, libaom `decode_partition`'s `bsize2`/`subsize` recursion
15049 // bottom). libaom's `update_ext_partition_context` writes
15050 // `partition_context_lookup[subsize]` at the 8x8 slot -- `{30,30}` for
15051 // `BLOCK_8X8` (bit0=0, what `decode_leaf8` already reproduces via
15052 // side_mi=8) but `{31,31}` for `BLOCK_4X4` (bit0=1) here, and
15053 // `partition_ctx_mi`'s `left_side_mi[mi_r]*2 <= side` needs
15054 // `left_side_mi <= 4` to read that bit as 1. Leaving this at 8 (this
15055 // round's bug) makes the very next sibling 8x8's `partition_w8` read
15056 // with the wrong context and desync immediately.
15057 let side_mi = 2;
15058 for cell in 0..side_mi {
15059 neighbours.left_side_mi[leaf_mi.0 + cell] = 4;
15060 neighbours.above_side_mi[leaf_mi.1 + cell] = 4;
15061 }
15062 let round_up_even = |n: usize| n.div_ceil(2) * 2;
15063 let bound_h = round_up_even(neighbours.mi_rows);
15064 let bound_w = round_up_even(neighbours.mi_cols);
15065 let u_state = neighbour_state(&u_grid);
15066 let v_state = neighbour_state(&v_grid);
15067 for cell in 0..side_mi {
15068 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
15069 neighbours.left[leaf_mi.0 + cell][1] = u_state;
15070 neighbours.left[leaf_mi.0 + cell][2] = v_state;
15071 }
15072 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
15073 neighbours.above[leaf_mi.1 + cell][1] = u_state;
15074 neighbours.above[leaf_mi.1 + cell][2] = v_state;
15075 }
15076 }
15077 Ok((leaf_modes[2], leaf_modes[1]))
15078}
15079
15080/// Decodes a `PARTITION_VERT`/`PARTITION_HORZ` of one 8x8 block into two
15081/// `BLOCK_4X8`/`BLOCK_8X4` leaves (lane-tx4x8), the last partition shape
15082/// below 8x8 this decoder refused. Mirrors [`decode_leaf_split4`] element for
15083/// element -- same mode reads ([`read_intra_mode_sub8`]: no angle delta, no
15084/// tx-depth symbol below 8x8), same "chroma once, on the last sub-block, at
15085/// the whole 8x8 group's 4x4 unit" rule (`is_chroma_reference` is false for
15086/// every sub-block one mi wide or high but the last) -- differing only where
15087/// the shape does:
15088///
15089/// * the transform is a true `TX_4X8`/`TX_8X4`
15090/// ([`dequant_and_inverse_typed_wh`], whose `abs(rect_type) == 1` scale and
15091/// `av1_inv_txfm_shift_ls` row already cover this size pair);
15092/// * the CDF set is [`TxbSet::LumaRect4x8`] (`get_txsize_entropy_ctx` squares
15093/// up to `TX_8X8`) with a 32-position `eob_pt` and the `TX_4X4` `tx_type`
15094/// row -- see that variant's doc comment;
15095/// * the scan is [`SCAN_4X8`]/[`SCAN_8X4`], or their `mrow`/`mcol` siblings
15096/// ([`class_scan_table_wh`]) when the coded `tx_type` is `V_DCT`/`H_DCT`;
15097/// * `Reach` comes from libaom's own `has_tr_4x8`/`has_bl_8x4` rows
15098/// ([`Reach::of_rect`]);
15099/// * `update_partition_context` writes `partition_context_lookup[BLOCK_4X8]`
15100/// = `{31, 30}` (width 4 above, height 8 left), not the `{31, 31}` a
15101/// `BLOCK_4X4` split writes.
15102///
15103/// Filter intra on one of these leaves is decoded (lane-fi8 r1): the flag is
15104/// read from `BLOCK_4X8`/`BLOCK_8X4`'s own `cdf::FILTER_INTRA` row (classes
15105/// 8/9, NOT `BLOCK_4X4`'s), the predictor is [`crate::intra::predict_filter_intra`]
15106/// over the leaf's true `bw`x`bh` -- per 4x4 transform unit, with that unit's
15107/// own edge, when `tx_depth` splits it -- and the coded `tx_type` row is
15108/// [`fi_tx_row`]'s `fimode_to_intradir`, not the block's raw `DC_PRED`.
15109#[allow(clippy::too_many_arguments)]
15110fn decode_leaf_rect8(
15111 dec: &mut SymbolDecoder,
15112 cdfs: &mut Cdfs,
15113 neighbours: &mut Neighbours,
15114 outer_at: (usize, usize),
15115 leaf_mi: (usize, usize),
15116 vert: bool,
15117 scan4: &[u16],
15118 y: &mut PlaneBuf<'static>,
15119 u: &mut PlaneBuf<'static>,
15120 v: &mut PlaneBuf<'static>,
15121 base_q_idx: u8,
15122 enable_filter_intra: bool,
15123 allow_intrabc: bool,
15124 tx_select: bool,
15125 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
15126) -> Result<(usize, usize)> {
15127 let (r, c) = outer_at;
15128 // lane-modectx r1: availability-correct fallback pair (see
15129 // `modes_above_left`), not the raw coarse bands.
15130 let (above_mode, left_mode) = neighbours.modes_above_left(r, c);
15131 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
15132 let (bw, bh) = if vert { (4, 8) } else { (8, 4) };
15133 let (w_mi, h_mi) = (bw / MI, bh / MI);
15134 let scan: &[u16] = if vert { &SCAN_4X8 } else { &SCAN_8X4 };
15135 let mut leaf_modes = [0usize; 2];
15136 let mut leaf_skips = [false; 2];
15137 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
15138 for i in 0..2usize {
15139 let lmi = if vert {
15140 (leaf_mi.0, leaf_mi.1 + i)
15141 } else {
15142 (leaf_mi.0 + i, leaf_mi.1)
15143 };
15144 // Inside the pair the sibling is the neighbour on the split axis;
15145 // outside it the mi-granular map, else the coarse 16x16 slot.
15146 let leaf_above = if !vert && i == 1 {
15147 leaf_modes[0]
15148 } else {
15149 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
15150 };
15151 let leaf_left = if vert && i == 1 {
15152 leaf_modes[0]
15153 } else {
15154 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
15155 };
15156 let has_chroma = i == 1;
15157 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
15158 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
15159 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
15160 filter_intra_size_class_rect(bw, bh)
15161 .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize"),
15162 skip_ctx, allow_intrabc, lmi.0, lmi.1, fctx,
15163 )?;
15164 if filter_intra.is_some() {
15165 // lane-fi8 r1: `predict_filter_intra` walks its 4x2 patches over
15166 // a true `bw`x`bh` block, so a 4x8/8x4 leaf predicts through the
15167 // same `reconstruct_rect`/`reconstruct` calls below -- and under
15168 // a split transform, per 4x4 unit with that unit's own edge,
15169 // which is exactly what the depth-1 loop already does.
15170 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
15171 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.set(c.get() + 1));
15172 }
15173 // `TxMode::Select`'s `tx_depth` (spec 5.11.16) exists at a 4x8/8x4
15174 // leaf too, and is read for every intra block, skipped or not. Its
15175 // category is libaom's `bsize_to_tx_size_cat(BLOCK_4X8) == 0` --
15176 // `sub_tx_size_map[TX_4X8] == TX_4X4` is a single step, so it is the
15177 // same 2-symbol `tx_size_cat0` an 8x8 uses, not the 3-symbol
15178 // `tx_size_cat2` the 32x16 strips read -- with the rect context
15179 // (`get_tx_size_context`'s `max_tx_wide`/`max_tx_high` = bw/bh).
15180 // Missing this read consumed one symbol fewer than the encoder wrote
15181 // and desynced the tile at the very first rect leaf (class
15182 // `symbol-consumption-gap`).
15183 let depth = if tx_select {
15184 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band
15185 // read every other rect reader now does -- a no-op on a key frame.
15186 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
15187 tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx)
15188 } else {
15189 tx_size_context_rect(neighbours, lmi, bw, bh)
15190 };
15191 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
15192 } else {
15193 0
15194 };
15195 if depth != 0 {
15196 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
15197 RECT8_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
15198 }
15199 leaf_modes[i] = mode;
15200 leaf_skips[i] = skip;
15201 neighbours.record_mode_mi(lmi.0, lmi.1, w_mi, h_mi, mode);
15202 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
15203 if smooth_neighbor {
15204 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
15205 }
15206 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
15207 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
15208 // `sub_tx_size_map[TX_4X8] == TX_4X4`: depth 1 splits the leaf into
15209 // two 4x4 transform units along its long axis, each predicted from
15210 // the previous unit's reconstruction and reading its own `txb_skip`
15211 // context -- `decode_leaf8`'s own depth-1 loop, two units instead of
15212 // four. The per-TU path writes its own neighbour state, so the
15213 // block-level write below is skipped for it.
15214 let split = depth != 0;
15215 if split {
15216 let mut done = 0usize;
15217 for tu in 0..2usize {
15218 let tu_mi = if vert {
15219 (lmi.0 + tu, lmi.1)
15220 } else {
15221 (lmi.0, lmi.1 + tu)
15222 };
15223 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);
15224 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
15225 // Same per-TU rule as every other split-transform site
15226 // (lane-palette2 r12): a transform unit inside a block is not
15227 // a block at that position, so its reach comes from the
15228 // block's own row, offset by the unit's position.
15229 let tu_reach = tu_reach(
15230 bw,
15231 bh,
15232 tu_px - px,
15233 tu_py - py,
15234 4,
15235 reach,
15236 px,
15237 py,
15238 y.width,
15239 y.height, fctx,
15240 );
15241 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
15242 if skip {
15243 // A skipped leaf still predicts per transform unit: the
15244 // second 4x4 takes its above/left edge from the first
15245 // one's reconstruction, which is NOT what a single 4x8
15246 // prediction of the same mode produces.
15247 let zeros = vec![0i32; 16];
15248 push_intra(0,
15249 tu_px, tu_py, 4, mode, angle_delta_y, tu_reach, &zeros, None,
15250 filter_intra, smooth_neighbor, fctx,
15251 );
15252 neighbours.record_mi_luma(tu_mi, 4, &zeros);
15253 continue;
15254 }
15255 let tu_grid = read_plane(
15256 dec,
15257 cdfs,
15258 if reduced_tx_set {
15259 TxbSet::Luma4
15260 } else {
15261 TxbSet::Luma4Set1
15262 },
15263 scan4,
15264 0,
15265 tu_around,
15266 mode,
15267 mode,
15268 angle_delta_y,
15269 tu_reach,
15270 y,
15271 tu_px,
15272 tu_py,
15273 4,
15274 TX4,
15275 base_q_idx,
15276 None,
15277 filter_intra,
15278 Some(tu_skip_ctx),
15279 smooth_neighbor, fctx,
15280 )?;
15281 if tu_grid.iter().any(|&l| l != 0) {
15282 done += 1;
15283 }
15284 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
15285 }
15286 if done > 0 {
15287 if vert {
15288 TX4X8_CODED_HITS.with(|h| h.set(h.get() + 1));
15289 } else {
15290 TX8X4_CODED_HITS.with(|h| h.set(h.get() + 1));
15291 }
15292 }
15293 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
15294 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, 4, 4, 0, fctx);
15295 if has_chroma {
15296 last_uv = chroma;
15297 }
15298 continue;
15299 }
15300 let grid = if skip {
15301 let zeros = vec![0i32; bw * bh];
15302 push_intra_rect(0,
15303 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
15304 smooth_neighbor, fctx,
15305 );
15306 zeros
15307 } else {
15308 // `plane_bsize == txsize_to_bsize[tx_size]` here too (the leaf's
15309 // luma TU *is* the leaf), so `get_txb_ctx` fixes `txb_skip_ctx`
15310 // at 0 -- see `decode_leaf_split4`'s own note.
15311 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
15312 let set = if reduced_tx_set {
15313 TxbSet::LumaRect4x8
15314 } else {
15315 TxbSet::LumaRect4x8Set1
15316 };
15317 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
15318 let (levels, tx_type) = read_coeffs_rect(
15319 dec,
15320 &mut coding,
15321 scan,
15322 bw,
15323 bh,
15324 0,
15325 dc_sign_ctx(around.2),
15326 TxType::DctDct,
15327 )?;
15328 if levels.iter().any(|&l| l != 0) {
15329 if vert {
15330 TX4X8_CODED_HITS.with(|h| h.set(h.get() + 1));
15331 } else {
15332 TX8X4_CODED_HITS.with(|h| h.set(h.get() + 1));
15333 }
15334 }
15335 let residual = dequant_and_inverse_typed_wh(
15336 &levels,
15337 bw,
15338 bh,
15339 crate::decode::bit_depth(fctx),
15340 fctx.current_q_idx.with(|q| q.get()),
15341 plane_q_delta(0, fctx).0,
15342 plane_q_delta(0, fctx).1,
15343 tx_type,
15344 );
15345 push_intra_rect(0,
15346 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
15347 smooth_neighbor, fctx,
15348 );
15349 levels
15350 };
15351 // Plane 0's per-TU coefficient context over this leaf's own mi span
15352 // (`record_mi_luma`'s rect twin -- the chroma planes are written once
15353 // for the whole 8x8 group below).
15354 let state = neighbour_state(&grid);
15355 for cell in 0..h_mi {
15356 if lmi.0 + cell < neighbours.mi_rows {
15357 neighbours.left[lmi.0 + cell][0] = state;
15358 }
15359 }
15360 for cell in 0..w_mi {
15361 if lmi.1 + cell < neighbours.mi_cols {
15362 neighbours.above[lmi.1 + cell][0] = state;
15363 }
15364 }
15365 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
15366 let (tx_w, tx_h) = if split { (4, 4) } else { (bw as u8, bh as u8) };
15367 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, tx_w, tx_h, 0, fctx);
15368 if has_chroma {
15369 last_uv = chroma;
15370 }
15371 }
15372 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
15373 let (cpx, cpy) = (gpx / 2, gpy / 2);
15374 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx);
15375 let (uv_mode, angle_delta_uv, alpha) =
15376 last_uv.expect("i==1 always sets has_chroma, so chroma is always Some");
15377 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
15378 neighbours.above_uv_mode[c] = uv_predict_mode;
15379 neighbours.left_uv_mode[r] = uv_predict_mode;
15380 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
15381 let (u_grid, v_grid): (Vec<i32>, Vec<i32>) = if leaf_skips[1] {
15382 // A skipped chroma block still gets its CfL contribution: libaom's
15383 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
15384 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
15385 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
15386 // added -- `skip_txfm` only drops the residual, never the alpha.
15387 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
15388 // merge keeps one fix and feeds both lanes' counters so neither of
15389 // their gates goes vacuous.
15390 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
15391 if alpha.is_some() {
15392 CHROMA_SKIP_CFL_HITS.with(|h| h.set(h.get() + 1));
15393 SKIP_CFL_HITS.with(|c| c.set(c.get() + 1));
15394 }
15395 push_intra(1, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx);
15396 push_intra(2, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &vec![0i32; 16], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx);
15397 (vec![0i32; 16], vec![0i32; 16])
15398 } else {
15399 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
15400 let chroma_around = neighbours.around_mi(leaf_mi, 8);
15401 let ug = read_plane(
15402 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
15403 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
15404 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx,
15405 )?;
15406 let vg = read_plane(
15407 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
15408 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
15409 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx,
15410 )?;
15411 (ug, vg)
15412 };
15413 // `update_partition_context` at the 8x8 level writes
15414 // `partition_context_lookup[subsize]` over the whole 8x8 span: BLOCK_4X8
15415 // is `{31, 30}` (bit0 set on the above half only), BLOCK_8X4 `{30, 31}`
15416 // -- the mirror of `decode_leaf_split4`'s `{31, 31}`, which
15417 // `partition_ctx_mi` reads back off these side values.
15418 for cell in 0..2 {
15419 neighbours.above_side_mi[leaf_mi.1 + cell] = bw;
15420 neighbours.left_side_mi[leaf_mi.0 + cell] = bh;
15421 }
15422 let round_up_even = |n: usize| n.div_ceil(2) * 2;
15423 let bound_h = round_up_even(neighbours.mi_rows);
15424 let bound_w = round_up_even(neighbours.mi_cols);
15425 let u_state = neighbour_state(&u_grid);
15426 let v_state = neighbour_state(&v_grid);
15427 for cell in 0..2usize {
15428 if cell < 2usize.min(bound_h.saturating_sub(leaf_mi.0)) {
15429 neighbours.left[leaf_mi.0 + cell][1] = u_state;
15430 neighbours.left[leaf_mi.0 + cell][2] = v_state;
15431 }
15432 if cell < 2usize.min(bound_w.saturating_sub(leaf_mi.1)) {
15433 neighbours.above[leaf_mi.1 + cell][1] = u_state;
15434 neighbours.above[leaf_mi.1 + cell][2] = v_state;
15435 }
15436 }
15437 // `(below_mode, right_mode)`: the sub-block a neighbour below sees is the
15438 // bottom one (the second under HORZ, the left one under VERT), the one a
15439 // neighbour to the right sees is the top-right (the second under VERT).
15440 Ok(if vert {
15441 (leaf_modes[0], leaf_modes[1])
15442 } else {
15443 (leaf_modes[1], leaf_modes[0])
15444 })
15445}
15446
15447/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
15448/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
15449/// (mod 8) reuse the same table.
15450const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
15451 [(-1, 1), (-2, 2)],
15452 [(0, 1), (-1, 2)],
15453 [(0, 1), (0, 2)],
15454 [(0, 1), (1, 2)],
15455 [(1, 1), (2, 2)],
15456 [(1, 0), (2, 1)],
15457 [(1, 0), (2, 0)],
15458 [(1, 0), (2, -1)],
15459];
15460/// A neighbour tap outside the frame's true extent -- `constrain` reads this
15461/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
15462const CDEF_VERY_LARGE: i32 = 0x4000;
15463const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
15464const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
15465
15466fn cdef_msb(x: i32) -> i32 {
15467 31 - x.leading_zeros() as i32
15468}
15469
15470/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
15471/// centre sample a filter tap is allowed to contribute.
15472#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
15473fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
15474 if threshold == 0 {
15475 return 0;
15476 }
15477 cdef_constrain_shifted(diff, threshold, cdef_constrain_shift(threshold, damping))
15478}
15479
15480/// `constrain`'s damping shift: a function of the block's threshold and
15481/// damping alone, so the filter loop computes it once per block instead of
15482/// the `leading_zeros` + branch it used to do twice per tap read.
15483fn cdef_constrain_shift(threshold: i32, damping: i32) -> i32 {
15484 (damping - cdef_msb(threshold)).max(0)
15485}
15486
15487/// [`cdef_constrain`]'s body with the shift already resolved; `threshold` is
15488/// non-zero on every call (the caller only filters when its strength is).
15489fn cdef_constrain_shifted(diff: i32, threshold: i32, shift: i32) -> i32 {
15490 let a = diff.abs();
15491 diff.signum() * (threshold - (a >> shift)).clamp(0, a)
15492}
15493
15494/// The widest `CDEF_DIRECTIONS` offset in either axis: every tap a block reads
15495/// lies inside its own samples grown by this much.
15496const CDEF_BORDER: usize = 2;
15497
15498/// Copies one block's whole CDEF footprint -- its `bh` x `bw` samples plus the
15499/// [`CDEF_BORDER`] tap ring -- out of the *unfiltered* plane into `buf` (row
15500/// stride `bw + 2 * CDEF_BORDER`), so the direction search and the tap loops
15501/// index a small contiguous window instead of re-deriving the frame-bounds
15502/// test on every one of a pixel's ~17 tap reads. Out-of-frame positions get
15503/// `CDEF_VERY_LARGE`, exactly as the per-sample closure did.
15504fn cdef_gather(
15505 src: &[u16],
15506 stride: usize,
15507 true_w: usize,
15508 true_h: usize,
15509 ox: usize,
15510 oy: usize,
15511 bw: usize,
15512 bh: usize,
15513 buf: &mut [i32],
15514) {
15515 let bstride = bw + 2 * CDEF_BORDER;
15516 let rows = bh + 2 * CDEF_BORDER;
15517 if oy >= CDEF_BORDER
15518 && ox >= CDEF_BORDER
15519 && oy + bh + CDEF_BORDER <= true_h
15520 && ox + bw + CDEF_BORDER <= true_w
15521 {
15522 // Interior block: every tap is inside the frame, so the whole window
15523 // is `rows` contiguous runs.
15524 for r in 0..rows {
15525 let s0 = (oy - CDEF_BORDER + r) * stride + (ox - CDEF_BORDER);
15526 let src_row = &src[s0..s0 + bstride];
15527 let dst_row = &mut buf[r * bstride..r * bstride + bstride];
15528 for (d, &v) in dst_row.iter_mut().zip(src_row) {
15529 *d = i32::from(v);
15530 }
15531 }
15532 return;
15533 }
15534 for r in 0..rows {
15535 let ny = oy as isize + r as isize - CDEF_BORDER as isize;
15536 for c in 0..bstride {
15537 let nx = ox as isize + c as isize - CDEF_BORDER as isize;
15538 buf[r * bstride + c] =
15539 if ny < 0 || nx < 0 || ny as usize >= true_h || nx as usize >= true_w {
15540 CDEF_VERY_LARGE
15541 } else {
15542 i32::from(src[ny as usize * stride + nx as usize])
15543 };
15544 }
15545 }
15546}
15547
15548/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
15549/// direction of an 8x8 luma window and the variance gap between it and its
15550/// orthogonal, `sample(row, col)` reading that window's own pixels.
15551fn cdef_find_dir(coeff_shift: i32, sample: impl Fn(usize, usize) -> i32) -> (usize, i32) {
15552 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
15553 let mut partial = [[0i64; 15]; 8];
15554 for i in 0..8i64 {
15555 for j in 0..8i64 {
15556 // libaom `cdef_find_dir_c`: normalise to an 8-bit sample before
15557 // accumulating, same as `constrain`'s threshold shift below.
15558 let x = i64::from(sample(i as usize, j as usize) >> coeff_shift) - 128;
15559 partial[0][(i + j) as usize] += x;
15560 partial[1][(i + j / 2) as usize] += x;
15561 partial[2][i as usize] += x;
15562 partial[3][(3 + i - j / 2) as usize] += x;
15563 partial[4][(7 + i - j) as usize] += x;
15564 partial[5][(3 - i / 2 + j) as usize] += x;
15565 partial[6][j as usize] += x;
15566 partial[7][(i / 2 + j) as usize] += x;
15567 }
15568 }
15569 let mut cost = [0i64; 8];
15570 for i in 0..8usize {
15571 cost[2] += partial[2][i] * partial[2][i];
15572 cost[6] += partial[6][i] * partial[6][i];
15573 }
15574 cost[2] *= DIV_TABLE[8];
15575 cost[6] *= DIV_TABLE[8];
15576 for i in 0..7usize {
15577 cost[0] += (partial[0][i] * partial[0][i] + partial[0][14 - i] * partial[0][14 - i])
15578 * DIV_TABLE[i + 1];
15579 cost[4] += (partial[4][i] * partial[4][i] + partial[4][14 - i] * partial[4][14 - i])
15580 * DIV_TABLE[i + 1];
15581 }
15582 cost[0] += partial[0][7] * partial[0][7] * DIV_TABLE[8];
15583 cost[4] += partial[4][7] * partial[4][7] * DIV_TABLE[8];
15584 for i in (1..8).step_by(2) {
15585 for j in 0..5usize {
15586 cost[i] += partial[i][3 + j] * partial[i][3 + j];
15587 }
15588 cost[i] *= DIV_TABLE[8];
15589 for j in 0..3usize {
15590 cost[i] += (partial[i][j] * partial[i][j] + partial[i][10 - j] * partial[i][10 - j])
15591 * DIV_TABLE[2 * j + 2];
15592 }
15593 }
15594 let mut best_cost = 0i64;
15595 let mut best_dir = 0usize;
15596 for (i, &c) in cost.iter().enumerate() {
15597 if c > best_cost {
15598 best_cost = c;
15599 best_dir = i;
15600 }
15601 }
15602 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
15603 (best_dir, var as i32)
15604}
15605
15606/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
15607/// (high variance gap) gets more deringing than a flat or non-directional
15608/// one, only ever applied to the luma primary strength.
15609fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
15610 if var == 0 {
15611 return 0;
15612 }
15613 let i = if var >> 6 != 0 {
15614 cdef_msb(var >> 6).min(12)
15615 } else {
15616 0
15617 };
15618 (strength * (4 + i) + 8) >> 4
15619}
15620
15621/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
15622/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
15623/// previously-filtered neighbour must never feed this block's own sum).
15624#[allow(clippy::too_many_arguments)]
15625#[allow(unsafe_code)]
15626fn cdef_filter_block(
15627 src: &[i32],
15628 dst: &mut PlaneBuf<'static>,
15629 ox: usize,
15630 oy: usize,
15631 bw: usize,
15632 bh: usize,
15633 pri_strength: i32,
15634 sec_strength: i32,
15635 dir: usize,
15636 pri_damping: i32,
15637 sec_damping: i32,
15638 enable_primary: bool,
15639 enable_secondary: bool,
15640 coeff_shift: i32, fctx: &crate::decode::FrameCtx,
15641) {
15642 let (stride, smax) = (dst.width, sample_max(fctx));
15643 #[cfg(target_arch = "x86_64")]
15644 if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 && (bw == 4 || bw == 8) && bh % 2 == 0
15645 {
15646 // SAFETY: reached only when the CPU reports avx2; the kernel reads
15647 // `src`'s whole (bw + 4) x (bh + 4) window and writes exactly the
15648 // `bh` runs of `bw` samples the scalar form writes.
15649 unsafe {
15650 cdef_simd::filter_block_avx2(
15651 src,
15652 dst.data.to_mut(),
15653 stride,
15654 ox,
15655 oy,
15656 bw,
15657 bh,
15658 pri_strength,
15659 sec_strength,
15660 dir,
15661 pri_damping,
15662 sec_damping,
15663 enable_primary,
15664 enable_secondary,
15665 coeff_shift,
15666 smax,
15667 )
15668 };
15669 return;
15670 }
15671 cdef_filter_block_scalar(
15672 src,
15673 dst.data.to_mut(),
15674 stride,
15675 ox,
15676 oy,
15677 bw,
15678 bh,
15679 pri_strength,
15680 sec_strength,
15681 dir,
15682 pri_damping,
15683 sec_damping,
15684 enable_primary,
15685 enable_secondary,
15686 coeff_shift,
15687 smax,
15688 );
15689}
15690
15691/// [`cdef_filter_block`]'s scalar reference: spec 7.15.3 sample by sample,
15692/// the form every non-AVX2 build decodes through and the one
15693/// `cdef_simd_kernel_matches_the_scalar_filter` checks the kernel against.
15694#[allow(clippy::too_many_arguments)]
15695fn cdef_filter_block_scalar(
15696 src: &[i32],
15697 dst: &mut [u16],
15698 stride: usize,
15699 ox: usize,
15700 oy: usize,
15701 bw: usize,
15702 bh: usize,
15703 pri_strength: i32,
15704 sec_strength: i32,
15705 dir: usize,
15706 pri_damping: i32,
15707 sec_damping: i32,
15708 enable_primary: bool,
15709 enable_secondary: bool,
15710 coeff_shift: i32,
15711 smax: i32,
15712) {
15713 let clipping_required = enable_primary && enable_secondary;
15714 // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >>
15715 // coeff_shift) & 1]` -- `pri_strength` (and its `adjust_strength`
15716 // derivative) carries the bit-depth shift, so the tap-set parity bit
15717 // must be read back above that shift, not off the raw low bit.
15718 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
15719 // Both damping shifts depend only on this block's strengths (spec 7.15.3's
15720 // `constrain`), so they are resolved here rather than per tap read.
15721 let pri_shift = cdef_constrain_shift(pri_strength.max(1), pri_damping);
15722 let sec_shift = cdef_constrain_shift(sec_strength.max(1), sec_damping);
15723 let bstride = bw + 2 * CDEF_BORDER;
15724 // `src` is [`cdef_gather`]'s window: (i, j) in block coordinates, taps
15725 // reaching +-CDEF_BORDER, so every index below is in range by construction.
15726 let at = |i: i32, j: i32| -> i32 {
15727 src[(i + CDEF_BORDER as i32) as usize * bstride + (j + CDEF_BORDER as i32) as usize]
15728 };
15729 let (pri_dir, sec_dir0, sec_dir1) =
15730 (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]);
15731 for i in 0..bh {
15732 for j in 0..bw {
15733 let (i32i, i32j) = (i as i32, j as i32);
15734 let x = at(i32i, i32j);
15735 let mut sum = 0i32;
15736 let mut max = x;
15737 let mut min = x;
15738 for k in 0..2usize {
15739 if enable_primary {
15740 let (tr, tc) = pri_dir[k];
15741 let p0 = at(i32i + tr, i32j + tc);
15742 let p1 = at(i32i - tr, i32j - tc);
15743 sum += pri_taps[k] * cdef_constrain_shifted(p0 - x, pri_strength, pri_shift);
15744 sum += pri_taps[k] * cdef_constrain_shifted(p1 - x, pri_strength, pri_shift);
15745 if clipping_required {
15746 if p0 != CDEF_VERY_LARGE {
15747 max = max.max(p0);
15748 }
15749 if p1 != CDEF_VERY_LARGE {
15750 max = max.max(p1);
15751 }
15752 min = min.min(p0).min(p1);
15753 }
15754 }
15755 if enable_secondary {
15756 let (tr0, tc0) = sec_dir0[k];
15757 let (tr1, tc1) = sec_dir1[k];
15758 let s0 = at(i32i + tr0, i32j + tc0);
15759 let s1 = at(i32i - tr0, i32j - tc0);
15760 let s2 = at(i32i + tr1, i32j + tc1);
15761 let s3 = at(i32i - tr1, i32j - tc1);
15762 if clipping_required {
15763 for s in [s0, s1, s2, s3] {
15764 if s != CDEF_VERY_LARGE {
15765 max = max.max(s);
15766 }
15767 }
15768 min = min.min(s0).min(s1).min(s2).min(s3);
15769 }
15770 sum += CDEF_SEC_TAPS[k]
15771 * (cdef_constrain_shifted(s0 - x, sec_strength, sec_shift)
15772 + cdef_constrain_shifted(s1 - x, sec_strength, sec_shift)
15773 + cdef_constrain_shifted(s2 - x, sec_strength, sec_shift)
15774 + cdef_constrain_shifted(s3 - x, sec_strength, sec_shift));
15775 }
15776 }
15777 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
15778 if clipping_required {
15779 y = y.clamp(min, max);
15780 }
15781 dst[(oy + i) * stride + (ox + j)] = y.clamp(0, smax) as u16;
15782 }
15783 }
15784}
15785
15786/// lane-perf7 step 1: [`cdef_filter_block`]'s AVX2 kernel -- the scalar
15787/// filter was 13.1% of a 4K decode's self time. Nothing here is spec logic:
15788/// the same taps, the same `constrain`, the same `min`/`max` clamp with the
15789/// `CDEF_VERY_LARGE` sentinel excluded from the max, the same
15790/// `y + ((8 + sum - (sum < 0)) >> 4)` rounding, done 16 samples (two rows) at
15791/// a time in 16-bit lanes.
15792///
15793/// 16-bit lanes are exact for every value this filter sees: window samples
15794/// are in `[0, CDEF_VERY_LARGE]` (0x4000), so a tap difference fits in
15795/// `i16`, a `constrain` result is bounded by the threshold (at most
15796/// `15 << 4`), and the tap-weighted sum by `24 *` that.
15797#[cfg(target_arch = "x86_64")]
15798#[allow(unsafe_code)]
15799#[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract
15800mod cdef_simd {
15801 use super::{
15802 cdef_constrain_shift, CDEF_BORDER, CDEF_DIRECTIONS, CDEF_PRI_TAPS, CDEF_SEC_TAPS,
15803 CDEF_VERY_LARGE,
15804 };
15805 use std::arch::x86_64::*;
15806
15807 /// The window's rows `i` and `i + 1` at one tap offset, as one 256-bit
15808 /// register (low half = row `i`).
15809 ///
15810 /// # Safety
15811 /// Requires AVX2; `off + bstride + 8` must be inside `w`.
15812 #[target_feature(enable = "avx2")]
15813 #[inline]
15814 unsafe fn ld2(w: *const i16, off: isize, bstride: isize) -> __m256i {
15815 let lo = _mm_loadu_si128(w.offset(off).cast());
15816 let hi = _mm_loadu_si128(w.offset(off + bstride).cast());
15817 _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1)
15818 }
15819
15820 /// Spec 7.15.3's `constrain`, lane-parallel:
15821 /// `sign(diff) * clamp(threshold - (|diff| >> shift), 0, |diff|)`.
15822 /// `_mm256_sign_epi16` reproduces `signum` exactly, zero included (the
15823 /// clamped magnitude is already 0 where `diff` is).
15824 ///
15825 /// # Safety
15826 /// Requires AVX2.
15827 #[target_feature(enable = "avx2")]
15828 #[inline]
15829 unsafe fn constrain(p: __m256i, x: __m256i, thr: __m256i, shift: __m128i) -> __m256i {
15830 let diff = _mm256_sub_epi16(p, x);
15831 let a = _mm256_abs_epi16(diff);
15832 let t = _mm256_sub_epi16(thr, _mm256_sra_epi16(a, shift));
15833 let t = _mm256_min_epi16(_mm256_max_epi16(t, _mm256_setzero_si256()), a);
15834 _mm256_sign_epi16(t, diff)
15835 }
15836
15837 /// [`super::cdef_filter_block_scalar`]'s arithmetic, two rows per
15838 /// iteration. `bw` is 8 (luma) or 4 (4:2:0 chroma) and `bh` matches; for
15839 /// `bw == 4` the upper four lanes of each half are window samples read
15840 /// past the row (never past the buffer -- `w` is padded to 256 entries),
15841 /// computed and then dropped by the 64-bit store.
15842 ///
15843 /// # Safety
15844 /// Requires AVX2. `src` must hold the `(bw + 4) x (bh + 4)` window and
15845 /// `dst` the `bh` rows of `bw` samples at `(ox, oy)`.
15846 #[target_feature(enable = "avx2")]
15847 #[allow(clippy::too_many_arguments)]
15848 pub unsafe fn filter_block_avx2(
15849 src: &[i32],
15850 dst: &mut [u16],
15851 stride: usize,
15852 ox: usize,
15853 oy: usize,
15854 bw: usize,
15855 bh: usize,
15856 pri_strength: i32,
15857 sec_strength: i32,
15858 dir: usize,
15859 pri_damping: i32,
15860 sec_damping: i32,
15861 enable_primary: bool,
15862 enable_secondary: bool,
15863 coeff_shift: i32,
15864 smax: i32,
15865 ) {
15866 let bstride = bw + 2 * CDEF_BORDER;
15867 // The window as `i16`, padded so every two-row tap load stays inside
15868 // it (largest read: (bh + 3) * bstride + 8 <= 152 for the 8x8 luma
15869 // block, 72 for the 4x4 chroma one).
15870 let mut w = [0i16; 256];
15871 let rows = bh + 2 * CDEF_BORDER;
15872 for (d, &v) in w[..rows * bstride].iter_mut().zip(&src[..rows * bstride]) {
15873 *d = v as i16;
15874 }
15875 let clipping_required = enable_primary && enable_secondary;
15876 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
15877 let pri_shift = _mm_cvtsi32_si128(cdef_constrain_shift(pri_strength.max(1), pri_damping));
15878 let sec_shift = _mm_cvtsi32_si128(cdef_constrain_shift(sec_strength.max(1), sec_damping));
15879 let pri_thr = _mm256_set1_epi16(pri_strength as i16);
15880 let sec_thr = _mm256_set1_epi16(sec_strength as i16);
15881 let very_large = _mm256_set1_epi16(CDEF_VERY_LARGE as i16);
15882 let zero = _mm256_setzero_si256();
15883 let eight = _mm256_set1_epi16(8);
15884 let smaxv = _mm256_set1_epi16(smax as i16);
15885 let (pri_dir, sec_dir0, sec_dir1) =
15886 (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]);
15887 let wp = w.as_ptr();
15888 let bs = bstride as isize;
15889 let dp = dst.as_mut_ptr();
15890 let mut i = 0usize;
15891 while i < bh {
15892 let base = (i + CDEF_BORDER) as isize * bs + CDEF_BORDER as isize;
15893 let x = ld2(wp, base, bs);
15894 let mut sum = zero;
15895 let mut max = x;
15896 let mut min = x;
15897 for k in 0..2usize {
15898 if enable_primary {
15899 let (tr, tc) = pri_dir[k];
15900 let off = tr as isize * bs + tc as isize;
15901 let p0 = ld2(wp, base + off, bs);
15902 let p1 = ld2(wp, base - off, bs);
15903 let tap = _mm256_set1_epi16(pri_taps[k] as i16);
15904 sum = _mm256_add_epi16(
15905 sum,
15906 _mm256_mullo_epi16(tap, constrain(p0, x, pri_thr, pri_shift)),
15907 );
15908 sum = _mm256_add_epi16(
15909 sum,
15910 _mm256_mullo_epi16(tap, constrain(p1, x, pri_thr, pri_shift)),
15911 );
15912 if clipping_required {
15913 // The sentinel is excluded from the max exactly as the
15914 // scalar `if p != CDEF_VERY_LARGE` does: masking it to
15915 // 0 cannot win a max whose seed `x` is non-negative.
15916 max = _mm256_max_epi16(
15917 max,
15918 _mm256_andnot_si256(_mm256_cmpeq_epi16(p0, very_large), p0),
15919 );
15920 max = _mm256_max_epi16(
15921 max,
15922 _mm256_andnot_si256(_mm256_cmpeq_epi16(p1, very_large), p1),
15923 );
15924 min = _mm256_min_epi16(min, _mm256_min_epi16(p0, p1));
15925 }
15926 }
15927 if enable_secondary {
15928 let (tr0, tc0) = sec_dir0[k];
15929 let (tr1, tc1) = sec_dir1[k];
15930 let off0 = tr0 as isize * bs + tc0 as isize;
15931 let off1 = tr1 as isize * bs + tc1 as isize;
15932 let s0 = ld2(wp, base + off0, bs);
15933 let s1 = ld2(wp, base - off0, bs);
15934 let s2 = ld2(wp, base + off1, bs);
15935 let s3 = ld2(wp, base - off1, bs);
15936 if clipping_required {
15937 for s in [s0, s1, s2, s3] {
15938 max = _mm256_max_epi16(
15939 max,
15940 _mm256_andnot_si256(_mm256_cmpeq_epi16(s, very_large), s),
15941 );
15942 }
15943 min = _mm256_min_epi16(
15944 min,
15945 _mm256_min_epi16(
15946 _mm256_min_epi16(s0, s1),
15947 _mm256_min_epi16(s2, s3),
15948 ),
15949 );
15950 }
15951 let c = _mm256_add_epi16(
15952 _mm256_add_epi16(
15953 constrain(s0, x, sec_thr, sec_shift),
15954 constrain(s1, x, sec_thr, sec_shift),
15955 ),
15956 _mm256_add_epi16(
15957 constrain(s2, x, sec_thr, sec_shift),
15958 constrain(s3, x, sec_thr, sec_shift),
15959 ),
15960 );
15961 sum = _mm256_add_epi16(
15962 sum,
15963 _mm256_mullo_epi16(_mm256_set1_epi16(CDEF_SEC_TAPS[k] as i16), c),
15964 );
15965 }
15966 }
15967 // `-1` where `sum < 0`, i.e. the scalar `- i32::from(sum < 0)`.
15968 let neg = _mm256_cmpgt_epi16(zero, sum);
15969 let mut y = _mm256_add_epi16(
15970 x,
15971 _mm256_srai_epi16(_mm256_add_epi16(_mm256_add_epi16(eight, sum), neg), 4),
15972 );
15973 if clipping_required {
15974 y = _mm256_min_epi16(_mm256_max_epi16(y, min), max);
15975 }
15976 y = _mm256_min_epi16(_mm256_max_epi16(y, zero), smaxv);
15977 let (lo, hi) = (_mm256_castsi256_si128(y), _mm256_extracti128_si256(y, 1));
15978 let o0 = ((oy + i) * stride + ox) as isize;
15979 let o1 = o0 + stride as isize;
15980 if bw == 8 {
15981 _mm_storeu_si128(dp.offset(o0).cast(), lo);
15982 _mm_storeu_si128(dp.offset(o1).cast(), hi);
15983 } else {
15984 _mm_storel_epi64(dp.offset(o0).cast(), lo);
15985 _mm_storel_epi64(dp.offset(o1).cast(), hi);
15986 }
15987 i += 2;
15988 }
15989 }
15990}
15991
15992/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
15993/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
15994/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
15995/// every block's level comes from [`LoopFilterParams::level`] plus the
15996/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
15997/// `get_filter_level`, precomputed per-block here rather than cached in a
15998/// table the way libaom's `av1_loop_filter_frame_init` does).
15999///
16000/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
16001/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
16002fn apply_deblock(
16003 y: &mut PlaneBuf<'static>,
16004 u: &mut PlaneBuf<'static>,
16005 v: &mut PlaneBuf<'static>,
16006 lf: &LoopFilterParams,
16007 n: &Neighbours,
16008 frame_width: usize,
16009 frame_height: usize, fctx: &crate::decode::FrameCtx,
16010) {
16011 // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel
16012 // mismatch between the raw reconstruction and post-filter output.
16013 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_DEBLOCK") {
16014 return;
16015 }
16016 if lf.level[0] != 0 || lf.level[1] != 0 {
16017 deblock_plane(y, 0, lf, n, frame_width, frame_height, fctx);
16018 }
16019 if lf.level[2] != 0 {
16020 deblock_plane(u, 1, lf, n, frame_width, frame_height, fctx);
16021 }
16022 if lf.level[3] != 0 {
16023 deblock_plane(v, 2, lf, n, frame_width, frame_height, fctx);
16024 }
16025}
16026
16027/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
16028/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
16029/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
16030/// mi unit under this decoder's assumed 4:2:0 subsampling).
16031///
16032/// lane-t900 r30b: the chroma arm ORs in the subsampling, exactly as
16033/// `set_lpf_parameters` does (`av1_loopfilter.c:245`, `mi_col = scale_horz |
16034/// ((x << scale_horz) >> MI_SIZE_LOG2)`) -- "for sub8x8 block, chroma
16035/// prediction mode is obtained from the bottom/right mi structure of the
16036/// co-located 8x8 luma block, so for chroma plane both mi_row and mi_col
16037/// should be odd". Dropping that `| 1` read the group's TOP-LEFT mi, which
16038/// is the same cell for every block 8x8 and larger and a DIFFERENT coded
16039/// block (different tx size, ref frame, skip flag and delta_lf) as soon as
16040/// the group is split into 4x4 luma blocks (class
16041/// `context-read-from-one-cell`).
16042fn plane_to_mi(chroma: bool, coord: usize) -> usize {
16043 if chroma { (coord / 2) | 1 } else { coord / 4 }
16044}
16045
16046/// This plane's own transform width in pixels at the covering block, spec
16047/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
16048/// width directly; chroma halves it (this decoder's UV transform is always
16049/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
16050/// under 4:2:0 and a block that never splits its own transform).
16051fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
16052 let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid };
16053 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
16054}
16055
16056/// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
16057/// edges step and gate by transform height, which differs from width only
16058/// on rect partition strips.
16059fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
16060 let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid };
16061 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
16062}
16063
16064/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
16065/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
16066/// present only when its neighbour exists inside the true frame -- whether
16067/// the block immediately above (at this block's own leftmost mi column) or
16068/// to the left (at its own topmost mi row) coded a transform at least as wide
16069/// as `own_side`.
16070fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
16071 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side;
16072 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side;
16073 usize::from(above) + usize::from(left)
16074}
16075
16076/// `get_tx_size_context` as libaom actually writes it (`pred_common.h:342`),
16077/// for a block inside an INTER frame: the two `TXFM_CONTEXT` arrays
16078/// ([`Neighbours::above_txfm`]/[`Neighbours::left_txfm`], which only the
16079/// inter path maintains), except that an *inter* neighbour contributes its
16080/// own BLOCK size rather than its transform size -- the two differ the moment
16081/// a neighbour's var-tx tree splits. [`tx_size_context`]'s deblock-grid
16082/// approximation coincides with this only while every neighbour codes one
16083/// whole-block transform, which is exactly what `TxMode::Select` ends.
16084/// [`tx_size_context_txfm`] with the block's own width and height (lane-intrasplit
16085/// r1): `get_tx_size_context` compares the neighbour ABOVE against
16086/// `tx_size_wide[max_txsize_rect_lookup[bsize]]` and the neighbour to the LEFT
16087/// against `tx_size_high[...]` (libaom `pred_common.h:342`), which for a 2:1
16088/// strip are two different numbers. The intra strip inside an inter frame read
16089/// this through [`tx_size_context_rect`] -- the key frame's deblock-grid
16090/// approximation -- so once `TxMode::Select` made the depth symbol exist, it was
16091/// read off the wrong CDF row whenever a neighbour's var-tx tree had split.
16092fn tx_size_context_txfm_rect(
16093 n: &Neighbours,
16094 (mi_r, mi_c): (usize, usize),
16095 own_w: usize,
16096 own_h: usize, fctx: &crate::decode::FrameCtx,
16097) -> usize {
16098 INTRA_IN_INTER_TXCTX_HITS.with(|c| c.set(c.get() + 1));
16099 let has_above = mi_r > n.tile_row0_mi;
16100 let has_left = mi_c > n.tile_col0_mi;
16101 let mut above = usize::from(n.above_txfm[mi_c]) >= own_w;
16102 let mut left = usize::from(n.left_txfm[mi_r]) >= own_h;
16103 if has_above && n.above_inter[mi_c] {
16104 above = n.above_side_mi[mi_c] >= own_w;
16105 }
16106 if has_left && n.left_inter[mi_r] {
16107 left = n.left_side_mi[mi_r] >= own_h;
16108 }
16109 if crate::envflags::env_flag!("EC_TXCTX") {
16110 eprintln!(
16111 "EC_TXCTX mi={mi_r},{mi_c} own={own_w}x{own_h} ha={has_above} hl={has_left} \
16112 above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \
16113 above={above} left={left}",
16114 n.above_txfm[mi_c],
16115 n.left_txfm[mi_r],
16116 n.above_inter[mi_c],
16117 n.left_inter[mi_r],
16118 n.above_side_mi[mi_c],
16119 n.left_side_mi[mi_r],
16120 );
16121 }
16122 let ctx = match (has_above, has_left) {
16123 (true, true) => usize::from(above) + usize::from(left),
16124 (true, false) => usize::from(above),
16125 (false, true) => usize::from(left),
16126 (false, false) => 0,
16127 };
16128 // lane-midcut r3: count only the blocks the KEY FRAME deblock-grid
16129 // approximation ([`tx_size_context_rect`]) would have read off a DIFFERENT
16130 // CDF row, i.e. exactly the blocks this band read fixes -- a plain "rect
16131 // intra in an inter frame" tally is green on the buggy code too (class
16132 // gate-blind-to-feature).
16133 if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
16134 let (cw, ch) = (own_w.min(64), own_h.min(64));
16135 let stale = usize::from(has_above && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= cw)
16136 + usize::from(has_left && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= ch);
16137 if ctx != stale {
16138 INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS.with(|c| c.set(c.get() + 1));
16139 }
16140 }
16141 ctx
16142}
16143
16144/// lane-intrasplit r3: `above_inter`/`left_inter` are mi-granular bands (they
16145/// are written and read everywhere else with a raw mi index); the SUB-cell
16146/// division this pair used read a cell four blocks away, so the inter-neighbour
16147/// override above fired on the wrong neighbour -- the first divergence of the
16148/// 10-bit gate's stream was exactly this (`tx_depth` ctx 0 where libaom has 1,
16149/// at the intra block right of an inter one).
16150fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
16151 let has_above = mi_r > n.tile_row0_mi;
16152 let has_left = mi_c > n.tile_col0_mi;
16153 let mut above = usize::from(n.above_txfm[mi_c]) >= side;
16154 let mut left = usize::from(n.left_txfm[mi_r]) >= side;
16155 // lane-angledelta r1 (class [[context-read-from-one-cell]]): both
16156 // `above_inter`/`left_inter` bands are written per MI unit
16157 // (`record_inter_rect_mi`), so they are read per MI too -- the `/ (SUB /
16158 // MI)` here read the 16-px cell's FIRST mi instead, i.e. a different
16159 // block whenever the neighbour column/row is not the cell's first. A
16160 // 16x16 intra block whose left neighbour is an inter block at mi row 4
16161 // then missed libaom's "an inter neighbour contributes its BLOCK size"
16162 // override and read `tx_size_cat1` row 1 where aomdec reads row 2.
16163 if has_above && n.above_inter[mi_c] {
16164 above = n.above_side_mi[mi_c] >= side;
16165 }
16166 if has_left && n.left_inter[mi_r] {
16167 left = n.left_side_mi[mi_r] >= side;
16168 }
16169 if crate::envflags::env_flag!("EC_TXCTX") {
16170 eprintln!(
16171 "EC_TXCTX mi={mi_r},{mi_c} own={side} ha={has_above} hl={has_left} \
16172 above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \
16173 above={above} left={left}",
16174 n.above_txfm[mi_c],
16175 n.left_txfm[mi_r],
16176 n.above_inter[mi_c],
16177 n.left_inter[mi_r],
16178 n.above_side_mi[mi_c],
16179 n.left_side_mi[mi_r],
16180 );
16181 }
16182 match (has_above, has_left) {
16183 (true, true) => usize::from(above) + usize::from(left),
16184 (true, false) => usize::from(above),
16185 (false, true) => usize::from(left),
16186 (false, false) => 0,
16187 }
16188}
16189
16190/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
16191/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
16192/// the transform's own side in pixels (`side >> depth`) -- this decoder's
16193/// four square categories (8/16/32/64) each halve at most twice, matching
16194/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
16195fn read_tx_size(
16196 dec: &mut SymbolDecoder,
16197 cdfs: &mut Cdfs,
16198 n: &Neighbours,
16199 at_mi: (usize, usize),
16200 side: usize,
16201 // lane-txselect: `get_tx_size_context`'s real context, for the callers
16202 // that have one -- see [`tx_size_context_txfm`]. `None` keeps the
16203 // key-frame path's own deblock-grid approximation.
16204 ctx_override: Option<usize>,
16205) -> usize {
16206 // `max_txsize_rect_lookup[bsize]` (libaom `read_selected_tx_size` /
16207 // `get_tx_size_context`): a block wider than 64 still tops out at
16208 // TX_64X64, so BLOCK_128X128 reads BLOCK_64X64's own category (its depth
16209 // chain 64->32->16->8->4 is the same four steps) and resolves against 64,
16210 // never against its own 128 side (lane-sb128b r1).
16211 let max_tx = side.min(64);
16212 let ctx = ctx_override.unwrap_or_else(|| tx_size_context(n, at_mi, max_tx));
16213 let depth = match max_tx {
16214 8 => {
16215 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
16216 }
16217 16 => {
16218 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
16219 }
16220 32 => {
16221 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
16222 }
16223 64 => {
16224 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
16225 }
16226 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64/128"),
16227 };
16228 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
16229 let (rng, _) = dec.debug_state();
16230 let (mi_r, mi_c) = at_mi;
16231 eprintln!(
16232 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={depth} ctx={ctx} rng={rng}"
16233 );
16234 }
16235 if depth != 0 {
16236 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
16237 }
16238 max_tx >> depth
16239}
16240
16241/// `txfm_partition_context` (libaom `av1_common_int.h`): an inter block's
16242/// `txfm_split` context -- a category from the block's own largest square
16243/// transform and whether this unit already sits below it, times three, plus
16244/// the two neighbour terms (whether the transform last written above/left of
16245/// this unit is narrower/shorter than the unit itself).
16246#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
16247fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize {
16248 txfm_partition_ctx_rect(above_px, left_px, blk_max_px, tx_px, tx_px)
16249}
16250
16251/// [`txfm_partition_ctx`] for a *rectangular* transform (lane-inter4 r2):
16252/// libaom's `txfm_partition_context` compares the above context against
16253/// `tx_size_wide` and the left one against `tx_size_high`, and takes its
16254/// category from `txsize_sqr_up_map[tx_size]` -- all three collapse to one
16255/// side for a square transform, which is why the square form above is a
16256/// special case of this one.
16257fn txfm_partition_ctx_rect(
16258 above_px: u8,
16259 left_px: u8,
16260 blk_max_px: usize,
16261 tx_w: usize,
16262 tx_h: usize,
16263) -> usize {
16264 let above = usize::from(usize::from(above_px) < tx_w);
16265 let left = usize::from(usize::from(left_px) < tx_h);
16266 let tx_px = tx_w.max(tx_h);
16267 // `get_sqr_tx_size(max(block_size_wide, block_size_high))`, capped at the
16268 // largest transform (`TX_64X64`); `TX_4X4`..`TX_64X64` index as
16269 // `log2(px) - 2`.
16270 let max_tx = blk_max_px.min(64);
16271 let max_idx = max_tx.trailing_zeros() as usize - 2;
16272 let category = usize::from(tx_px != max_tx && max_tx > 8) + (4 - max_idx) * 2;
16273 category * 3 + above + left
16274}
16275
16276/// `txfm_partition_update` (libaom `av1_common_int.h`): once a var-tx unit
16277/// resolves, every mi cell its *parent* unit (`txb_px`) spans records the
16278/// resolved transform's own size.
16279#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
16280fn txfm_partition_update(
16281 n: &mut Neighbours,
16282 at_mi: (usize, usize),
16283 tx_px: usize,
16284 txb_px: usize,
16285) {
16286 txfm_partition_update_rect(n, at_mi, (tx_px, tx_px), (txb_px, txb_px));
16287}
16288
16289/// [`txfm_partition_update`] for a rectangular transform (lane-inter4 r2):
16290/// the left column records `tx_size_high` over the parent's own height and
16291/// the above row records `tx_size_wide` over its width.
16292/// libaom `set_txfm_ctxs` + `txfm_partition_update` (`decodeframe.c`, end of
16293/// `decode_token_recon_block`): EVERY block of an inter frame publishes its
16294/// TRANSFORM size into both `TXFM_CONTEXT` bands, intra blocks included. The
16295/// key frame writes neither (its readers use the deblock grid), so the
16296/// key-frame bodies reused by [`decode_intra_rect_in_inter`] have to do it
16297/// themselves when they run inside an inter frame. The 2:1 and 16x4 arms do it
16298/// at the call site (the transform size comes back to them); the 1:4 arms
16299/// ([`decode_block_rect4`] / [`decode_block_rect64`]) keep their size inside,
16300/// so they call this where their own depth resolves. A no-op on a key frame
16301/// ([`INTRA_IN_INTER_MODE`] unset), where those bands are not read at all.
16302///
16303/// lane-t900 r1 root cause: the HORZ_4 32x8 intra strip at mi(0,312) of an
16304/// inter frame left `left_txfm[0]` at a stale 32 where libaom's own
16305/// `set_txfm_ctxs` writes 8, so the intra 8x16 block at mi(0,320) read
16306/// `tx_size_cat1` row 1 instead of row 0 -- same depth VALUE, different CDF,
16307/// range 39156 where the reference has 54736 (class tx-grid-published-block-side
16308/// / early-return-skips-tail).
16309fn publish_txfm_bands_if_in_inter(
16310 n: &mut Neighbours,
16311 at_mi: (usize, usize),
16312 (tx_w, tx_h): (usize, usize),
16313 (bw, bh): (usize, usize), fctx: &crate::decode::FrameCtx,
16314) {
16315 if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_none() {
16316 return;
16317 }
16318 let (mi_r, mi_c) = at_mi;
16319 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
16320 for i in 0..bw / MI {
16321 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
16322 *cell = tx_w as u8;
16323 }
16324 }
16325 for i in 0..bh / MI {
16326 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
16327 *cell = tx_h as u8;
16328 }
16329 }
16330}
16331
16332fn txfm_partition_update_rect(
16333 n: &mut Neighbours,
16334 (mi_r, mi_c): (usize, usize),
16335 (tx_w, tx_h): (usize, usize),
16336 (txb_w, txb_h): (usize, usize),
16337) {
16338 if crate::envflags::env_flag!("EC_TXUPD") {
16339 eprintln!("EC_TXUPD rect mi=({},{}) tx=({tx_w},{tx_h}) txb=({txb_w},{txb_h})", mi_r, mi_c);
16340 }
16341 for i in 0..txb_h / MI {
16342 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
16343 *cell = tx_h as u8;
16344 }
16345 }
16346 for i in 0..txb_w / MI {
16347 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
16348 *cell = tx_w as u8;
16349 }
16350 }
16351}
16352
16353/// `set_txfm_ctxs` (libaom `av1_common_int.h`): the non-var-tx write of the
16354/// same contexts -- a skipped *inter* block records its own block size rather
16355/// than its transform size.
16356fn set_txfm_ctxs(
16357 n: &mut Neighbours,
16358 (mi_r, mi_c): (usize, usize),
16359 tx_px: usize,
16360 w_mi: usize,
16361 h_mi: usize,
16362 skip_inter: bool,
16363) {
16364 if crate::envflags::env_flag!("EC_TXUPD") {
16365 eprintln!("EC_TXUPD ctxs mi=({mi_r},{mi_c}) tx={tx_px} wh=({w_mi},{h_mi}) skip_inter={skip_inter}");
16366 }
16367 let bw = if skip_inter { w_mi * MI } else { tx_px };
16368 let bh = if skip_inter { h_mi * MI } else { tx_px };
16369 for i in 0..w_mi {
16370 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
16371 *cell = bw as u8;
16372 }
16373 }
16374 for i in 0..h_mi {
16375 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
16376 *cell = bh as u8;
16377 }
16378 }
16379}
16380
16381/// The value libaom initialises both transform contexts to -- NOT zero:
16382/// `av1_zero_above_context` memsets the txfm row to
16383/// `tx_size_wide[TX_SIZES_LARGEST]` and `av1_zero_left_context` does the same
16384/// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64
16385/// pixels, so an unwritten neighbour reads as the *widest* possible
16386/// transform, not the narrowest.
16387const TXFM_CTX_INIT: u8 = 64;
16388
16389/// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most
16390/// twice below its own largest transform.
16391const MAX_VARTX_DEPTH: usize = 2;
16392
16393/// libaom `sub_tx_size_map[TX_SIZES_ALL]` (`common_data.c`): the transform
16394/// one `txfm_split` step below `tx_size`. RECTANGULAR for the 1:4 shapes
16395/// (`[TX_64X16] == TX_32X16`, `[TX_16X64] == TX_16X32`) and for the 4:1
16396/// small ones, square everywhere else.
16397fn sub_tx_size_map(tx_w: usize, tx_h: usize) -> (usize, usize) {
16398 match (tx_w, tx_h) {
16399 (4, 4) => (4, 4),
16400 (8, 8) => (4, 4),
16401 (16, 16) => (8, 8),
16402 (32, 32) => (16, 16),
16403 (64, 64) => (32, 32),
16404 (4, 8) | (8, 4) => (4, 4),
16405 (8, 16) | (16, 8) => (8, 8),
16406 (16, 32) | (32, 16) => (16, 16),
16407 (32, 64) | (64, 32) => (32, 32),
16408 (4, 16) => (4, 8),
16409 (16, 4) => (8, 4),
16410 (8, 32) => (8, 16),
16411 (32, 8) => (16, 8),
16412 (16, 64) => (16, 32),
16413 (64, 16) => (32, 16),
16414 _ => unreachable!("not a TX_SIZES_ALL shape: {tx_w}x{tx_h}"),
16415 }
16416}
16417
16418#[test]
16419fn sub_tx_size_map_matches_libaom() {
16420 // libaom `common_data.c` `sub_tx_size_map`, in TX_SIZES_ALL order.
16421 const TABLE: [((usize, usize), (usize, usize)); 19] = [
16422 ((4, 4), (4, 4)), ((8, 8), (4, 4)), ((16, 16), (8, 8)), ((32, 32), (16, 16)),
16423 ((64, 64), (32, 32)), ((4, 8), (4, 4)), ((8, 4), (4, 4)), ((8, 16), (8, 8)),
16424 ((16, 8), (8, 8)), ((16, 32), (16, 16)), ((32, 16), (16, 16)), ((32, 64), (32, 32)),
16425 ((64, 32), (32, 32)), ((4, 16), (4, 8)), ((16, 4), (8, 4)), ((8, 32), (8, 16)),
16426 ((32, 8), (16, 8)), ((16, 64), (16, 32)), ((64, 16), (32, 16)),
16427 ];
16428 for (tx, want) in TABLE {
16429 assert_eq!(sub_tx_size_map(tx.0, tx.1), want, "sub_tx_size_map({tx:?})");
16430 }
16431}
16432
16433/// The domain of var-tx leaf sizes, enumerated against the two refusals that
16434/// name a leaf "larger than 32x32" / "larger than 64x64".
16435///
16436/// [`read_var_tx_size`] emits a leaf in exactly three places, and each one is
16437/// either the unit it was entered with or a `sub_tx_size_map` step below it:
16438/// the depth cap, the `!split` return, and libaom's `sub_txs == TX_4X4` early
16439/// return. So the leaf set reachable from an entry unit is that unit plus the
16440/// chain of `sub_tx_size_map` steps under it, capped at `MAX_VARTX_DEPTH` --
16441/// which this test enumerates, and over which no leaf is ever larger than the
16442/// entry.
16443///
16444/// That closes both refusals:
16445///
16446/// * [`read_block_tx_size_rect`]'s `bw.max(bh) > 64` branch enters every unit
16447/// at TX_64X64 (`max_txsize_rect_lookup[BLOCK_128X64]`), so "larger than
16448/// 64x64" names a leaf the tree cannot produce;
16449/// * [`read_block_tx_size`] enters at `side.min(64)` with a ceiling of 32
16450/// below the 128 root. The only entry that exceeds that ceiling is 64x64,
16451/// reached only when `side == 64`, and then the block is ONE unit whose only
16452/// above-ceiling leaf is the whole 64x64 unit itself -- which is the `single`
16453/// case the refusal is guarded by.
16454#[test]
16455fn a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered() {
16456 // Every leaf `read_var_tx_size` can reach from `entry`, as (depth, w, h).
16457 fn reachable(entry: (usize, usize), depth: usize, out: &mut Vec<(usize, usize, usize)>) {
16458 out.push((depth, entry.0, entry.1));
16459 if depth == MAX_VARTX_DEPTH {
16460 return;
16461 }
16462 let sub = sub_tx_size_map(entry.0, entry.1);
16463 if sub == (4, 4) {
16464 out.push((depth + 1, 4, 4));
16465 return;
16466 }
16467 reachable(sub, depth + 1, out);
16468 }
16469
16470 for entry in [(4, 4), (8, 8), (16, 16), (32, 32), (64, 64)] {
16471 let mut leaves = Vec::new();
16472 reachable(entry, 0, &mut leaves);
16473 for (depth, w, h) in &leaves {
16474 assert!(
16475 w.max(h) <= &entry.0.max(entry.1),
16476 "a {}x{} unit reaches a {w}x{h} leaf at depth {depth}",
16477 entry.0,
16478 entry.1
16479 );
16480 }
16481 // Above-ceiling leaves of a 64x64 entry: the entry itself, at depth 0.
16482 if entry == (64, 64) {
16483 let above: Vec<&(usize, usize, usize)> =
16484 leaves.iter().filter(|(_, w, h)| w.max(h) > &32).collect();
16485 assert_eq!(above, [&(0usize, 64usize, 64usize)], "64x64 entry, leaves above 32");
16486 }
16487 }
16488
16489 // The entry size and ceiling each caller uses, over the block sides that
16490 // reach them (`read_block_tx_size`'s square path; the 128-root rect path
16491 // enters at a fixed 64).
16492 for side in [8usize, 16, 32, 64, 128] {
16493 let max_tx = side.min(64);
16494 let ceiling = if side > 64 { 64 } else { 32 };
16495 let units = (side / max_tx) * (side / max_tx);
16496 if max_tx <= ceiling {
16497 continue;
16498 }
16499 assert_eq!(
16500 (side, units),
16501 (64, 1),
16502 "a {side}px block enters var-tx at {max_tx} over a ceiling of {ceiling} in \
16503 {units} units -- an above-ceiling leaf there would NOT be the `single` case"
16504 );
16505 }
16506}
16507
16508/// `read_var_tx_size` (spec 5.11.17, libaom `decodeframe.c`
16509/// `read_tx_size_vartx`): the recursive `txfm_split` tree of one
16510/// max-transform-sized unit of an inter block, collecting the resolved leaf
16511/// transform units into `out` as `(row offset, col offset, side)` in mi units
16512/// -- exactly the order `decode_reconstruct_tx` later reads their
16513/// coefficients in. `blk_row`/`blk_col` are mi offsets inside the block;
16514/// `max_w_mi`/`max_h_mi` clip it to the true frame edge (`max_block_wide`/
16515/// `max_block_high`).
16516#[allow(clippy::too_many_arguments)]
16517fn read_var_tx_size(
16518 dec: &mut SymbolDecoder,
16519 cdfs: &mut Cdfs,
16520 n: &mut Neighbours,
16521 at_mi: (usize, usize),
16522 blk_max_px: usize,
16523 (max_w_mi, max_h_mi): (usize, usize),
16524 (tx_w, tx_h): (usize, usize),
16525 depth: usize,
16526 blk_row: usize,
16527 blk_col: usize,
16528 out: &mut Vec<(usize, usize, usize, usize)>,
16529) {
16530 if blk_row >= max_h_mi || blk_col >= max_w_mi {
16531 return;
16532 }
16533 let unit = (at_mi.0 + blk_row, at_mi.1 + blk_col);
16534 if depth == MAX_VARTX_DEPTH {
16535 out.push((blk_row, blk_col, tx_w, tx_h));
16536 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
16537 return;
16538 }
16539 let ctx = txfm_partition_ctx_rect(
16540 n.above_txfm[unit.1],
16541 n.left_txfm[unit.0],
16542 blk_max_px,
16543 tx_w,
16544 tx_h,
16545 );
16546 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
16547 TXFM_SPLIT_READS.with(|c| c.set(c.get() + 1));
16548 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
16549 let (rng, _) = dec.debug_state();
16550 eprintln!(
16551 "EC_ISTEP mi_row={} mi_col={} name=txfm_split val={} ctx={ctx} rng={rng}",
16552 unit.0,
16553 unit.1,
16554 u8::from(split)
16555 );
16556 }
16557 if !split {
16558 out.push((blk_row, blk_col, tx_w, tx_h));
16559 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
16560 return;
16561 }
16562 TXFM_SPLIT_HITS.with(|c| c.set(c.get() + 1));
16563 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
16564 if (sub_w, sub_h) == (4, 4) {
16565 // libaom's `sub_txs == TX_4X4` early return: every mi cell of the
16566 // unit is marked 4x4 (raster order) without recursing.
16567 for row in 0..tx_h / MI {
16568 for col in 0..tx_w / MI {
16569 if blk_row + row < max_h_mi && blk_col + col < max_w_mi {
16570 out.push((blk_row + row, blk_col + col, 4, 4));
16571 }
16572 }
16573 }
16574 txfm_partition_update_rect(n, unit, (4, 4), (tx_w, tx_h));
16575 return;
16576 }
16577 for row in (0..tx_h / MI).step_by(sub_h / MI) {
16578 for col in (0..tx_w / MI).step_by(sub_w / MI) {
16579 read_var_tx_size(
16580 dec,
16581 cdfs,
16582 n,
16583 at_mi,
16584 blk_max_px,
16585 (max_w_mi, max_h_mi),
16586 (sub_w, sub_h),
16587 depth + 1,
16588 blk_row + row,
16589 blk_col + col,
16590 out,
16591 );
16592 }
16593 }
16594}
16595
16596/// `read_block_tx_size` (libaom `decodeframe.c` `parse_decode_block`'s tx
16597/// branch): every block of a `TxMode::Select` inter frame codes its transform
16598/// size right after its own mode info -- an inter non-skip block through the
16599/// recursive var-tx tree ([`read_var_tx_size`], whose leaf list this returns),
16600/// every other block through the intra `tx_depth` symbol (a skipped inter
16601/// block codes no symbol at all) plus a `set_txfm_ctxs` write. Returns the
16602/// block's own resolved transform side and the leaf list, the latter only
16603/// when the tree resolved to more than one transform unit.
16604#[allow(clippy::too_many_arguments)]
16605fn read_block_tx_size(
16606 dec: &mut SymbolDecoder,
16607 cdfs: &mut Cdfs,
16608 n: &mut Neighbours,
16609 at_mi: (usize, usize),
16610 side: usize,
16611 (mi_cols, mi_rows): (usize, usize),
16612 is_inter: bool,
16613 skip: bool, fctx: &crate::decode::FrameCtx,
16614) -> Result<(usize, Option<Vec<(usize, usize, usize, usize)>>)> {
16615 if !fctx.tx_select_inter.with(std::cell::Cell::get) {
16616 // lane-sb128c r1: `max_txsize_rect_lookup[BLOCK_128X128]` is TX_64X64,
16617 // so a 128x128 inter block is FOUR luma units even with `tx_mode ==
16618 // TX_MODE_LARGEST` -- the same leaf shape the var-tx tree hands back.
16619 // lane-sb128c r3: intra too -- an INTRA 128x128 block under
16620 // `TX_MODE_LARGEST` also resolves to TX_64X64, i.e. four luma units.
16621 if side > 64 {
16622 let step = 64 / MI;
16623 let mut leaves = Vec::new();
16624 for row in (0..side / MI).step_by(step) {
16625 for col in (0..side / MI).step_by(step) {
16626 leaves.push((row, col, 64, 64));
16627 }
16628 }
16629 return Ok((64, Some(leaves)));
16630 }
16631 return Ok((side, None));
16632 }
16633 let side_mi = side / MI;
16634 if is_inter && !skip {
16635 let max_tx = side.min(64);
16636 let max_w_mi = side_mi.min(mi_cols.saturating_sub(at_mi.1));
16637 let max_h_mi = side_mi.min(mi_rows.saturating_sub(at_mi.0));
16638 let mut leaves = Vec::new();
16639 let step = max_tx / MI;
16640 for row in (0..side_mi).step_by(step) {
16641 for col in (0..side_mi).step_by(step) {
16642 read_var_tx_size(
16643 dec,
16644 cdfs,
16645 n,
16646 at_mi,
16647 side,
16648 (max_w_mi, max_h_mi),
16649 (max_tx, max_tx),
16650 0,
16651 row,
16652 col,
16653 &mut leaves,
16654 );
16655 }
16656 }
16657 let single = leaves.len() == 1 && leaves[0].2 == side && leaves[0].3 == side;
16658 // lane-sb128c r6: below the 128 root the ceiling is main's TX_32X32
16659 // ([`inter_txbset_for`] has no 64-point *inter* table set); a 128x128
16660 // block's own var-tx tree legitimately bottoms out at TX_64X64 leaves,
16661 // which the mu-chunk reader above codes as their 32x32 coded corner.
16662 let leaf_ceiling = if side > 64 { 64 } else { 32 };
16663 if !single && leaves.iter().any(|leaf| leaf.2.max(leaf.3) > leaf_ceiling) {
16664 // Only a block wider than a superblock's own 64x64 max transform
16665 // reaches here; this crate has no 64-point *inter* coefficient
16666 // table set ([`inter_txbset_for`] stops at 32).
16667 return Err(unsupported(
16668 "an inter var-tx tree with a leaf transform larger than 32x32",
16669 ));
16670 }
16671 let resolved = leaves.last().map_or(side, |l| l.2);
16672 return Ok((resolved, (!single).then_some(leaves)));
16673 }
16674 let tx = if is_inter {
16675 side.min(64)
16676 } else {
16677 read_tx_size(
16678 dec,
16679 cdfs,
16680 n,
16681 at_mi,
16682 side,
16683 // lane-sb128c r3: `get_tx_size_context` compares the neighbour txfm
16684 // contexts against `tx_size_wide[max_txsize_rect_lookup[bsize]]`,
16685 // which is 64 for BLOCK_128X128 -- never the block's own 128 side.
16686 Some(tx_size_context_txfm(n, at_mi, side.min(64))),
16687 )
16688 };
16689 set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter);
16690 if !is_inter && tx != side {
16691 // lane-intrainter r1: an intra block inside an inter frame whose
16692 // `tx_depth` split its luma transform codes exactly the key-frame
16693 // split path's transform units (`decode_block`'s multi-TU loop),
16694 // raster order over the block. Handed back in the same leaf shape the
16695 // inter var-tx tree uses, so the caller's per-TU luma loop, the
16696 // `record_split_luma` neighbour write-back and the per-TU deblock
16697 // edges are the ones it already runs for a var-tx inter block. A
16698 // caller that has no per-TU intra loop (the 8x8 leaf) refuses on
16699 // seeing `Some` here.
16700 let step = tx / MI;
16701 let mut leaves = Vec::new();
16702 for row in (0..side_mi).step_by(step) {
16703 for col in (0..side_mi).step_by(step) {
16704 leaves.push((row, col, tx, tx));
16705 }
16706 }
16707 INTRA_IN_INTER_SPLIT_TX_HITS.with(|c| {
16708 let mut h = c.get();
16709 h[(side.trailing_zeros() as usize).saturating_sub(3).min(3)] += 1;
16710 c.set(h);
16711 });
16712 return Ok((tx, Some(leaves)));
16713 }
16714 Ok((tx, None))
16715}
16716
16717/// lane-inter4 r2: the shapes whose *rectangular inter* residual this
16718/// decoder codes -- a 2:1 strip whose own max rect transform
16719/// (`max_txsize_rect_lookup[BLOCK_32X16] == TX_32X16`) has both a
16720/// coefficient table set ([`TxbSet::LumaRect32x16Inter`], 512-coefficient
16721/// `eob_pt`) and a `tx_type` alphabet here. 64x32/64x16 strips would need a
16722/// 64-point rect transform, and 16x8/8x16 needs
16723/// `default_inter_ext_tx_cdf[2][TX_8X8]` (the 12-symbol
16724/// `DTT9_IDTX_1DDCT` row at `tx_size_sqr == TX_8X8`, only reachable through a
16725/// rect transform), neither of which exists yet -- both stay refused by name.
16726pub(crate) fn rect_inter_residual_supported(w: usize, h: usize) -> bool {
16727 matches!(
16728 (w, h),
16729 // 2:1 strips whose transform is coded in full (lane-inter4).
16730 (32, 16) | (16, 32) | (16, 8) | (8, 16)
16731 // lane-inter16ab r2: the 16x16-level 1:4 strips. TX_16X4/TX_4X16
16732 // codes all 64 of its positions, and its chroma pair is an 8x4 /
16733 // 4x8 unit (`ss_size_lookup[BLOCK_16X4]` = BLOCK_8X4).
16734 | (16, 4) | (4, 16)
16735 // lane-r14 r2: strips with a 64-px axis. `av1_get_max_eob` codes
16736 // only the low 32 coefficients of a 64-length axis, so these read
16737 // exactly the truncated corner the INTRA superblock-strip path
16738 // already reads (`read_intra_mode_rect`), through
16739 // `av1_get_adjusted_tx_size`'s CDF set. Their `tx_size_sqr_up` is
16740 // `TX_64X64`, so `av1_get_ext_tx_set_type` is `DCT_ONLY` and no
16741 // `tx_type` symbol is coded at all.
16742 | (64, 32) | (32, 64) | (64, 16) | (16, 64)
16743 // lane-inter16ab r4: `sub_tx_size_map[TX_16X4] == TX_8X4`, so a
16744 // split-transform 16x4/4x16 strip has RECTANGULAR 8x4/4x8 leaves.
16745 // Only reachable as a var-tx LEAF -- an 8x4/4x8 inter BLOCK is
16746 // refused earlier ("an inter partition below 8x8").
16747 | (8, 4) | (4, 8)
16748 // lane-sb128c r7: the 128 root's HORZ/VERT halves. These are NOT
16749 // one rectangular transform -- `max_txsize_rect_lookup
16750 // [BLOCK_128X64]` is TX_64X64, so the block tiles into two square
16751 // TX_64X64 units read through the mu-chunk loop, same as the
16752 // 128x128 NONE block's four.
16753 | (128, 64) | (64, 128)
16754 // lane-rectres r1: the 32x32-level 1:4 strips -- THE shape both
16755 // 10-bit film cuts and every measured 1080p offset stop on
16756 // (measured: 6/6 probes refuse at 32x8 or 8x32, nothing else).
16757 // `max_txsize_rect_lookup[BLOCK_32X8] == TX_32X8` codes all 256
16758 // positions, and its chroma pair is a 16x4 / 4x16 unit
16759 // (`ss_size_lookup[BLOCK_32X8]` = BLOCK_16X4).
16760 | (32, 8) | (8, 32)
16761 )
16762}
16763
16764// lane-t900 r20: the `(side, write_w, write_h)` triples the inter block path
16765// actually PRESENTS, as a thread-local bitmask -- the measured domain behind
16766// the "rectangular ... has no ... here" refusals. `side` is the square context
16767// a block reads its CDFs at and `write_w`/`write_h` its true footprint;
16768// `inter_piece!` derives `reject_residual` from exactly that inequality, so
16769// these triples are what decides whether those refusals can fire at all. Bit
16770// 31 is "a triple this table does not list", which is what makes the gate a
16771// census rather than a restatement of its own table.
16772pub(crate) const INTER_BLOCK_SHAPES: [(usize, usize, usize); 18] = [
16773 (16, 16, 16),
16774 (32, 32, 32),
16775 (32, 16, 32),
16776 (32, 32, 16),
16777 (16, 8, 16),
16778 (16, 16, 8),
16779 (32, 8, 32),
16780 (64, 64, 64),
16781 (32, 32, 8),
16782 (64, 16, 64),
16783 (128, 128, 128),
16784 (64, 32, 64),
16785 (64, 64, 32),
16786 (16, 4, 16),
16787 (64, 64, 16),
16788 (16, 16, 4),
16789 (128, 128, 64),
16790 (128, 64, 128),
16791];
16792
16793/// Bit 31 of [`inter_block_shape_mask`]: a `(side, write_w, write_h)` triple
16794/// outside [`INTER_BLOCK_SHAPES`].
16795pub const INTER_BLOCK_SHAPE_UNLISTED: u32 = 1 << 31;
16796
16797thread_local! {
16798 static INTER_BLOCK_SHAPE_MASK: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
16799}
16800
16801/// Which of [`INTER_BLOCK_SHAPES`] this THREAD has decoded (thread-local, so a
16802/// gate reading it sees only the streams it decoded itself).
16803pub fn inter_block_shape_mask() -> u32 {
16804 INTER_BLOCK_SHAPE_MASK.with(std::cell::Cell::get)
16805}
16806
16807/// Records one block's shape. The table is ordered by measured frequency over
16808/// the three witnesses the census gate decodes, so the common square shapes
16809/// leave the scan on their first comparison.
16810fn census_inter_block_shape(side: usize, w: usize, h: usize) {
16811 let bit = match INTER_BLOCK_SHAPES.iter().position(|&s| s == (side, w, h)) {
16812 Some(i) => 1u32 << i,
16813 None => INTER_BLOCK_SHAPE_UNLISTED,
16814 };
16815 let seen = inter_block_shape_mask();
16816 if seen & bit == 0 {
16817 INTER_BLOCK_SHAPE_MASK.with(|c| c.set(seen | bit));
16818 }
16819}
16820
16821/// The luma coefficient/`tx_type` table set of a whole-block rectangular
16822/// INTER transform unit (lane-inter4 r3). `av1_get_ext_tx_set_type` splits
16823/// the two shapes: a 32x16/16x32 unit has `tx_size_sqr_up == TX_32X32`, so
16824/// it reads the 2-symbol `EXT_TX_SET_DCT_IDTX` set regardless of
16825/// `reduced_tx_set`; a 16x8/8x16 unit has `tx_size_sqr_up == TX_16X16` and
16826/// `tx_size_sqr == TX_8X8`, so it reads `EXT_TX_SET_DCT_IDTX` when reduced
16827/// and the 16-symbol `EXT_TX_SET_ALL16` otherwise -- both at the *8x8* CDF
16828/// row (`txsize_sqr_map`), never the 16x16 one.
16829fn rect_inter_luma_set(w: usize, h: usize, fctx: &crate::decode::FrameCtx) -> Result<TxbSet> {
16830 Ok(match (w, h) {
16831 (32, 16) | (16, 32) => TxbSet::LumaRect32x16Inter,
16832 // lane-inter16ab r4: the 8x4/4x8 split leaf of a 16x4/4x16 strip.
16833 // `av1_get_ext_tx_set_type` (blockd.h:1097) at `tx_size_sqr_up ==
16834 // TX_8X8`, `tx_size_sqr == TX_4X4`, inter: DCT_IDTX when reduced,
16835 // ALL16 otherwise -- both at the TX_4X4 row.
16836 (8, 4) | (4, 8) => {
16837 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
16838 TxbSet::LumaRect8x4Inter
16839 } else {
16840 TxbSet::LumaRect8x4InterSet1
16841 }
16842 }
16843 (16, 4) | (4, 16) => {
16844 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
16845 TxbSet::LumaRect16x4Inter
16846 } else {
16847 TxbSet::LumaRect16x4Inter1
16848 }
16849 }
16850 (16, 8) | (8, 16) => {
16851 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
16852 TxbSet::LumaRect16x8Inter
16853 } else {
16854 TxbSet::LumaRect16x8InterSet1
16855 }
16856 }
16857 // lane-r14 r2: `av1_get_adjusted_tx_size` maps TX_64X32/TX_32X64 to
16858 // TX_32X32 and TX_64X16/TX_16X64 to TX_32X16/TX_16X32, and
16859 // `get_txsize_entropy_ctx`/`txsize_log2_minus4` agree with the
16860 // adjusted size, so the existing sets are bit-exact. Neither carries a
16861 // `tx_type` table (DCT_ONLY above), so the intra/inter split is moot.
16862 // lane-rectres r1: `tx_size_sqr_up[TX_32X8] == TX_32X32`, so
16863 // `av1_get_ext_tx_set_type` is `EXT_TX_SET_DCT_IDTX` for inter with or
16864 // without `reduced_tx_set` -- one set, no `REDUCED_TX_SET_INTER`
16865 // branch, read at the `txsize_sqr_map[TX_32X8] == TX_8X8` row.
16866 (32, 8) | (8, 32) => TxbSet::LumaRect32x8Inter,
16867 (64, 32) | (32, 64) => TxbSet::Luma64,
16868 (64, 16) | (16, 64) => TxbSet::LumaRect32x16,
16869 _ => {
16870 return Err(unsupported(
16871 "a rectangular inter luma transform unit whose shape has no coefficient table set here",
16872 ));
16873 }
16874 })
16875}
16876
16877/// The chroma table set of the same block's single rectangular chroma unit
16878/// (`av1_get_max_uv_txsize`): 16x8/8x16 under a 32x16/16x32 strip, 8x4/4x8
16879/// under a 16x8/8x16 one. Neither codes a `tx_type` symbol -- both inherit
16880/// the luma unit's.
16881fn rect_inter_chroma_set(w: usize, h: usize) -> Result<TxbSet> {
16882 Ok(match (w, h) {
16883 (16, 8) | (8, 16) => TxbSet::ChromaRect16x8,
16884 (8, 4) | (4, 8) => TxbSet::ChromaRect8x4,
16885 // lane-r14 r2: chroma of a 64-axis strip -- 32x16/16x32 under a
16886 // 64x32/32x64 one, 32x8/8x32 under a 64x16/16x64 one. Neither chroma
16887 // unit has a 64-px axis, so both are coded in full; `Chroma16` is the
16888 // exact set for TX_32X8/TX_8X32 (`get_txsize_entropy_ctx` = TX_16X16,
16889 // `txsize_log2_minus4` = 4), same as the intra strip path uses.
16890 (32, 16) | (16, 32) => TxbSet::ChromaRect32x16,
16891 (32, 8) | (8, 32) => TxbSet::Chroma16,
16892 // lane-rectres r1: chroma of a 32x8/8x32 strip. `Chroma8` is the exact
16893 // set for TX_16X4/TX_4X16 (`get_txsize_entropy_ctx` = TX_8X8,
16894 // `txsize_log2_minus4` = 2, 64-coefficient `eob_pt`).
16895 (16, 4) | (4, 16) => TxbSet::Chroma8,
16896 _ => {
16897 return Err(unsupported(
16898 "a rectangular inter chroma transform unit whose shape has no coefficient table set here",
16899 ));
16900 }
16901 })
16902}
16903
16904/// libaom `size_group_lookup[bsize]` for the block shapes this decoder's
16905/// inter path reaches, from the block's TRUE footprint rather than the
16906/// square `side` corner-cut: 8x8/8x16/16x8 -> 1, 16x16/16x32/32x16 -> 2,
16907/// everything 32 and above -> 3.
16908fn size_group_wh(w: usize, h: usize) -> usize {
16909 // lane-inter4 r4: `size_group_lookup[BLOCK_SIZES_ALL]` (libaom
16910 // `common_data.h:60`) is 0 for every block with a 4-px side
16911 // (4x4/4x8/8x4/4x16/16x4), 1 for min side 8, 2 for 16, 3 above -- the old
16912 // `0..=8 => 1` row gave a sub-8 leaf group 1 where libaom says 0.
16913 match w.min(h) {
16914 0..=4 => 0,
16915 8 => 1,
16916 16 => 2,
16917 _ => 3,
16918 }
16919}
16920
16921#[test]
16922fn size_group_wh_matches_libaom_size_group_lookup() {
16923 // `BLOCK_SIZES_ALL` in libaom's own order, with `size_group_lookup`'s
16924 // transcribed values (common_data.h:60-62).
16925 const TABLE: [((usize, usize), usize); 22] = [
16926 ((4, 4), 0), ((4, 8), 0), ((8, 4), 0), ((8, 8), 1), ((8, 16), 1), ((16, 8), 1),
16927 ((16, 16), 2), ((16, 32), 2), ((32, 16), 2), ((32, 32), 3), ((32, 64), 3),
16928 ((64, 32), 3), ((64, 64), 3), ((64, 128), 3), ((128, 64), 3), ((128, 128), 3),
16929 ((4, 16), 0), ((16, 4), 0), ((8, 32), 1), ((32, 8), 1), ((16, 64), 2), ((64, 16), 2),
16930 ];
16931 for ((w, h), want) in TABLE {
16932 assert_eq!(size_group_wh(w, h), want, "size_group_wh({w}, {h})");
16933 }
16934}
16935
16936/// The default (2D) coefficient scan of a rectangular transform.
16937fn rect_scan(w: usize, h: usize) -> Result<&'static [u16]> {
16938 Ok(match (w, h) {
16939 (32, 16) => &SCAN_32X16,
16940 (16, 32) => &SCAN_16X32,
16941 (16, 8) => &SCAN_16X8,
16942 (8, 16) => &SCAN_8X16,
16943 (16, 4) => &SCAN_16X4,
16944 (4, 16) => &SCAN_4X16,
16945 (8, 4) => &SCAN_8X4,
16946 (4, 8) => &SCAN_4X8,
16947 (32, 8) => &SCAN_32X8,
16948 (8, 32) => &SCAN_8X32,
16949 _ => {
16950 return Err(unsupported(
16951 "a rectangular transform unit whose shape has no coefficient scan table here",
16952 ));
16953 }
16954 })
16955}
16956
16957/// lane-t900 r20, refusal D -- the three "a rectangular inter luma/chroma
16958/// transform unit whose shape has no coefficient table set here" / "a
16959/// rectangular transform unit whose shape has no coefficient scan table here"
16960/// arms, enumerated against the MEASURED domain of the inter block path
16961/// ([`INTER_BLOCK_SHAPES`], filled from three real streams by the gate
16962/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`).
16963///
16964/// What each helper is actually handed:
16965///
16966/// * [`rect_inter_luma_set`] -- the block's own footprint (call sites at the
16967/// whole-block residual), and a var-tx LEAF shape. `sub_tx_size_map` is
16968/// square for every rect transform except TX_16X4/TX_4X16, whose leaves are
16969/// TX_8X4/TX_4X8, so the leaf domain adds exactly 8x4 and 4x8.
16970/// * [`rect_inter_chroma_set`] -- `(write_w / 2, write_h / 2)` for a 4:2:0
16971/// block, except a 16x4/4x16 strip, whose chroma is the PAIR's 8x4 / 4x8.
16972/// * [`rect_scan`] -- the `min(w, 32) x min(h, 32)` coded corner of a rect
16973/// unit, and only when that corner is not 32x32 (a square corner goes
16974/// through the square reader with `rect_shape = Some((w, h))`).
16975///
16976/// The 128-px halves take neither: `max_txsize_rect_lookup[BLOCK_128X64]` is
16977/// TX_64X64, so they tile into SQUARE 64x64 luma units through the mu-chunk
16978/// loop, which is why they are skipped below.
16979#[test]
16980fn every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan() {
16981 let fctx = &crate::decode::FrameCtx::new();
16982 let corner_scan = |w: usize, h: usize| {
16983 let (cw, ch) = (w.min(32), h.min(32));
16984 if (cw, ch) == (32, 32) {
16985 return; // the square coefficient reader, not `rect_scan`
16986 }
16987 assert!(
16988 rect_scan(cw, ch).is_ok(),
16989 "a {w}x{h} rect transform codes its {cw}x{ch} corner, which has no scan table"
16990 );
16991 };
16992 let mut checked = 0;
16993 for &(side, w, h) in &INTER_BLOCK_SHAPES {
16994 if (w, h) == (side, side) || w.max(h) > 64 {
16995 continue;
16996 }
16997 assert!(
16998 rect_inter_luma_set(w, h, fctx).is_ok(),
16999 "the inter path decodes {w}x{h} blocks but has no luma coefficient table set for one"
17000 );
17001 corner_scan(w, h);
17002 // 4:2:0 chroma: the pair's 8x4 / 4x8 for a 1:4 strip, the halved
17003 // footprint for every other shape.
17004 let (cw, ch) = match (w, h) {
17005 (16, 4) => (8, 4),
17006 (4, 16) => (4, 8),
17007 _ => (w / 2, h / 2),
17008 };
17009 assert!(
17010 rect_inter_chroma_set(cw, ch).is_ok(),
17011 "a {w}x{h} block's {cw}x{ch} chroma unit has no coefficient table set"
17012 );
17013 corner_scan(cw, ch);
17014 checked += 1;
17015 }
17016 assert_eq!(
17017 checked, 12,
17018 "the block-shape census changed: {checked} rect shapes reach the rect transform \
17019 tables, not the 12 this claim was measured over"
17020 );
17021 // `sub_tx_size_map[TX_16X4] == TX_8X4` -- the only RECTANGULAR var-tx leaf
17022 // shapes, which reach `rect_inter_luma_set` as `(tw, th)`.
17023 for (w, h) in [(8usize, 4usize), (4, 8)] {
17024 assert!(
17025 rect_inter_luma_set(w, h, fctx).is_ok(),
17026 "the {w}x{h} split leaf of a 16x4/4x16 strip has no luma coefficient table set"
17027 );
17028 corner_scan(w, h);
17029 }
17030}
17031
17032/// [`read_block_tx_size`] for a rectangular inter block (lane-inter4 r2):
17033/// spec 5.11.17 / libaom `read_tx_size_vartx` starting from the block's own
17034/// `max_txsize_rect_lookup` entry, which for a 2:1 strip IS rectangular. The
17035/// depth-0 `txfm_partition` symbol reads its context off the rect transform's
17036/// own width/height; a `0` leaves one whole-block rect transform unit
17037/// (`None`), and a `1` splits it into `sub_tx_size_map`'s two SQUARE
17038/// sub-transforms (`sub_tx_size_map[TX_32X16] == TX_16X16`), from which the
17039/// ordinary square [`read_var_tx_size`] recursion continues at depth 1 -- so
17040/// every leaf of a split rect block is square and the existing square leaf
17041/// loop reconstructs it unchanged.
17042#[allow(clippy::too_many_arguments)]
17043fn read_block_tx_size_rect(
17044 dec: &mut SymbolDecoder,
17045 cdfs: &mut Cdfs,
17046 n: &mut Neighbours,
17047 at_mi: (usize, usize),
17048 (bw, bh): (usize, usize),
17049 (mi_cols, mi_rows): (usize, usize),
17050 skip: bool, fctx: &crate::decode::FrameCtx,
17051) -> Result<Option<Vec<(usize, usize, usize, usize)>>> {
17052 if skip {
17053 // `set_txfm_ctxs(.., skip && is_inter)`: a skipped inter block records
17054 // its own BLOCK size -- width above, height left -- not a transform.
17055 txfm_partition_update_rect(n, at_mi, (bw, bh), (bw, bh));
17056 return Ok(None);
17057 }
17058 // `max_txsize_rect_lookup` is the block's own size, capped at 64 -- and
17059 // `rect_inter_residual_supported` has already excluded everything above 32.
17060 // lane-sb128c r7: except at the 128 root. `max_txsize_rect_lookup
17061 // [BLOCK_128X64] == TX_64X64` (libaom `common_data.h`), so a 128x64 block
17062 // is TWO square top-level transform units side by side and a 64x128 one is
17063 // two stacked -- exactly what libaom `read_block_tx_size`
17064 // (decodeframe.c:1140) codes with its `idy/idx` loop over
17065 // `tx_size_high_unit/tx_size_wide_unit[max_tx_size]`. Each unit reads its
17066 // own `txfm_partition` symbol at depth 0.
17067 if bw.max(bh) > 64 {
17068 let tx = 64usize;
17069 let (max_w_mi, max_h_mi) = (
17070 (bw / MI).min(mi_cols.saturating_sub(at_mi.1)),
17071 (bh / MI).min(mi_rows.saturating_sub(at_mi.0)),
17072 );
17073 let mut leaves = Vec::new();
17074 if !fctx.tx_select_inter.with(std::cell::Cell::get) {
17075 for row in (0..bh / MI).step_by(tx / MI) {
17076 for col in (0..bw / MI).step_by(tx / MI) {
17077 leaves.push((row, col, tx, tx));
17078 }
17079 }
17080 for &(row, col, tw, th) in &leaves {
17081 txfm_partition_update_rect(n, (at_mi.0 + row, at_mi.1 + col), (tw, th), (tw, th));
17082 }
17083 return Ok(Some(leaves));
17084 }
17085 for row in (0..bh / MI).step_by(tx / MI) {
17086 for col in (0..bw / MI).step_by(tx / MI) {
17087 read_var_tx_size(
17088 dec,
17089 cdfs,
17090 n,
17091 at_mi,
17092 bw.max(bh),
17093 (max_w_mi, max_h_mi),
17094 (tx, tx),
17095 0,
17096 row,
17097 col,
17098 &mut leaves,
17099 );
17100 }
17101 }
17102 if leaves.iter().any(|l| l.2.max(l.3) > 64) {
17103 return Err(unsupported(
17104 "an inter var-tx tree with a leaf transform larger than 64x64",
17105 ));
17106 }
17107 return Ok(Some(leaves));
17108 }
17109 let (tx_w, tx_h) = (bw, bh);
17110 if !fctx.tx_select_inter.with(std::cell::Cell::get) {
17111 // `TX_MODE_LARGEST`: no symbol at all, the whole block is one
17112 // transform, and `set_txfm_ctxs` records exactly what
17113 // `txfm_partition_update` would for that same unit.
17114 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
17115 RECT_INTER_TU_HITS.with(|c| c.set(c.get() + 1));
17116 return Ok(None);
17117 }
17118 let ctx = txfm_partition_ctx_rect(
17119 n.above_txfm[at_mi.1],
17120 n.left_txfm[at_mi.0],
17121 bw.max(bh),
17122 tx_w,
17123 tx_h,
17124 );
17125 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
17126 TXFM_SPLIT_READS.with(|c| c.set(c.get() + 1));
17127 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
17128 let (rng, _) = dec.debug_state();
17129 eprintln!(
17130 "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}",
17131 at_mi.0,
17132 at_mi.1,
17133 u8::from(split)
17134 );
17135 }
17136 if !split {
17137 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
17138 RECT_INTER_TU_HITS.with(|c| c.set(c.get() + 1));
17139 return Ok(None);
17140 }
17141 TXFM_SPLIT_HITS.with(|c| c.set(c.get() + 1));
17142 RECT_INTER_TXSPLIT_HITS.with(|c| c.set(c.get() + 1));
17143 // lane-r14 r3: `sub_tx_size_map` (libaom `common_data.c`) stays
17144 // RECTANGULAR under a 1:4 strip -- `[TX_64X16] == TX_32X16`,
17145 // `[TX_16X64] == TX_16X32` -- so the recursion below is the general
17146 // rect one and its leaves carry their own width and height.
17147 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
17148 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(at_mi.1));
17149 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(at_mi.0));
17150 let mut leaves = Vec::new();
17151 for row in (0..bh / MI).step_by(sub_h / MI) {
17152 for col in (0..bw / MI).step_by(sub_w / MI) {
17153 read_var_tx_size(
17154 dec,
17155 cdfs,
17156 n,
17157 at_mi,
17158 bw.max(bh),
17159 (max_w_mi, max_h_mi),
17160 (sub_w, sub_h),
17161 1,
17162 row,
17163 col,
17164 &mut leaves,
17165 );
17166 }
17167 }
17168 Ok(Some(leaves))
17169}
17170
17171/// [`read_inter_plane`] for a rectangular transform unit (lane-inter4 r2):
17172/// the coefficients are read with the rect coefficient machinery
17173/// ([`read_coeffs_rect`], whose `TxClass` handling covers the 1D `V_*`/`H_*`
17174/// types), inverted with the rect inverse transform
17175/// ([`dequant_and_inverse_typed_wh`], which carries the 2:1 `sqrt2` scale),
17176/// and added onto the top-left `w x h` of the block's own square-strided
17177/// motion-compensated prediction buffer. Returns the *rect* coefficient grid
17178/// and the coded `tx_type`.
17179///
17180/// `txb_skip_ctx` is 0 for luma: this unit covers the whole block, i.e.
17181/// `get_txb_ctx`'s `plane_bsize == txsize_to_bsize[tx_size]` branch.
17182#[allow(clippy::too_many_arguments)]
17183fn read_inter_plane_rect(
17184 dec: &mut SymbolDecoder,
17185 cdfs: &mut Cdfs,
17186 set: TxbSet,
17187 (w, h): (usize, usize),
17188 stride: usize,
17189 plane_idx: usize,
17190 around: (bool, bool, i32),
17191 tx_mode: usize,
17192 // lane-wave1 step (i): unread -- this reader records its write
17193 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
17194 // stays in the signature so every call site still proves the plane is
17195 // exclusively held while its coefficients are parsed.
17196 _plane: &mut PlaneBuf<'static>,
17197 x: usize,
17198 y: usize,
17199 prediction: Pred<'_>,
17200 inherited_luma_tx_type: Option<TxType>,
17201 luma_skip_ctx: Option<usize>, fctx: &crate::decode::FrameCtx,
17202) -> Result<(Vec<i32>, TxType)> {
17203 let skip_ctx = if plane_idx == 0 {
17204 // `get_txb_ctx_general`: 0 only when this unit IS the whole plane
17205 // block; a var-tx leaf passes its own neighbour-table context.
17206 luma_skip_ctx.unwrap_or(0)
17207 } else {
17208 usize::from(around.0) + usize::from(around.1)
17209 };
17210 let mut coding = cdfs.txb(set, tx_mode);
17211 // `av1_get_ext_tx_set_type`'s DCT-only clamp is on `tx_size_sqr_up`, i.e.
17212 // the *longer* side of this rect transform.
17213 let default_tx_type = match inherited_luma_tx_type {
17214 Some(t) => reduce_inherited_chroma_tx_type(t, w, h, fctx),
17215 None => TxType::DctDct,
17216 };
17217 // lane-r14 r2: a 64-length axis codes only its low 32 coefficients
17218 // (`av1_get_max_eob`), so the coded unit is the `min(w,32) x min(h,32)`
17219 // corner, zero-extended into the true `w x h` grid before the inverse
17220 // transform -- exactly what the intra superblock-strip path does. A
17221 // corner that comes out square (32x32, under a 64x32/32x64 strip) reads
17222 // through the SQUARE coefficient reader with `rect_shape = Some((w, h))`,
17223 // because `av1_nz_map_ctx_offset` is indexed by the real, un-adjusted
17224 // rectangular shape (lane-sbpart r8).
17225 let (cw, ch) = (w.min(32), h.min(32));
17226 if plane_idx == 0 && w.max(h) == 64 {
17227 RECT64_INTER_TU_HITS.with(|c| c.set(c.get() + 1));
17228 }
17229 if plane_idx == 0 && (w, h) == (32, 8) || plane_idx == 0 && (w, h) == (8, 32) {
17230 RECT32X8_INTER_TU_HITS.with(|c| {
17231 let mut v = c.get();
17232 v[usize::from(w == 8)] += 1;
17233 c.set(v);
17234 });
17235 }
17236 let (corner, tx_type) = if (cw, ch) == (32, 32) {
17237 let scan32 = default_scan(TX32);
17238 read_coeffs(
17239 dec,
17240 &mut coding,
17241 &scan32,
17242 skip_ctx,
17243 dc_sign_ctx(around.2),
17244 default_tx_type,
17245 Some((w, h)),
17246 )?
17247 } else {
17248 read_coeffs_rect(
17249 dec,
17250 &mut coding,
17251 rect_scan(cw, ch)?,
17252 cw,
17253 ch,
17254 skip_ctx,
17255 dc_sign_ctx(around.2),
17256 default_tx_type,
17257 )?
17258 };
17259 let grid = if (cw, ch) == (w, h) {
17260 corner
17261 } else {
17262 let mut full = vec![0i32; w * h];
17263 for row in 0..ch {
17264 full[row * w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
17265 }
17266 full
17267 };
17268 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
17269 if crate::envflags::env_flag!("EC_TRACE_TXTYPE") {
17270 eprintln!("OUR_TXTYPE plane={plane_idx} x={x} y={y} w={w} h={h} tx_type={tx_type:?} inh={inherited_luma_tx_type:?}");
17271 }
17272 // `reconstruct_mc_rect` reads both buffers at the square prediction
17273 // stride, so the dense `w x h` residual is re-laid at that stride
17274 // (`TxParams::stride`) after the inverse transform.
17275 let tx = TxParams {
17276 w, h, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta, ac_delta, tx_type,
17277 stride,
17278 };
17279 push_mc_rect_tx(plane_idx, x, y, stride, w, h, prediction, tx, &grid, fctx);
17280 Ok((grid, tx_type))
17281}
17282
17283/// A rect coefficient grid re-laid into the square `stride x stride` grid the
17284/// neighbour/deblock stamps downstream of the residual expect.
17285fn embed_rect_grid(grid: &[i32], w: usize, h: usize, stride: usize) -> Vec<i32> {
17286 let mut full = vec![0i32; stride * stride];
17287 for row in 0..h {
17288 full[row * stride..][..w].copy_from_slice(&grid[row * w..][..w]);
17289 }
17290 full
17291}
17292
17293/// One 8x8 inter leaf's luma residual (lane-txselect): either the whole-8x8
17294/// transform, or -- when [`read_block_tx_size`]'s var-tx tree took the single
17295/// split a `BLOCK_8X8` can take (`split`) -- the four 4x4 transform units in
17296/// raster order, each reading its own coefficient context off the units
17297/// already decoded before it. Returns the block's luma grid (all-zero in the
17298/// split case, whose reconstruction has already happened unit by unit) and
17299/// the `tx_type` chroma inherits: `av1_get_tx_type`'s colocated luma lookup,
17300/// which for a split block lands on the top-left unit.
17301#[allow(clippy::too_many_arguments)]
17302fn read_inter_luma8(
17303 dec: &mut SymbolDecoder,
17304 cdfs: &mut Cdfs,
17305 neighbours: &mut Neighbours,
17306 leaf_mi: (usize, usize),
17307 y: &mut PlaneBuf<'static>,
17308 px: usize,
17309 py: usize,
17310 pred_y: Pred<'_>,
17311 mode_for_tx: usize,
17312 base_q_idx: u8,
17313 scan8: &[u16],
17314 scan4: &[u16],
17315 reduced_tx_set: bool,
17316 split: bool, fctx: &crate::decode::FrameCtx,
17317) -> Result<(Vec<i32>, TxType)> {
17318 if !split {
17319 return read_inter_plane(
17320 dec,
17321 cdfs,
17322 if reduced_tx_set {
17323 TxbSet::Luma8Inter
17324 } else {
17325 TxbSet::Luma8InterSet1
17326 },
17327 scan8,
17328 0,
17329 neighbours.around_mi(leaf_mi, 8)[0],
17330 mode_for_tx,
17331 y,
17332 px,
17333 py,
17334 8,
17335 base_q_idx,
17336 pred_y,
17337 None,
17338 None, fctx,
17339 );
17340 }
17341 let mut first = TxType::DctDct;
17342 for tu_row in 0..2 {
17343 for tu_col in 0..2 {
17344 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
17345 let tu_pred = pred_y.view(8).offset(tu_row * 4 * 8 + tu_col * 4);
17346 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
17347 let (tu_grid, tu_tx_type) = read_inter_plane(
17348 dec,
17349 cdfs,
17350 if reduced_tx_set {
17351 TxbSet::Luma4Inter
17352 } else {
17353 TxbSet::Luma4InterSet1
17354 },
17355 scan4,
17356 0,
17357 neighbours.around_mi(tu_mi, 4)[0],
17358 mode_for_tx,
17359 y,
17360 px + tu_col * 4,
17361 py + tu_row * 4,
17362 4,
17363 base_q_idx,
17364 tu_pred,
17365 None,
17366 Some(tu_skip_ctx), fctx,
17367 )?;
17368 if tu_row == 0 && tu_col == 0 {
17369 first = tu_tx_type;
17370 }
17371 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
17372 }
17373 }
17374 Ok((vec![0i32; 64], first))
17375}
17376
17377/// The [`TxbSet`] one leaf of an inter block's var-tx tree reads its
17378/// coefficient tables from -- the inter counterpart of [`txbset_for`].
17379/// `av1_get_tx_type`'s chroma tail (libaom `av1/common/blockd.h:1291-1305`):
17380/// an inter block's chroma transform inherits the *colocated luma* unit's
17381/// coded `tx_type`, then drops back to `DCT_DCT` unless that type is a member
17382/// of the extended set the CHROMA transform size selects
17383/// (`av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)][tx_type]`,
17384/// `blockd.h:1036`/`1097`). lane-golomb r7: we used to force `DCT_DCT` at
17385/// every chroma side >= 32, but `av1_get_ext_tx_set_type`'s DCT-only rung is
17386/// `tx_size_sqr_up > TX_32X32`; at exactly TX_32X32 an inter block reads
17387/// `EXT_TX_SET_DCT_IDTX`, so a 64x64 inter block whose first luma leaf coded
17388/// `IDTX` inherits IDTX on its 32x32 chroma units. `IDTX` and `DCT_DCT` are
17389/// both `TX_CLASS_2D`, so that mistake left the entropy stream perfectly in
17390/// sync and only corrupted the inverse transform (one 64x64 superblock of
17391/// high-frequency chroma noise, luma bit-exact).
17392fn reduce_inherited_chroma_tx_type(t: TxType, w: usize, h: usize, fctx: &crate::decode::FrameCtx) -> TxType {
17393 use TxType::*;
17394 let sqr_up = w.max(h);
17395 let sqr = w.min(h);
17396 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
17397 // `av1_get_ext_tx_set_type(tx_size, is_inter = 1, reduced)`.
17398 let allowed: &[TxType] = if sqr_up > 32 {
17399 // EXT_TX_SET_DCTONLY
17400 &[DctDct]
17401 } else if sqr_up == 32 || reduced {
17402 // EXT_TX_SET_DCT_IDTX
17403 &[DctDct, Idtx]
17404 } else if sqr == 16 {
17405 // EXT_TX_SET_DTT9_IDTX_1DDCT -- TX_TYPES 0..=11, i.e. everything but
17406 // the four 1D ADST/FLIPADST types.
17407 &[
17408 DctDct, AdstDct, DctAdst, AdstAdst, FlipAdstDct, DctFlipAdst, FlipAdstFlipAdst,
17409 AdstFlipAdst, FlipAdstAdst, Idtx, VDct, HDct,
17410 ]
17411 } else {
17412 // EXT_TX_SET_ALL16
17413 return t;
17414 };
17415 if allowed.contains(&t) { t } else { DctDct }
17416}
17417
17418fn inter_txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
17419 match tx_px {
17420 // lane-sb128c r1: a 128x128 inter block's own luma unit
17421 // (`max_txsize_rect_lookup[BLOCK_128X128] == TX_64X64`).
17422 // `av1_get_ext_tx_set_type` is `DCT_ONLY` at `tx_size_sqr_up ==
17423 // TX_64X64`, so no `tx_type` symbol is coded and the intra/inter sets
17424 // coincide -- exactly the set the whole-64x64 inter block already uses.
17425 64 => TxbSet::Luma64,
17426 32 => TxbSet::Luma32Inter,
17427 16 if reduced_tx_set => TxbSet::Luma16Inter,
17428 16 => TxbSet::Luma16InterSet1,
17429 8 if reduced_tx_set => TxbSet::Luma8Inter,
17430 8 => TxbSet::Luma8InterSet1,
17431 4 if reduced_tx_set => TxbSet::Luma4Inter,
17432 4 => TxbSet::Luma4InterSet1,
17433 _ => unreachable!("a var-tx leaf is never wider than a 64x64 block's 32x32 sub-transform"),
17434 }
17435}
17436
17437/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
17438/// the only four sizes a `TxMode::Select` block's coded coefficient grid
17439/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
17440fn scan_for<'a>(
17441 tx_px: usize,
17442 scan32: &'a [u16],
17443 scan16: &'a [u16],
17444 scan8: &'a [u16],
17445 scan4: &'a [u16],
17446) -> &'a [u16] {
17447 match tx_px {
17448 32 => scan32,
17449 16 => scan16,
17450 8 => scan8,
17451 4 => scan4,
17452 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
17453 }
17454}
17455
17456/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
17457/// from -- 64 is only ever the 64x64-block, depth-0, corner-scanned case
17458/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
17459/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
17460/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
17461/// regardless of the flag (`av1_get_ext_tx_set_type`'s
17462/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
17463/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
17464/// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]).
17465/// [`txbset_for`], for a block libaom's `is_inter_block` calls inter -- which
17466/// an intrabc block is (`blockd.h:373`), so its `tx_type` comes off the
17467/// inter `ext_tx` sets, never the mode-indexed intra ones.
17468fn txbset_for_inter(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
17469 match tx_px {
17470 64 => TxbSet::Luma64,
17471 32 => TxbSet::Luma32Inter,
17472 16 if reduced_tx_set => TxbSet::Luma16Inter,
17473 16 => TxbSet::Luma16InterSet1,
17474 8 if reduced_tx_set => TxbSet::Luma8Inter,
17475 8 => TxbSet::Luma8InterSet1,
17476 _ => TxbSet::Luma64,
17477 }
17478}
17479
17480fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
17481 match tx_px {
17482 64 => TxbSet::Luma64,
17483 32 => TxbSet::Luma32,
17484 16 => TxbSet::Luma16,
17485 8 if reduced_tx_set => TxbSet::Luma8,
17486 8 => TxbSet::Luma8Set1,
17487 4 if reduced_tx_set => TxbSet::Luma4,
17488 4 => TxbSet::Luma4Set1,
17489 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
17490 }
17491}
17492
17493/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
17494/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
17495fn unit_log2(px: u32) -> i32 {
17496 if px == 0 {
17497 0
17498 } else {
17499 px.trailing_zeros() as i32 - 2
17500 }
17501}
17502
17503/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
17504/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
17505/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
17506/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
17507/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
17508/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
17509/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
17510/// block anywhere aborted the whole stream's decode before comparison).
17511fn lf_level(
17512 lf: &LoopFilterParams,
17513 plane_idx: usize,
17514 dir: usize,
17515 ref_frame: i8,
17516 delta_lf: i32,
17517 segment_id: u8, fctx: &crate::decode::FrameCtx,
17518) -> i32 {
17519 let base = i32::from(if plane_idx == 0 {
17520 lf.level[dir]
17521 } else if plane_idx == 1 {
17522 lf.level[2]
17523 } else {
17524 lf.level[3]
17525 });
17526 // spec 7.14.4: the per-superblock `DeltaLF` term applies before the
17527 // ref/mode delta scaling below, and regardless of `delta_enabled`
17528 // (that flag only gates `ref_deltas`/`mode_deltas`).
17529 let base = (base + delta_lf).clamp(0, 63);
17530 // lane-seg, spec 7.14.4 / libaom `av1_loop_filter_frame_init`: this
17531 // block's segment's own `SEG_LVL_ALT_LF_*` delta applies after the
17532 // per-superblock `DeltaLF` term and before the ref/mode deltas below.
17533 // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4)
17534 // for chroma.
17535 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
17536 // lane-perf9: `segment_id` is `0` and this lookup is skipped entirely
17537 // when the frame codes no segmentation (`seg_lf_active`), which is what
17538 // spares the deblock loop two thread-local reads per 4x4 edge.
17539 let base = match seg_feature(usize::from(segment_id), feature, fctx) {
17540 Some(data) => (base + data).clamp(0, 63),
17541 None => base,
17542 };
17543 if !lf.delta_enabled {
17544 return base;
17545 }
17546 let scale = 1i32 << (base >> 5);
17547 let is_inter = ref_frame != 0;
17548 let is_globalmv = ref_frame < 0;
17549 let ref_idx = ref_frame.unsigned_abs() as usize;
17550 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
17551 if is_inter {
17552 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
17553 }
17554 lvl.clamp(0, 63)
17555}
17556
17557/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
17558/// no-segmentation, no-delta-LF path and to this decoder's own invariant
17559/// that a coded block's transform is always its own full size -- so a TU
17560/// edge is always also a PU edge, and the "both sides skipped, not a PU
17561/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
17562/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
17563/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
17564#[inline(always)]
17565fn edge_params(
17566 lf: &LoopFilterParams,
17567 n: &Neighbours,
17568 plane_idx: usize,
17569 dir: usize,
17570 chroma: bool,
17571 x0: usize,
17572 y0: usize,
17573 // lane-perf9: `segmentation_enabled`, read once per plane pass instead of
17574 // four thread-local reads (`SEG_MI_DIMS`, `SEG_IDS`, twice each) plus two
17575 // `SEG` borrows per 4x4 edge. With it clear, every segment id is 0 and no
17576 // `SEG_LVL_ALT_LF_*` feature can be active, so the levels are unchanged.
17577 seg_lf_active: bool, fctx: &crate::decode::FrameCtx,
17578) -> Option<(u8, i32)> {
17579 let (mi_r, mi_c) = (plane_to_mi(chroma, y0), plane_to_mi(chroma, x0));
17580 let cur_tx = if dir == 0 {
17581 tx_px_at(n, chroma, mi_r, mi_c)
17582 } else {
17583 tx_h_px_at(n, chroma, mi_r, mi_c)
17584 };
17585 // lane-deblock: `cur_tx` is a power-of-two pixel size, so the alignment
17586 // test is a mask, not the hardware `divl` this used to emit (10.7% of
17587 // `edge_params`' own samples sat on that divide's result test).
17588 //
17589 // Most 4-pixel edge groups die right here (a 4-aligned coordinate that
17590 // the covering transform does not start at), so this head is inlined
17591 // into the deblock loops and only survivors pay the call and the
17592 // register-spilling prologue of the body below.
17593 if cur_tx == 0 || (if dir == 0 { x0 } else { y0 }) & (cur_tx as usize - 1) != 0 {
17594 return None;
17595 }
17596 edge_params_body(lf, n, plane_idx, dir, chroma, x0, y0, mi_r, mi_c, cur_tx, seg_lf_active, fctx)
17597}
17598
17599/// [`edge_params`] past its transform-alignment gate.
17600#[allow(clippy::too_many_arguments)]
17601#[inline(never)]
17602fn edge_params_body(
17603 lf: &LoopFilterParams,
17604 n: &Neighbours,
17605 plane_idx: usize,
17606 dir: usize,
17607 chroma: bool,
17608 x0: usize,
17609 y0: usize,
17610 mi_r: usize,
17611 mi_c: usize,
17612 cur_tx: u32,
17613 seg_lf_active: bool,
17614 fctx: &crate::decode::FrameCtx,
17615) -> Option<(u8, i32)> {
17616 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
17617 // `mode_step` (`set_lpf_parameters`): one mi for luma, `1 << ss` for
17618 // chroma -- the previous cell must keep the odd parity `plane_to_mi`
17619 // just established, i.e. the bottom/right mi of the PREVIOUS 8x8 luma
17620 // group, not the other half of this one.
17621 let step = if chroma { 2 } else { 1 };
17622 let (pv_mi_r, pv_mi_c) = if dir == 0 {
17623 (mi_r, mi_c - step)
17624 } else {
17625 (mi_r - step, mi_c)
17626 };
17627 let pv_tx = if dir == 0 {
17628 tx_px_at(n, chroma, pv_mi_r, pv_mi_c)
17629 } else {
17630 tx_h_px_at(n, chroma, pv_mi_r, pv_mi_c)
17631 };
17632 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
17633 let delta_idx = if plane_idx == 0 { dir } else { plane_idx + 1 };
17634 let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][delta_idx]);
17635 let pv_delta_lf = i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][delta_idx]);
17636
17637 // spec 7.14.2 / libaom `set_lpf_parameters`: a transform edge between two
17638 // SKIPPED INTER blocks is filtered only when it is also a prediction
17639 // (coded-block) edge -- `!pv_skip || !curr_skipped || pu_edge`. The
17640 // omission of this term (on the stale invariant "a coded block's transform
17641 // is always its own full size", which var-tx broke) had us filtering an
17642 // interior 8-px lattice the reference never touches: on the pinned 192x68
17643 // inter stream frame 1 went from 7244 wrong post-deblock luma px to 0.
17644 // libaom prices `pu_edge` in the PLANE's own pixels against the plane's
17645 // block size (`!(coord & (block_size_wide[get_plane_block_size(bsize)] -
17646 // 1))`), which for chroma bottoms out at 4 px: every 4-aligned chroma
17647 // edge of a sub-8x8 group is a prediction edge, even though the group's
17648 // bottom/right mi does not start there. Comparing mi origins instead is
17649 // the same test only while the block's own origin is aligned to its
17650 // size, which a 4x4 luma block read at the `| 1` mi is not.
17651 let cur_org = n.blk_org_grid[mi_r * n.skip_grid_cols_mi + mi_c];
17652 let cur_dim = n.blk_dim_grid[mi_r * n.skip_grid_cols_mi + mi_c];
17653 let (org_px, dim_mi) = if dir == 0 {
17654 (usize::from(cur_org[1]), usize::from(cur_dim[0]))
17655 } else {
17656 (usize::from(cur_org[0]), usize::from(cur_dim[1]))
17657 };
17658 let pu_edge = if chroma {
17659 let plane_dim = (dim_mi * MI / 2).max(4);
17660 (if dir == 0 { x0 } else { y0 }) % plane_dim == 0
17661 } else {
17662 plane_to_mi(false, if dir == 0 { x0 } else { y0 }) == org_px
17663 };
17664 if !pu_edge
17665 && cur_ref != 0
17666 && pv_ref != 0
17667 && n.skip_at(mi_r, mi_c)
17668 && n.skip_at(pv_mi_r, pv_mi_c)
17669 {
17670 return None;
17671 }
17672 let (cur_seg, pv_seg) = if seg_lf_active {
17673 (segment_id_at(mi_r, mi_c, fctx), segment_id_at(pv_mi_r, pv_mi_c, fctx))
17674 } else {
17675 (0, 0)
17676 };
17677 let cur_level = lf_level(lf, plane_idx, dir, cur_ref, cur_delta_lf, cur_seg, fctx);
17678 let pv_level = lf_level(lf, plane_idx, dir, pv_ref, pv_delta_lf, pv_seg, fctx);
17679 if cur_level == 0 && pv_level == 0 {
17680 return None;
17681 }
17682 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
17683 let len: u8 = if chroma {
17684 if dim == 0 { 4 } else { 6 }
17685 } else {
17686 [4, 8, 14, 14, 14][dim]
17687 };
17688 let level = if cur_level != 0 { cur_level } else { pv_level };
17689 DEBLOCK_HITS.with(|c| c.set(c.get() + 1));
17690 Some((len, level))
17691}
17692
17693/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
17694fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
17695 let sharpness = i32::from(sharpness);
17696 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
17697 let mut lim = level >> shift;
17698 if sharpness > 0 {
17699 lim = lim.min(9 - sharpness);
17700 }
17701 lim = lim.max(1);
17702 (2 * (level + 2) + lim, lim, level >> 4)
17703}
17704
17705#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
17706fn sclamp(v: i32, fctx: &crate::decode::FrameCtx) -> i32 {
17707 // libaom's `signed_char_clamp_high`: the clamp range scales with
17708 // `128 << (bit_depth - 8)` alongside the centering constant below.
17709 let scale = 1i32 << (bit_depth(fctx) - 8);
17710 v.clamp(-128 * scale, 128 * scale - 1)
17711}
17712
17713fn round_pow2(v: i32, n: u32) -> i32 {
17714 (v + (1 << (n - 1))) >> n
17715}
17716
17717/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
17718/// fallback.
17719fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32, fctx: &crate::decode::FrameCtx) -> [i32; 4] {
17720 if !mask {
17721 return [p1, p0, q0, q1];
17722 }
17723 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
17724 // lane-perf6: `sclamp` re-read the thread-local bit depth on every one of
17725 // this kernel's eight clamps, and this kernel runs per deblocked sample.
17726 // Same bound, resolved once.
17727 let scale = 1i32 << (bit_depth(fctx) - 8);
17728 let sclamp = |v: i32| v.clamp(-128 * scale, 128 * scale - 1);
17729 let centre = 128i32 * scale;
17730 let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre);
17731 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
17732 let filter = sclamp(outer + 3 * (qs0 - ps0));
17733 let filter1 = sclamp(filter + 4) >> 3;
17734 let filter2 = sclamp(filter + 3) >> 3;
17735 let oq0 = sclamp(qs0 - filter1) + centre;
17736 let op0 = sclamp(ps0 + filter2) + centre;
17737 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
17738 let oq1 = sclamp(qs1 - tap) + centre;
17739 let op1 = sclamp(ps1 + tap) + centre;
17740 [op1, op0, oq0, oq1]
17741}
17742
17743/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
17744/// `filter4`'s narrow taps.
17745#[allow(clippy::too_many_arguments)]
17746fn filter6(
17747 mask: bool,
17748 thresh: i32,
17749 flat: bool,
17750 p2: i32,
17751 p1: i32,
17752 p0: i32,
17753 q0: i32,
17754 q1: i32,
17755 q2: i32, fctx: &crate::decode::FrameCtx,
17756) -> [i32; 4] {
17757 if flat && mask {
17758 [
17759 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
17760 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
17761 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
17762 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
17763 ]
17764 } else {
17765 filter4(mask, thresh, p1, p0, q0, q1, fctx)
17766 }
17767}
17768
17769/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
17770#[allow(clippy::too_many_arguments)]
17771fn filter8(
17772 mask: bool,
17773 thresh: i32,
17774 flat: bool,
17775 p3: i32,
17776 p2: i32,
17777 p1: i32,
17778 p0: i32,
17779 q0: i32,
17780 q1: i32,
17781 q2: i32,
17782 q3: i32, fctx: &crate::decode::FrameCtx,
17783) -> [i32; 6] {
17784 if flat && mask {
17785 [
17786 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
17787 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
17788 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
17789 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
17790 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
17791 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
17792 ]
17793 } else {
17794 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1, fctx);
17795 [p2, op1, op0, oq0, oq1, q2]
17796 }
17797}
17798
17799/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
17800/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
17801/// way -- they are only ever taps here, never written).
17802#[allow(clippy::too_many_arguments)]
17803fn filter14(
17804 mask: bool,
17805 thresh: i32,
17806 flat: bool,
17807 flat2: bool,
17808 p6: i32,
17809 p5: i32,
17810 p4: i32,
17811 p3: i32,
17812 p2: i32,
17813 p1: i32,
17814 p0: i32,
17815 q0: i32,
17816 q1: i32,
17817 q2: i32,
17818 q3: i32,
17819 q4: i32,
17820 q5: i32,
17821 q6: i32, fctx: &crate::decode::FrameCtx,
17822) -> [i32; 12] {
17823 if flat2 && flat && mask {
17824 [
17825 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
17826 round_pow2(
17827 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
17828 4,
17829 ),
17830 round_pow2(
17831 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
17832 4,
17833 ),
17834 round_pow2(
17835 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
17836 4,
17837 ),
17838 round_pow2(
17839 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
17840 4,
17841 ),
17842 round_pow2(
17843 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
17844 4,
17845 ),
17846 round_pow2(
17847 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
17848 4,
17849 ),
17850 round_pow2(
17851 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
17852 4,
17853 ),
17854 round_pow2(
17855 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
17856 4,
17857 ),
17858 round_pow2(
17859 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
17860 4,
17861 ),
17862 round_pow2(
17863 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
17864 4,
17865 ),
17866 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
17867 ]
17868 } else {
17869 let [op2, op1, op0, oq0, oq1, oq2] =
17870 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3, fctx);
17871 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
17872 }
17873}
17874
17875/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
17876/// the first (`q0`) sample past the edge, `outer_stride` advances to the
17877/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
17878/// the next along the edge's own filtering direction.
17879#[allow(clippy::too_many_arguments)]
17880fn filter_edge(
17881 data: &mut [u16],
17882 base: usize,
17883 outer_stride: isize,
17884 tap_stride: isize,
17885 len: u8,
17886 level: i32,
17887 sharpness: u8, fctx: &crate::decode::FrameCtx,
17888) {
17889 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
17890 // libaom `highbd_filter_mask*`/`highbd_flat_mask4`/`highbd_hev_mask`:
17891 // every 8-bit threshold (including the flat masks' fixed `1`) is
17892 // compared against a raw pixel difference on the stream's own bit-depth
17893 // scale, so each is shifted left by `bit_depth - 8` before use.
17894 let shift = bit_depth(fctx) - 8;
17895 let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift);
17896 let flat_thresh = 1i32 << shift;
17897 let smax = sample_max(fctx);
17898 for i in 0..4isize {
17899 let center = (base as isize + i * outer_stride) as usize;
17900 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
17901 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
17902 match len {
17903 4 => {
17904 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
17905 let mask = (p1 - p0).abs() <= limit
17906 && (q1 - q0).abs() <= limit
17907 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
17908 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1, fctx);
17909 data[idx(-2)] = op1.clamp(0, smax) as u16;
17910 data[idx(-1)] = op0.clamp(0, smax) as u16;
17911 data[idx(0)] = oq0.clamp(0, smax) as u16;
17912 data[idx(1)] = oq1.clamp(0, smax) as u16;
17913 }
17914 6 => {
17915 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
17916 let mask = (p2 - p1).abs() <= limit
17917 && (p1 - p0).abs() <= limit
17918 && (q1 - q0).abs() <= limit
17919 && (q2 - q1).abs() <= limit
17920 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
17921 let flat = (p1 - p0).abs() <= flat_thresh
17922 && (q1 - q0).abs() <= flat_thresh
17923 && (p2 - p0).abs() <= flat_thresh
17924 && (q2 - q0).abs() <= flat_thresh;
17925 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2, fctx);
17926 data[idx(-2)] = op1.clamp(0, smax) as u16;
17927 data[idx(-1)] = op0.clamp(0, smax) as u16;
17928 data[idx(0)] = oq0.clamp(0, smax) as u16;
17929 data[idx(1)] = oq1.clamp(0, smax) as u16;
17930 }
17931 8 => {
17932 let (p3, p2, p1, p0, q0, q1, q2, q3) =
17933 (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3));
17934 let mask = (p3 - p2).abs() <= limit
17935 && (p2 - p1).abs() <= limit
17936 && (p1 - p0).abs() <= limit
17937 && (q1 - q0).abs() <= limit
17938 && (q2 - q1).abs() <= limit
17939 && (q3 - q2).abs() <= limit
17940 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
17941 let flat = (p1 - p0).abs() <= flat_thresh
17942 && (q1 - q0).abs() <= flat_thresh
17943 && (p2 - p0).abs() <= flat_thresh
17944 && (q2 - q0).abs() <= flat_thresh
17945 && (p3 - p0).abs() <= flat_thresh
17946 && (q3 - q0).abs() <= flat_thresh;
17947 let [op2, op1, op0, oq0, oq1, oq2] =
17948 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3, fctx);
17949 data[idx(-3)] = op2.clamp(0, smax) as u16;
17950 data[idx(-2)] = op1.clamp(0, smax) as u16;
17951 data[idx(-1)] = op0.clamp(0, smax) as u16;
17952 data[idx(0)] = oq0.clamp(0, smax) as u16;
17953 data[idx(1)] = oq1.clamp(0, smax) as u16;
17954 data[idx(2)] = oq2.clamp(0, smax) as u16;
17955 }
17956 _ => {
17957 let (p6, p5, p4, p3, p2, p1, p0) =
17958 (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1));
17959 let (q0, q1, q2, q3, q4, q5, q6) =
17960 (px(0), px(1), px(2), px(3), px(4), px(5), px(6));
17961 let mask = (p3 - p2).abs() <= limit
17962 && (p2 - p1).abs() <= limit
17963 && (p1 - p0).abs() <= limit
17964 && (q1 - q0).abs() <= limit
17965 && (q2 - q1).abs() <= limit
17966 && (q3 - q2).abs() <= limit
17967 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
17968 let flat = (p1 - p0).abs() <= flat_thresh
17969 && (q1 - q0).abs() <= flat_thresh
17970 && (p2 - p0).abs() <= flat_thresh
17971 && (q2 - q0).abs() <= flat_thresh
17972 && (p3 - p0).abs() <= flat_thresh
17973 && (q3 - q0).abs() <= flat_thresh;
17974 let flat2 = (p4 - p0).abs() <= flat_thresh
17975 && (q4 - q0).abs() <= flat_thresh
17976 && (p5 - p0).abs() <= flat_thresh
17977 && (q5 - q0).abs() <= flat_thresh
17978 && (p6 - p0).abs() <= flat_thresh
17979 && (q6 - q0).abs() <= flat_thresh;
17980 let out = filter14(
17981 mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5,
17982 q6, fctx,
17983 );
17984 for (k, v) in (-6..=5isize).zip(out) {
17985 data[idx(k)] = v.clamp(0, smax) as u16;
17986 }
17987 }
17988 }
17989 }
17990}
17991
17992/// lane-perf8: [`filter_edge`]'s AVX2 kernel -- the scalar loop was 8.0% of a
17993/// 4K decode's self time, spent almost entirely on the per-tap strided
17994/// addressing (`perf annotate`'s hot lines are `leaq`/`movzwl` pairs, not the
17995/// arithmetic). Nothing here is spec logic: the same masks, the same
17996/// `filter4`/`filter6`/`filter8`/`filter14` weighted sums and the same
17997/// rounding, done for 16 edge lines at once.
17998///
17999/// 16-bit lanes are exact for every value these filters see. Samples are in
18000/// `[0, 4095]`, so a difference and the `blimit` term (`2 * |p0 - q0| +
18001/// |p1 - q1| / 2 <= 10237`) fit `i16`; `filter4` works in the centred domain
18002/// where every intermediate is clamped to `+-128 << (bit_depth - 8)`; and the
18003/// wide kernels' weights each total 8 or 16, so their sums (at most
18004/// `16 * 4095 + 8 = 65528`) fit `u16` -- hence `_mm256_srli_epi16` for their
18005/// rounding shift, which is the unsigned shift the scalar's non-negative sum
18006/// takes.
18007#[cfg(target_arch = "x86_64")]
18008#[allow(unsafe_code)]
18009#[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract
18010mod deblock_simd {
18011 use std::arch::x86_64::*;
18012
18013 /// `a <= b` lane-wise, as a full-width mask.
18014 ///
18015 /// # Safety
18016 /// Requires AVX2.
18017 #[target_feature(enable = "avx2")]
18018 #[inline]
18019 unsafe fn le(a: __m256i, b: __m256i) -> __m256i {
18020 _mm256_cmpeq_epi16(_mm256_max_epi16(a, b), b)
18021 }
18022
18023 /// `|a - b|` lane-wise.
18024 ///
18025 /// # Safety
18026 /// Requires AVX2.
18027 #[target_feature(enable = "avx2")]
18028 #[inline]
18029 unsafe fn ad(a: __m256i, b: __m256i) -> __m256i {
18030 _mm256_abs_epi16(_mm256_sub_epi16(a, b))
18031 }
18032
18033 /// `signed_char_clamp_high`, lane-wise.
18034 ///
18035 /// # Safety
18036 /// Requires AVX2.
18037 #[target_feature(enable = "avx2")]
18038 #[inline]
18039 unsafe fn sclamp(v: __m256i, lo: __m256i, hi: __m256i) -> __m256i {
18040 _mm256_min_epi16(_mm256_max_epi16(v, lo), hi)
18041 }
18042
18043 /// 16 rows of 16 `i16` transposed in place (unpack ladder, then the
18044 /// 128-bit lane swap AVX2's in-lane unpacks leave behind).
18045 ///
18046 /// # Safety
18047 /// Requires AVX2.
18048 #[target_feature(enable = "avx2")]
18049 unsafe fn transpose16(t: &mut [__m256i; 16]) {
18050 let mut a = [_mm256_setzero_si256(); 16];
18051 for k in 0..8 {
18052 a[2 * k] = _mm256_unpacklo_epi16(t[2 * k], t[2 * k + 1]);
18053 a[2 * k + 1] = _mm256_unpackhi_epi16(t[2 * k], t[2 * k + 1]);
18054 }
18055 let mut b = [_mm256_setzero_si256(); 16];
18056 for g in 0..4 {
18057 let s = 4 * g;
18058 b[s] = _mm256_unpacklo_epi32(a[s], a[s + 2]);
18059 b[s + 1] = _mm256_unpackhi_epi32(a[s], a[s + 2]);
18060 b[s + 2] = _mm256_unpacklo_epi32(a[s + 1], a[s + 3]);
18061 b[s + 3] = _mm256_unpackhi_epi32(a[s + 1], a[s + 3]);
18062 }
18063 let mut c = [_mm256_setzero_si256(); 16];
18064 for g in 0..2 {
18065 let s = 8 * g;
18066 for j in 0..4 {
18067 c[s + 2 * j] = _mm256_unpacklo_epi64(b[s + j], b[s + j + 4]);
18068 c[s + 2 * j + 1] = _mm256_unpackhi_epi64(b[s + j], b[s + j + 4]);
18069 }
18070 }
18071 for i in 0..8 {
18072 t[i] = _mm256_permute2x128_si256(c[i], c[i + 8], 0x20);
18073 t[i + 8] = _mm256_permute2x128_si256(c[i], c[i + 8], 0x31);
18074 }
18075 }
18076
18077 /// The wide kernels' tap weights, in tap order and with the spec's
18078 /// rounding divisor as the row sum: `filter6` over `p2..q2`, `filter8`
18079 /// over `p3..q3`, `filter14` over `p6..q6`.
18080 const W6: [[i16; 6]; 4] = [
18081 [3, 2, 2, 1, 0, 0],
18082 [1, 2, 2, 2, 1, 0],
18083 [0, 1, 2, 2, 2, 1],
18084 [0, 0, 1, 2, 2, 3],
18085 ];
18086 const W8: [[i16; 8]; 6] = [
18087 [3, 2, 1, 1, 1, 0, 0, 0],
18088 [2, 1, 2, 1, 1, 1, 0, 0],
18089 [1, 1, 1, 2, 1, 1, 1, 0],
18090 [0, 1, 1, 1, 2, 1, 1, 1],
18091 [0, 0, 1, 1, 1, 2, 1, 2],
18092 [0, 0, 0, 1, 1, 1, 2, 3],
18093 ];
18094 #[allow(dead_code)] // superseded by the running-sum rows; kept as the weights' statement
18095 const W14: [[i16; 14]; 12] = [
18096 [7, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
18097 [5, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
18098 [4, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0],
18099 [3, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0],
18100 [2, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0],
18101 [1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0],
18102 [0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1],
18103 [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2],
18104 [0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 3],
18105 [0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 4],
18106 [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 5],
18107 [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 7],
18108 ];
18109
18110 /// One weighted tap sum, rounded by `shift` (3 for the divide-by-8 rows,
18111 /// 4 for `filter14`'s divide-by-16 ones). The sum is non-negative and
18112 /// below `1 << 16`, so the logical shift is the arithmetic one.
18113 ///
18114 /// # Safety
18115 /// Requires AVX2.
18116 ///
18117 /// lane-deblock: the tap count, the weights and the shift are all const
18118 /// here (they were slice parameters, which left the weight `match` as a
18119 /// runtime branch and a `movzwl` per tap -- `testl`/`je`/`movzwl` were
18120 /// 34% of this kernel's samples, and the spilled tap slices another 17%).
18121 #[target_feature(enable = "avx2")]
18122 #[inline] // rust#145574: `inline(always)` is rejected on a `target_feature` fn
18123 unsafe fn wsum<const N: usize, const SHIFT: i32>(
18124 taps: &[__m256i; N],
18125 w: &[i16; N],
18126 ) -> __m256i {
18127 let mut s = _mm256_setzero_si256();
18128 for i in 0..N {
18129 match w[i] {
18130 0 => {}
18131 1 => s = _mm256_add_epi16(s, taps[i]),
18132 2 => s = _mm256_add_epi16(s, _mm256_add_epi16(taps[i], taps[i])),
18133 k => s = _mm256_add_epi16(s, _mm256_mullo_epi16(taps[i], _mm256_set1_epi16(k))),
18134 }
18135 }
18136 let s = _mm256_add_epi16(s, _mm256_set1_epi16(1 << (SHIFT - 1)));
18137 if SHIFT == 3 {
18138 _mm256_srli_epi16(s, 3)
18139 } else {
18140 _mm256_srli_epi16(s, 4)
18141 }
18142 }
18143
18144 /// One wide-kernel row set, unrolled so each `wsum` sees its weight row
18145 /// as a constant.
18146 macro_rules! wrows {
18147 ($r:expr, $off:expr, $tbl:ident, $taps:expr, $shift:literal, $flat:expr, $($j:literal),*) => {
18148 $(
18149 $r[$off + $j] = _mm256_blendv_epi8($r[$off + $j], wsum::<_, $shift>(&$taps, &$tbl[$j]), $flat);
18150 )*
18151 };
18152 }
18153
18154 /// [`super::filter_edge`]'s body for 16 lines held as `t[0..16]`, `q0` in
18155 /// `t[8]`; the filtered taps are written back in place.
18156 ///
18157 /// # Safety
18158 /// Requires AVX2.
18159 #[target_feature(enable = "avx2")]
18160 #[allow(clippy::too_many_arguments)]
18161 unsafe fn filter16(
18162 t: &mut [__m256i; 16],
18163 len: u8,
18164 blimit: i32,
18165 limit: i32,
18166 hev_thr: i32,
18167 flat_thresh: i32,
18168 scale: i32,
18169 smax: i32,
18170 ) {
18171 let lim = _mm256_set1_epi16(limit as i16);
18172 let blim = _mm256_set1_epi16(blimit as i16);
18173 let hthr = _mm256_set1_epi16(hev_thr as i16);
18174 let fthr = _mm256_set1_epi16(flat_thresh as i16);
18175 let zero = _mm256_setzero_si256();
18176 let smaxv = _mm256_set1_epi16(smax as i16);
18177 let (p6, p5, p4, p3, p2, p1, p0) = (t[1], t[2], t[3], t[4], t[5], t[6], t[7]);
18178 let (q0, q1, q2, q3, q4, q5, q6) = (t[8], t[9], t[10], t[11], t[12], t[13], t[14]);
18179
18180 // `highbd_filter_mask`: the neighbour steps this kernel's length
18181 // reaches, plus the shared `blimit` term.
18182 let d1 = _mm256_max_epi16(ad(p1, p0), ad(q1, q0));
18183 let mut md = d1;
18184 if len >= 6 {
18185 md = _mm256_max_epi16(md, _mm256_max_epi16(ad(p2, p1), ad(q2, q1)));
18186 }
18187 if len >= 8 {
18188 md = _mm256_max_epi16(md, _mm256_max_epi16(ad(p3, p2), ad(q3, q2)));
18189 }
18190 let bl = _mm256_add_epi16(
18191 _mm256_slli_epi16(ad(p0, q0), 1),
18192 _mm256_srli_epi16(ad(p1, q1), 1),
18193 );
18194 let mask = _mm256_and_si256(le(md, lim), le(bl, blim));
18195 let hev = _mm256_cmpgt_epi16(d1, hthr);
18196
18197 // `filter4`, in the centred domain.
18198 let centre = _mm256_set1_epi16((128 * scale) as i16);
18199 let lo = _mm256_set1_epi16((-128 * scale) as i16);
18200 let hi = _mm256_set1_epi16((128 * scale - 1) as i16);
18201 let ps1 = _mm256_sub_epi16(p1, centre);
18202 let ps0 = _mm256_sub_epi16(p0, centre);
18203 let qs0 = _mm256_sub_epi16(q0, centre);
18204 let qs1 = _mm256_sub_epi16(q1, centre);
18205 let outer = _mm256_and_si256(hev, sclamp(_mm256_sub_epi16(ps1, qs1), lo, hi));
18206 let f = sclamp(
18207 _mm256_add_epi16(
18208 outer,
18209 _mm256_mullo_epi16(_mm256_set1_epi16(3), _mm256_sub_epi16(qs0, ps0)),
18210 ),
18211 lo,
18212 hi,
18213 );
18214 let f1 = _mm256_srai_epi16(sclamp(_mm256_add_epi16(f, _mm256_set1_epi16(4)), lo, hi), 3);
18215 let f2 = _mm256_srai_epi16(sclamp(_mm256_add_epi16(f, _mm256_set1_epi16(3)), lo, hi), 3);
18216 let tap = _mm256_andnot_si256(
18217 hev,
18218 _mm256_srai_epi16(_mm256_add_epi16(f1, _mm256_set1_epi16(1)), 1),
18219 );
18220 let n_p1 = _mm256_add_epi16(sclamp(_mm256_add_epi16(ps1, tap), lo, hi), centre);
18221 let n_p0 = _mm256_add_epi16(sclamp(_mm256_add_epi16(ps0, f2), lo, hi), centre);
18222 let n_q0 = _mm256_add_epi16(sclamp(_mm256_sub_epi16(qs0, f1), lo, hi), centre);
18223 let n_q1 = _mm256_add_epi16(sclamp(_mm256_sub_epi16(qs1, tap), lo, hi), centre);
18224 let mut r = [
18225 p5,
18226 p4,
18227 p3,
18228 p2,
18229 _mm256_blendv_epi8(p1, n_p1, mask),
18230 _mm256_blendv_epi8(p0, n_p0, mask),
18231 _mm256_blendv_epi8(q0, n_q0, mask),
18232 _mm256_blendv_epi8(q1, n_q1, mask),
18233 q2,
18234 q3,
18235 q4,
18236 q5,
18237 ];
18238
18239 if len >= 6 {
18240 // `highbd_flat_mask4`, over the same reach as this length's mask.
18241 let mut fl = _mm256_max_epi16(
18242 _mm256_max_epi16(ad(p1, p0), ad(q1, q0)),
18243 _mm256_max_epi16(ad(p2, p0), ad(q2, q0)),
18244 );
18245 if len >= 8 {
18246 fl = _mm256_max_epi16(fl, _mm256_max_epi16(ad(p3, p0), ad(q3, q0)));
18247 }
18248 let flat = _mm256_and_si256(le(fl, fthr), mask);
18249 if len == 6 {
18250 let taps = [p2, p1, p0, q0, q1, q2];
18251 wrows!(r, 4, W6, taps, 3, flat, 0, 1, 2, 3);
18252 } else {
18253 let taps = [p3, p2, p1, p0, q0, q1, q2, q3];
18254 wrows!(r, 3, W8, taps, 3, flat, 0, 1, 2, 3, 4, 5);
18255 if len > 8 {
18256 let fl2 = _mm256_max_epi16(
18257 _mm256_max_epi16(
18258 _mm256_max_epi16(ad(p4, p0), ad(q4, q0)),
18259 _mm256_max_epi16(ad(p5, p0), ad(q5, q0)),
18260 ),
18261 _mm256_max_epi16(ad(p6, p0), ad(q6, q0)),
18262 );
18263 let flat2 = _mm256_and_si256(le(fl2, fthr), flat);
18264 // lane-deblock: `filter14`'s twelve rows as a RUNNING
18265 // sum. Consecutive `W14` rows differ by three or four
18266 // taps (row j+1 - row j is a constant vector with two
18267 // negative and two positive entries), so each output
18268 // costs one add, one sub and the rounding shift instead
18269 // of a fresh 14-tap weighted sum -- 168 tap operations
18270 // become 44. Exact: every partial sum is taken mod
18271 // 2^16 by `add/sub_epi16` and every ROW sum is a real
18272 // `W14` row, at most `16 * 4095 + 8 < 2^16`, so the
18273 // unsigned rounding shift sees the true value.
18274 // `deblock_simd_kernel_matches_the_scalar_filter` pins
18275 // it against `filter_edge` at 8/10/12-bit.
18276 let mut s = _mm256_add_epi16(
18277 _mm256_add_epi16(
18278 _mm256_mullo_epi16(p6, _mm256_set1_epi16(7)),
18279 _mm256_slli_epi16(_mm256_add_epi16(p5, p4), 1),
18280 ),
18281 _mm256_add_epi16(
18282 _mm256_add_epi16(_mm256_add_epi16(p3, p2), _mm256_add_epi16(p1, p0)),
18283 q0,
18284 ),
18285 );
18286 macro_rules! row14 {
18287 ($idx:literal) => {
18288 r[$idx] = _mm256_blendv_epi8(
18289 r[$idx],
18290 _mm256_srli_epi16(
18291 _mm256_add_epi16(s, _mm256_set1_epi16(8)),
18292 4,
18293 ),
18294 flat2,
18295 );
18296 };
18297 ($idx:literal, $plus:expr, $minus:expr) => {
18298 s = _mm256_sub_epi16(_mm256_add_epi16(s, $plus), $minus);
18299 row14!($idx);
18300 };
18301 }
18302 let add2 = |a, b| _mm256_add_epi16(a, b);
18303 row14!(0);
18304 row14!(1, add2(p3, q1), _mm256_slli_epi16(p6, 1));
18305 row14!(2, add2(p2, q2), add2(p6, p5));
18306 row14!(3, add2(p1, q3), add2(p6, p4));
18307 row14!(4, add2(p0, q4), add2(p6, p3));
18308 row14!(5, add2(q0, q5), add2(p6, p2));
18309 row14!(6, add2(q1, q6), add2(p6, p1));
18310 row14!(7, add2(q2, q6), add2(p5, p0));
18311 row14!(8, add2(q3, q6), add2(p4, q0));
18312 row14!(9, add2(q4, q6), add2(p3, q1));
18313 row14!(10, add2(q5, q6), add2(p2, q2));
18314 row14!(11, _mm256_slli_epi16(q6, 1), add2(p1, q3));
18315 }
18316 }
18317 }
18318
18319 // `r[j]` holds the sample at tap `j - 6`, i.e. `t[j + 2]`.
18320 let (a, b) = match len {
18321 4 | 6 => (4, 8),
18322 8 => (3, 9),
18323 _ => (0, 12),
18324 };
18325 for j in a..b {
18326 t[j + 2] = _mm256_min_epi16(_mm256_max_epi16(r[j], zero), smaxv);
18327 }
18328 }
18329
18330 /// 16 edge lines at `base`. `vertical` names the edge: a vertical edge's
18331 /// 16 lines are 16 consecutive rows and its taps are consecutive samples
18332 /// (loaded as a 16x16 tile and transposed), a horizontal edge's are 16
18333 /// consecutive columns with each tap a whole row segment.
18334 ///
18335 /// # Safety
18336 /// Requires AVX2. For a vertical edge `base % stride >= 8`, `base %
18337 /// stride + 8 <= stride` and 16 rows from `base` must be inside `data`;
18338 /// for a horizontal edge `base >= 8 * stride` and `base + 8 * stride`
18339 /// must be inside it.
18340 #[target_feature(enable = "avx2")]
18341 #[allow(clippy::too_many_arguments)]
18342 pub unsafe fn edge16(
18343 data: &mut [u16],
18344 base: usize,
18345 stride: usize,
18346 vertical: bool,
18347 len: u8,
18348 blimit: i32,
18349 limit: i32,
18350 hev_thr: i32,
18351 flat_thresh: i32,
18352 scale: i32,
18353 smax: i32,
18354 ) {
18355 let p = data.as_mut_ptr();
18356 let mut t = [_mm256_setzero_si256(); 16];
18357 // The taps this length reads, as `t` indices.
18358 let (lo, hi) = match len {
18359 4 => (6, 10),
18360 6 => (5, 11),
18361 8 => (4, 12),
18362 _ => (1, 15),
18363 };
18364 if vertical {
18365 for j in 0..16 {
18366 t[j] = _mm256_loadu_si256(p.add(base + j * stride - 8).cast());
18367 }
18368 transpose16(&mut t);
18369 } else {
18370 let top = base - 8 * stride;
18371 for i in lo..hi {
18372 t[i] = _mm256_loadu_si256(p.add(top + i * stride).cast());
18373 }
18374 }
18375 filter16(&mut t, len, blimit, limit, hev_thr, flat_thresh, scale, smax);
18376 if vertical {
18377 transpose16(&mut t);
18378 for j in 0..16 {
18379 _mm256_storeu_si256(p.add(base + j * stride - 8).cast(), t[j]);
18380 }
18381 } else {
18382 let top = base - 8 * stride;
18383 let (a, b) = match len {
18384 4 | 6 => (6, 10),
18385 8 => (5, 11),
18386 _ => (2, 14),
18387 };
18388 for i in a..b {
18389 _mm256_storeu_si256(p.add(top + i * stride).cast(), t[i]);
18390 }
18391 }
18392 }
18393}
18394
18395/// [`filter_edge`] for 16 adjacent edge lines that share `edge_params`'
18396/// output. Returns `false` when this build or CPU has no kernel, leaving the
18397/// caller on the scalar path.
18398#[allow(unused_variables)]
18399fn filter_edge16(
18400 data: &mut [u16],
18401 base: usize,
18402 stride: usize,
18403 vertical: bool,
18404 len: u8,
18405 level: i32,
18406 sharpness: u8, fctx: &crate::decode::FrameCtx,
18407) -> bool {
18408 #[cfg(target_arch = "x86_64")]
18409 {
18410 if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 {
18411 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
18412 let shift = bit_depth(fctx) - 8;
18413 // SAFETY: the avx2 arm is reached only when the CPU reports it,
18414 // and `deblock_plane` checks the kernel's edge bounds.
18415 #[allow(unsafe_code)]
18416 unsafe {
18417 deblock_simd::edge16(
18418 data,
18419 base,
18420 stride,
18421 vertical,
18422 len,
18423 blimit << shift,
18424 limit << shift,
18425 hev_thr << shift,
18426 1 << shift,
18427 1 << shift,
18428 sample_max(fctx),
18429 )
18430 };
18431 return true;
18432 }
18433 }
18434 false
18435}
18436
18437/// One plane's worth of spec 7.14: every vertical edge across the plane,
18438/// then every horizontal edge (the order the spec and libaom both use).
18439fn deblock_plane(
18440 plane: &mut PlaneBuf<'static>,
18441 plane_idx: usize,
18442 lf: &LoopFilterParams,
18443 n: &Neighbours,
18444 frame_width: usize,
18445 frame_height: usize, fctx: &crate::decode::FrameCtx,
18446) {
18447 let chroma = plane_idx != 0;
18448 // r7: libaom clips the deblock loop to the CODED frame's own
18449 // width/height, not the mi-aligned `true_width`/`true_height` margin
18450 // (the padding up to the next 8-pixel/superblock boundary that
18451 // reconstruction still fills in but the loop filter never visits).
18452 // Confirmed against the superres gate: with the margin included, the
18453 // last coded mi column's horizontal edges were filtered when libaom's
18454 // real output leaves them untouched (r6's post-deblock diff, 37 px, all
18455 // in columns 44-47); clipping here closes it (3/3 frames pixel-exact).
18456 // lane-golomb r9: the bound is the MI-ROUNDED frame, not the coded
18457 // frame. libaom's `av1_filter_block_plane_vert/horz` walk the superblock
18458 // and stop at `cm->mi_params.mi_cols`/`mi_rows`, which
18459 // `av1_set_mb_mi` derives from `ALIGN_POWER_OF_TWO(width, 3)` -- the
18460 // 8-pixel-aligned frame, i.e. a 68-wide frame is filtered out to column
18461 // 72 and the vertical edge AT x=68 is a real edge that rewrites the
18462 // in-crop columns 64..67. Clipping at `frame_width` skipped it, which is
18463 // the +-1 straddling-band defect (68x192 cq35, frame 1, 141 luma pixels
18464 // all in columns 64..67; frame 0 survived because that edge carried no
18465 // filter level there). r7's superres measurement is preserved: its frame
18466 // was already 8-aligned, so this bound equals `frame_width` there and
18467 // still excludes the superblock padding up to `true_width`.
18468 let (cw, ch) = if chroma {
18469 (frame_width.div_ceil(2), frame_height.div_ceil(2))
18470 } else {
18471 (frame_width, frame_height)
18472 };
18473 let (tw, th, stride) = (
18474 plane.true_width.min(cw),
18475 plane.true_height.min(ch),
18476 plane.width,
18477 );
18478 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") {
18479 eprintln!("DEBLOCK plane={plane_idx} tw={tw} th={th} stride={stride} true={}x{} crop={cw}x{ch}", plane.true_width, plane.true_height);
18480 }
18481 // lane-perf8: both passes iterate the edge's OWN direction innermost, so
18482 // 4 consecutive 4-sample groups (16 lines) can go through one AVX2
18483 // kernel. The swap is order-preserving: a filtered group overlaps only
18484 // groups along the edge it sits on -- the vertical pass's writes at
18485 // `x0` reach columns `x0 - 7 ..= x0 + 5` of its own 4 rows, so the
18486 // dependence is on ascending `x0` within a row, which stays the outer
18487 // loop's order, and rows remain independent (horizontal pass mirrored).
18488 let rows = plane.data.len() / stride.max(1);
18489 let seg_lf_active = fctx.seg.with(|s| s.borrow().enabled);
18490 // lane-filt1: both passes are split across `EC_AV1_FILTER_THREADS`
18491 // bands along the axis whose writes are disjoint. A vertical edge's
18492 // 4-sample groups write columns `x0-7 ..= x0+5` of their OWN 4 rows, so
18493 // row bands never touch each other; a horizontal edge's groups write rows
18494 // `y0-7 ..= y0+6` of their own 4 columns, so column bands never do. Both
18495 // read the mode-info grids immutably. The grouping a band starts with is
18496 // free: every 4-row (4-column) group's output is a pure function of that
18497 // group, whether it goes through `filter_edge16` with three neighbours or
18498 // through `filter_edge` alone. Band boundaries are multiples of 16 so no
18499 // group ever straddles one.
18500 // lane-perf10 merge: the output plane is owned (perf10 made mutable
18501 // plane params PlaneBuf<'static>); force the Cow to Owned ONCE here so
18502 // the bands below never clone it concurrently.
18503 plane.data.to_mut();
18504 let threads = crate::par::filter_threads();
18505 let sp = crate::par::Shared::new(plane);
18506 let vbands: Vec<(usize, usize)> = crate::par::bands(th.div_ceil(16), threads)
18507 .into_iter()
18508 .map(|(a, b)| (a * 16, (b * 16).min(th)))
18509 .collect();
18510 crate::par::run_bands(&vbands, fctx, |y_lo, y_hi, fctx| {
18511 // SAFETY: this band writes only rows `y_lo..y_hi` of the plane, which
18512 // no other band touches (see `Shared`'s own corner-cut note).
18513 #[allow(unsafe_code)]
18514 let plane = unsafe { sp.get() };
18515 let mut x0 = 4usize;
18516 while x0 < tw {
18517 let mut y0 = y_lo;
18518 while y0 < y_hi {
18519 if y0 + 16 <= y_hi && x0 >= 8 && x0 + 8 <= stride {
18520 let ps: [Option<(u8, i32)>; 4] =
18521 std::array::from_fn(|k| edge_params(lf, n, plane_idx, 0, chroma, x0, y0 + 4 * k, seg_lf_active, fctx));
18522 if let Some((len, level)) = ps[0] {
18523 if ps.iter().all(|p| *p == ps[0])
18524 && filter_edge16(
18525 plane.data.to_mut(),
18526 y0 * stride + x0,
18527 stride,
18528 true,
18529 len,
18530 level,
18531 lf.sharpness, fctx,
18532 )
18533 {
18534 y0 += 16;
18535 continue;
18536 }
18537 }
18538 for (k, p) in ps.iter().enumerate() {
18539 if let Some((len, level)) = *p {
18540 filter_edge(
18541 plane.data.to_mut(),
18542 (y0 + 4 * k) * stride + x0,
18543 stride as isize,
18544 1,
18545 len,
18546 level,
18547 lf.sharpness, fctx,
18548 );
18549 }
18550 }
18551 y0 += 16;
18552 continue;
18553 }
18554 if let Some((len, level)) = edge_params(lf, n, plane_idx, 0, chroma, x0, y0, seg_lf_active, fctx) {
18555 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") && plane_idx == 0 {
18556 eprintln!("VEDGE x0={x0} y0={y0} len={len} level={level}");
18557 }
18558 filter_edge(
18559 plane.data.to_mut(),
18560 y0 * stride + x0,
18561 stride as isize,
18562 1,
18563 len,
18564 level,
18565 lf.sharpness, fctx,
18566 );
18567 }
18568 y0 += 4;
18569 }
18570 x0 += 4;
18571 }
18572 });
18573 // The horizontal pass runs only after the WHOLE vertical pass of this
18574 // plane (spec 7.14 order), which `run_bands` guarantees by joining.
18575 let hbands: Vec<(usize, usize)> = crate::par::bands(tw.div_ceil(16), threads)
18576 .into_iter()
18577 .map(|(a, b)| (a * 16, (b * 16).min(tw)))
18578 .collect();
18579 crate::par::run_bands(&hbands, fctx, |x_lo, x_hi, fctx| {
18580 // SAFETY: this band writes only columns `x_lo..x_hi`.
18581 #[allow(unsafe_code)]
18582 let plane = unsafe { sp.get() };
18583 let mut y0 = 4usize;
18584 while y0 < th {
18585 let mut x0 = x_lo;
18586 while x0 < x_hi {
18587 if x0 + 16 <= x_hi && y0 >= 8 && y0 + 7 <= rows {
18588 let ps: [Option<(u8, i32)>; 4] =
18589 std::array::from_fn(|k| edge_params(lf, n, plane_idx, 1, chroma, x0 + 4 * k, y0, seg_lf_active, fctx));
18590 if let Some((len, level)) = ps[0] {
18591 if ps.iter().all(|p| *p == ps[0])
18592 && filter_edge16(
18593 plane.data.to_mut(),
18594 y0 * stride + x0,
18595 stride,
18596 false,
18597 len,
18598 level,
18599 lf.sharpness, fctx,
18600 )
18601 {
18602 x0 += 16;
18603 continue;
18604 }
18605 }
18606 for (k, p) in ps.iter().enumerate() {
18607 if let Some((len, level)) = *p {
18608 filter_edge(
18609 plane.data.to_mut(),
18610 y0 * stride + x0 + 4 * k,
18611 1,
18612 stride as isize,
18613 len,
18614 level,
18615 lf.sharpness, fctx,
18616 );
18617 }
18618 }
18619 x0 += 16;
18620 continue;
18621 }
18622 if let Some((len, level)) = edge_params(lf, n, plane_idx, 1, chroma, x0, y0, seg_lf_active, fctx) {
18623 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE")
18624 && plane_idx == 0
18625 && x0 == 44
18626 {
18627 eprintln!(
18628 "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}",
18629 lf.sharpness
18630 );
18631 }
18632 filter_edge(
18633 plane.data.to_mut(),
18634 y0 * stride + x0,
18635 1,
18636 stride as isize,
18637 len,
18638 level,
18639 lf.sharpness, fctx,
18640 );
18641 }
18642 x0 += 4;
18643 }
18644 y0 += 4;
18645 } });
18646}
18647
18648thread_local! {
18649 /// lane-perf6: reused whole-plane `u16` buffers. Every frame takes a
18650 /// pre-CDEF snapshot of all three planes, a post-deblock snapshot when
18651 /// loop restoration is active, and a fresh LR destination per plane --
18652 /// freshly allocated that is ~25 MB of `mmap`/`munmap` per frame at 4K,
18653 /// so every sample written also takes a first-touch page fault. The
18654 /// buffers are handed back here instead and refilled in place.
18655 static PLANE_SCRATCH: std::cell::RefCell<Vec<Vec<u16>>> =
18656 const { std::cell::RefCell::new(Vec::new()) };
18657}
18658
18659/// A pooled buffer holding a copy of `src`.
18660fn scratch_from(src: &[u16]) -> Vec<u16> {
18661 let mut v = PLANE_SCRATCH.with(|p| p.borrow_mut().pop()).unwrap_or_default();
18662 v.clear();
18663 v.extend_from_slice(src);
18664 v
18665}
18666
18667/// An empty pooled buffer, for a caller that fills it itself.
18668fn scratch_empty() -> Vec<u16> {
18669 let mut v = PLANE_SCRATCH.with(|p| p.borrow_mut().pop()).unwrap_or_default();
18670 v.clear();
18671 v
18672}
18673
18674/// A pooled buffer of exactly `n` samples whose contents are NOT cleared --
18675/// for a caller that writes every element it later reads (lane-copy: the
18676/// post-deblock snapshot writes 4 rows in 64 and reads no other).
18677fn scratch_sized(n: usize) -> Vec<u16> {
18678 let mut v = PLANE_SCRATCH.with(|p| p.borrow_mut().pop()).unwrap_or_default();
18679 if v.len() > n {
18680 v.truncate(n);
18681 } else if v.len() < n {
18682 v.resize(n, 0);
18683 }
18684 v
18685}
18686
18687/// A plane's post-deblock snapshot, its samples taken from the pool (every
18688/// other field is `usize`).
18689///
18690/// lane-copy: loop restoration is the only reader, and spec 7.17.2's stripe
18691/// boundary substitution reads the post-deblock plane at just four rows
18692/// around each interior stripe boundary (`row` outside
18693/// `[stripe_v_start, stripe_v_end)` resolves to `stripe_v_start-1`,
18694/// `stripe_v_start-2`, `stripe_v_end` or `stripe_v_end+1` in
18695/// `restoration::lr_src_row`); stripes are `64 >> ss_y` rows offset by
18696/// `RESTORATION_UNIT_OFFSET = 8 >> ss_y`, so the boundaries sit at
18697/// `k*stripe_h - offset`. Copying only those rows turns a full-plane
18698/// memmove per plane per frame into 4 rows in 64 (luma). Every other row of
18699/// the pooled buffer keeps whatever a previous frame left there -- an
18700/// initialised value that no reader ever reaches.
18701fn plane_snapshot(p: &PlaneBuf<'_>, ss_y: u32) -> PlaneBuf<'static> {
18702 let mut data = scratch_sized(p.data.len());
18703 let rows = if p.width == 0 { 0 } else { p.data.len() / p.width };
18704 let stripe_h = 64usize >> ss_y;
18705 let offset = 8usize >> ss_y;
18706 let mut b = stripe_h - offset;
18707 while b < rows {
18708 let (lo, hi) = (b - 2, (b + 2).min(rows));
18709 data[lo * p.width..hi * p.width].copy_from_slice(&p.data[lo * p.width..hi * p.width]);
18710 b += stripe_h;
18711 }
18712 PlaneBuf { data: std::borrow::Cow::Owned(data), ..*p }
18713}
18714
18715/// The output crop, taking the plane by value: a frame whose width is
18716/// already superblock-aligned (only its height is padded) has a padded
18717/// buffer whose stride equals the visible width, so the crop is a pure
18718/// truncation of the buffer we already own -- no full-plane copy at all
18719/// (lane-copy: three ~6 MB memmoves per 4K frame on the frame thread's
18720/// serial tail). Any other shape falls back to the row-by-row copy.
18721fn crop_owned(plane: PlaneBuf<'_>, w: usize, h: usize) -> Vec<u16> {
18722 let stride = plane.width;
18723 let mut data = plane.data.into_owned();
18724 if stride == w {
18725 data.truncate(w * h);
18726 return data;
18727 }
18728 let mut out = Vec::with_capacity(w * h);
18729 for row in 0..h {
18730 out.extend(data[row * stride..][..w].iter().copied());
18731 }
18732 out
18733}
18734
18735/// Hands a buffer back to the pool; the capacity is what is worth keeping.
18736fn scratch_return(v: Vec<u16>) {
18737 PLANE_SCRATCH.with(|p| p.borrow_mut().push(v));
18738}
18739
18740/// One CDEF mi-row band, as a real function rather than the body of the
18741/// `run_bands` closure: inside the closure the destination planes are
18742/// `&mut` references derived from a `par::Shared` raw pointer in the same
18743/// scope as the `src_*` snapshot reads, so LLVM cannot tell the two apart and
18744/// re-loads through them on every tap. Reference parameters restore `noalias`
18745/// (lane-perf11 (a): -x% instructions at one filter thread).
18746#[allow(clippy::too_many_arguments)]
18747fn cdef_band(
18748 r_lo: usize,
18749 r_hi: usize,
18750 y: &mut PlaneBuf<'static>,
18751 u: &mut PlaneBuf<'static>,
18752 v: &mut PlaneBuf<'static>,
18753 src_y: &[u16],
18754 src_u: &[u16],
18755 src_v: &[u16],
18756 cdef: &CdefParams,
18757 skip_grid: &Neighbours,
18758 idx_grid: &[u8],
18759 sb_cols: usize,
18760 coeff_shift: i32,
18761 damping: i32,
18762 damping_uv: i32,
18763 (frame_w, frame_h): (usize, usize),
18764 fctx: &crate::decode::FrameCtx,
18765) {
18766 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
18767 if sb_cols == 0 {
18768 return 0;
18769 }
18770 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
18771 idx_grid.get(sb_r * sb_cols + sb_c).copied().unwrap_or(0) as usize
18772 };
18773 // One scratch window per plane kind, reused by every unit (8x8 luma and
18774 // 4x4 chroma, each grown by the [`CDEF_BORDER`] tap ring).
18775 let mut win_y = [0i32; (8 + 2 * CDEF_BORDER) * (8 + 2 * CDEF_BORDER)];
18776 let mut win_uv = [0i32; (4 + 2 * CDEF_BORDER) * (4 + 2 * CDEF_BORDER)];
18777 let mut mi_r = r_lo;
18778 while mi_r < r_hi {
18779 let mut mi_c = 0usize;
18780 while mi_c < skip_grid.mi_cols {
18781 if skip_grid.is_skip_txfm(mi_r, mi_c) {
18782 CDEF_SKIPPED_UNITS.with(|c| c.set(c.get() + 1));
18783 }
18784 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
18785 let sidx = strength_idx(mi_r, mi_c);
18786 let (ox, oy) = (mi_c * 4, mi_r * 4);
18787 // Nothing to do for this unit at all: the direction search is
18788 // only ever consumed through a strength, so a unit whose four
18789 // strengths are zero never needs its 8x8 window gathered.
18790 if cdef.y_pri_strength[sidx] == 0
18791 && cdef.y_sec_strength[sidx] == 0
18792 && cdef.uv_pri_strength[sidx] == 0
18793 && cdef.uv_sec_strength[sidx] == 0
18794 {
18795 mi_c += 2;
18796 continue;
18797 }
18798 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
18799 cdef_gather(src_y, y_stride, y_true_w, y_true_h, ox, oy, 8, 8, &mut win_y);
18800 let sample_y = |r: i32, c: i32| -> i32 {
18801 win_y[(r + CDEF_BORDER as i32) as usize * (8 + 2 * CDEF_BORDER)
18802 + (c + CDEF_BORDER as i32) as usize]
18803 };
18804 // lane-cdef r1: the direction search reads the SAME padded
18805 // block the taps do -- libaom runs `cdef_find_dir` on the
18806 // prepared filter block (`cdef_block.c:296-320` over
18807 // `cdef_prepare_fb`'s buffer, `cdef.c:249-256`), whose columns
18808 // and rows past the mi-rounded frame extent are CDEF_VERY_LARGE.
18809 // Clamping to the last real sample instead made every straddling
18810 // edge 8x8 (odd `mi_cols`/`mi_rows`) pick a different var, hence
18811 // a different `adjust_strength`, hence a +-1 band at the crop edge.
18812 let (dir, var) = cdef_find_dir(coeff_shift, |r, c| sample_y(r as i32, c as i32));
18813
18814 // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
18815 // -- each plane zeroes the shared direction when *its own*
18816 // frame-level primary strength is 0, independent of the
18817 // per-block adjusted `t` and of the other plane's strength.
18818 let y_pri_strength = i32::from(cdef.y_pri_strength[sidx]) << coeff_shift;
18819 let y_sec_strength = i32::from(cdef.y_sec_strength[sidx]) << coeff_shift;
18820 let y_dir = if y_pri_strength != 0 { dir } else { 0 };
18821 let t = cdef_adjust_strength(y_pri_strength, var);
18822 // lane-cdef r1 rung: one line per filtered 8x8 luma CDEF unit.
18823 if crate::envflags::env_flag!("EC_AV1_CDEF_DBG") {
18824 eprintln!(
18825 "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}"
18826 );
18827 }
18828 let enable_primary = t != 0;
18829 let enable_secondary = y_sec_strength != 0;
18830 if (ox + 8 > frame_w || oy + 8 > frame_h)
18831 && (enable_primary
18832 || enable_secondary
18833 || cdef.uv_pri_strength[sidx] != 0
18834 || cdef.uv_sec_strength[sidx] != 0)
18835 {
18836 CDEF_STRADDLE_UNITS.with(|c| c.set(c.get() + 1));
18837 }
18838 if enable_primary || enable_secondary {
18839 cdef_filter_block(
18840 &win_y,
18841 y,
18842 ox,
18843 oy,
18844 8,
18845 8,
18846 t,
18847 y_sec_strength,
18848 y_dir,
18849 damping,
18850 damping,
18851 enable_primary,
18852 enable_secondary,
18853 coeff_shift, fctx,
18854 );
18855 }
18856
18857 let t_uv = i32::from(cdef.uv_pri_strength[sidx]) << coeff_shift;
18858 let uv_sec_strength = i32::from(cdef.uv_sec_strength[sidx]) << coeff_shift;
18859 let uv_dir = if t_uv != 0 { dir } else { 0 };
18860 let enable_primary_uv = t_uv != 0;
18861 let enable_secondary_uv = uv_sec_strength != 0;
18862 if enable_primary_uv || enable_secondary_uv {
18863 let (cox, coy) = (ox / 2, oy / 2);
18864 for (plane, src_p) in [(&mut *u, src_u), (&mut *v, src_v)] {
18865 let (tw, th) = (plane.true_width, plane.true_height);
18866 let stride = plane.width;
18867 cdef_gather(src_p, stride, tw, th, cox, coy, 4, 4, &mut win_uv);
18868 cdef_filter_block(
18869 &win_uv,
18870 plane,
18871 cox,
18872 coy,
18873 4,
18874 4,
18875 t_uv,
18876 uv_sec_strength,
18877 uv_dir,
18878 damping_uv,
18879 damping_uv,
18880 enable_primary_uv,
18881 enable_secondary_uv,
18882 coeff_shift, fctx,
18883 );
18884 }
18885 }
18886 }
18887 mi_c += 2;
18888 }
18889 mi_r += 2;
18890 }
18891}
18892
18893fn apply_cdef(
18894 y: &mut PlaneBuf<'static>,
18895 u: &mut PlaneBuf<'static>,
18896 v: &mut PlaneBuf<'static>,
18897 cdef: &CdefParams,
18898 skip_grid: &Neighbours,
18899 // This frame header's own CROPPED luma size, for the straddling-unit
18900 // counter only -- CDEF itself walks the mi-rounded plane.
18901 (frame_w, frame_h): (usize, usize), fctx: &crate::decode::FrameCtx,
18902) {
18903 // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling.
18904 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_CDEF") {
18905 return;
18906 }
18907 // lane-cdefstrip r1 instrument, BEFORE either early return so it is valid
18908 // for every frame: an 8x8 CDEF unit none of whose four mi cells a coded
18909 // block wrote this frame. `Neighbours` seeds `skip_grid` all-false, so a
18910 // decode arm that forgets `fill_skip_grid_rect` reads "not skip" and CDEF
18911 // filters a unit libaom's `is_8x8_block_skip` (`cdef.c:29-38`) may exclude.
18912 // Always 0 on every stream measured; a gate asserts it stays 0.
18913 {
18914 let mut r = 0usize;
18915 while r < skip_grid.mi_rows {
18916 let mut c = 0usize;
18917 while c < skip_grid.mi_cols {
18918 if (0..2).any(|rr| {
18919 (0..2).any(|cc| {
18920 !skip_grid
18921 .skip_written
18922 .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc))
18923 .copied()
18924 .unwrap_or(true)
18925 })
18926 }) {
18927 CDEF_UNWRITTEN_SKIP_UNITS.with(|c2| c2.set(c2.get() + 1));
18928 if crate::envflags::env_flag!("EC_AV1_DEBUG_CDEF_BAND") {
18929 eprintln!("cdef band unwritten at mi ({r},{c}) px ({},{})", r * 4, c * 4);
18930 }
18931 }
18932 let cell = |rr: usize, cc: usize| {
18933 skip_grid
18934 .skip_grid
18935 .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc))
18936 .copied()
18937 .unwrap_or(false)
18938 };
18939 let first = cell(0, 0);
18940 if (0..2).any(|rr| (0..2).any(|cc| cell(rr, cc) != first)) {
18941 CDEF_MIXED_SKIP_UNITS.with(|c2| c2.set(c2.get() + 1));
18942 }
18943 c += 2;
18944 }
18945 r += 2;
18946 }
18947 }
18948 // `cdef.bits == 0` still means "no filtering at all" whenever the single
18949 // (index 0) strength pair is all-zero -- the fast path every existing
18950 // gate stream takes. A `bits > 0` frame can still be all-zero-strength
18951 // at every index, but that is rare enough not to special-case; the
18952 // per-superblock lookup below degrades to the same index-0 read anyway
18953 // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`).
18954 if cdef.bits == 0
18955 && cdef.y_pri_strength[0] == 0
18956 && cdef.y_sec_strength[0] == 0
18957 && cdef.uv_pri_strength[0] == 0
18958 && cdef.uv_sec_strength[0] == 0
18959 {
18960 return;
18961 }
18962 let sb_cols = fctx.cdef_sb_cols.with(|c| c.get());
18963 // One entry per superblock (a few hundred at 4K), so this clone is not
18964 // one of the per-frame copies lane-perf6 pooled below.
18965 let idx_grid = fctx.cdef_idx_grid.with(|g| g.borrow().clone());
18966 let src_y = scratch_from(&y.data);
18967 let src_u = scratch_from(&u.data);
18968 let src_v = scratch_from(&v.data);
18969 // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`,
18970 // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`.
18971 let coeff_shift = i32::from(bit_depth(fctx)) - 8;
18972 let damping = i32::from(cdef.damping) + coeff_shift;
18973 let damping_uv = (damping - 1).max(0);
18974 // lane-filt1: every CDEF unit reads ONLY the pre-CDEF snapshots
18975 // (`src_y`/`src_u`/`src_v`, immutable here) and writes its own 8x8 luma /
18976 // 4x4 chroma square, so units are independent. Bands are mi ROW bands (2
18977 // mi = 8 luma rows, 4 chroma rows), which makes each band's writes a
18978 // disjoint row range of all three planes.
18979 let (sy, su, sv) = (
18980 crate::par::Shared::new(y),
18981 crate::par::Shared::new(u),
18982 crate::par::Shared::new(v),
18983 );
18984 let mi_rows = skip_grid.mi_rows;
18985 let cbands: Vec<(usize, usize)> = crate::par::bands(mi_rows.div_ceil(2), crate::par::filter_threads())
18986 .into_iter()
18987 .map(|(a, b)| (a * 2, (b * 2).min(mi_rows)))
18988 .collect();
18989 crate::par::run_bands(&cbands, fctx, |r_lo, r_hi, fctx| {
18990 // SAFETY: this band writes only the plane rows its own mi rows cover,
18991 // disjoint from every other band's (see `Shared`).
18992 #[allow(unsafe_code)]
18993 let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) };
18994 cdef_band(
18995 r_lo,
18996 r_hi,
18997 y,
18998 u,
18999 v,
19000 &src_y,
19001 &src_u,
19002 &src_v,
19003 cdef,
19004 skip_grid,
19005 &idx_grid,
19006 sb_cols,
19007 coeff_shift,
19008 damping,
19009 damping_uv,
19010 (frame_w, frame_h),
19011 fctx,
19012 );
19013 });
19014 scratch_return(src_y);
19015 scratch_return(src_u);
19016 scratch_return(src_v);
19017}
19018
19019/// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
19020/// ordering note: libaom also runs `superres_post_decode` between the two,
19021/// but this decoder never implements super-resolution, so there is nothing
19022/// to interleave). `deblocked_*` is each plane's post-deblock, pre-CDEF
19023/// buffer (the caller clones it before calling [`apply_cdef`]) -- loop
19024/// restoration's stripe-boundary rows read from it instead of the
19025/// CDEF-filtered plane, per `restoration.rs`'s own `lr_sample` doc comment.
19026#[allow(clippy::too_many_arguments)]
19027fn apply_loop_restoration(
19028 y: &mut PlaneBuf<'static>,
19029 u: &mut PlaneBuf<'static>,
19030 v: &mut PlaneBuf<'static>,
19031 deblocked_y: &PlaneBuf<'_>,
19032 deblocked_u: &PlaneBuf<'_>,
19033 deblocked_v: &PlaneBuf<'_>,
19034 lr: &LoopRestorationParams,
19035 grid: &crate::restoration::RestorationGrid,
19036 // lane-golomb r8: this frame header's own (cropped) luma size. Loop
19037 // restoration is the ONE post-decode filter that does NOT run over the
19038 // mi-rounded plane: libaom's `av1_loop_restoration_filter_frame` sizes
19039 // every plane with `av1_get_upsampled_plane_size` -- `plane_w =
19040 // ROUND_POWER_OF_TWO(cm->superres_upscaled_width, ss_x)`, `plane_h =
19041 // ROUND_POWER_OF_TWO(cm->height, ss_y)` (`av1/common/restoration.c:47`)
19042 // -- and asserts it equals the buffer's CROP width
19043 // (`restoration.c:1106`), then `av1_extend_frame(..., plane_w, plane_h,
19044 // ...)` (`restoration.c:1109`) replicates the right/bottom border from
19045 // that cropped edge before any unit is filtered. Deblock and CDEF DO
19046 // walk the mi grid, which is why passing `true_width`/`true_height`
19047 // here went unnoticed until a frame whose size is not a multiple of 8
19048 // (68 -> mi-rounded 72): the LR taps at the last four real columns then
19049 // read this decoder's own decoded samples at columns 68..71 where
19050 // libaom reads column 67 replicated -- +-1 over the straddling band
19051 // (class av1-truesize-lane: true frame size vs mi-rounded).
19052 (frame_w, frame_h): (usize, usize), fctx: &crate::decode::FrameCtx,
19053) {
19054 let mut out = scratch_empty();
19055 crate::restoration::apply_loop_restoration_plane(
19056 &y.data,
19057 &deblocked_y.data,
19058 y.width,
19059 frame_w,
19060 frame_h,
19061 0,
19062 lr.frame_restoration_type[0],
19063 lr.loop_restoration_size[0],
19064 grid,
19065 0,
19066 &mut out, fctx,
19067 );
19068 scratch_return(std::mem::replace(&mut y.data, std::borrow::Cow::Owned(out)).into_owned());
19069 let mut out = scratch_empty();
19070 crate::restoration::apply_loop_restoration_plane(
19071 &u.data,
19072 &deblocked_u.data,
19073 u.width,
19074 frame_w.div_ceil(2),
19075 frame_h.div_ceil(2),
19076 1,
19077 lr.frame_restoration_type[1],
19078 lr.loop_restoration_size[1],
19079 grid,
19080 1,
19081 &mut out, fctx,
19082 );
19083 scratch_return(std::mem::replace(&mut u.data, std::borrow::Cow::Owned(out)).into_owned());
19084 let mut out = scratch_empty();
19085 crate::restoration::apply_loop_restoration_plane(
19086 &v.data,
19087 &deblocked_v.data,
19088 v.width,
19089 frame_w.div_ceil(2),
19090 frame_h.div_ceil(2),
19091 1,
19092 lr.frame_restoration_type[2],
19093 lr.loop_restoration_size[2],
19094 grid,
19095 2,
19096 &mut out, fctx,
19097 );
19098 scratch_return(std::mem::replace(&mut v.data, std::borrow::Cow::Owned(out)).into_owned());
19099}
19100
19101/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
19102/// returning the picture it reconstructs to.
19103///
19104/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
19105/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
19106/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
19107/// `compute_image_size` derives one from the other, but not losslessly: a
19108/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
19109/// what the reconstruction is cropped to on the way out, mirroring
19110/// [`crate::encode::crop_encoded`].
19111///
19112/// # Errors
19113/// Returns an error when a block's partition, mode, skip flag or transform
19114/// type is anything this decoder does not reconstruct (round 2: inter, tx
19115/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
19116/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
19117/// or when the tile payload runs out of the symbols this decode expects (a
19118/// genuinely foreign stream).
19119#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
19120pub(crate) fn decode_key_frame_tile(
19121 data: &[u8],
19122 mi_cols: u32,
19123 mi_rows: u32,
19124 base_q_idx: u8,
19125 frame_width: u32,
19126 frame_height: u32,
19127 enable_filter_intra: bool,
19128 cdef: &CdefParams,
19129 loop_filter: &LoopFilterParams,
19130 tx_select: bool,
19131 reduced_tx_set: bool,
19132 allow_screen_content_tools: bool,
19133 allow_intrabc: bool, fctx: &crate::decode::FrameCtx,
19134) -> Result<Picture> {
19135 let delta = DeltaParams::default();
19136 let single_tile = TileInfo {
19137 mi_col_starts: vec![0, mi_cols],
19138 mi_row_starts: vec![0, mi_rows],
19139 ..TileInfo::default()
19140 };
19141 decode_key_frame_tile_with_cdfs(
19142 &[data],
19143 &single_tile,
19144 mi_cols,
19145 mi_rows,
19146 base_q_idx,
19147 crate::quant::QuantDeltas::default(),
19148 frame_width,
19149 frame_height,
19150 enable_filter_intra,
19151 false,
19152 cdef,
19153 loop_filter,
19154 &LoopRestorationParams::default(),
19155 None,
19156 tx_select,
19157 reduced_tx_set,
19158 allow_screen_content_tools,
19159 allow_intrabc,
19160 delta, fctx,
19161 )
19162 .map(|(picture, _)| picture)
19163}
19164
19165 /// lane-superres r3: the real decoded margin beyond `frame_width` up to
19166 /// the mi-aligned `true_width`, set by the most recent
19167 /// [`decode_key_frame_tile_with_cdfs`] OR (lane-superres r10)
19168 /// [`decode_inter_frame_tile_with_cdfs`] call -- both frame kinds crop
19169 /// their reconstructed buffer down from the same mi-aligned extent, so
19170 /// they share this one slot. See each function's own comment at its
19171 /// write site. `None` when there was no margin to save.
19172
19173/// The margin the most recent key- or inter-frame tile decode stashed
19174/// (see [`LAST_FRAME_WIDE_MARGIN`]) -- `stream.rs`'s superres path
19175/// reads this immediately after the call, before any other frame
19176/// decode can overwrite it.
19177#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
19178pub(crate) fn take_last_frame_wide_margin(fctx: &crate::decode::FrameCtx) -> Option<Picture> {
19179 fctx.last_frame_wide_margin.with(|m| m.borrow_mut().take())
19180}
19181
19182/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
19183/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
19184/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
19185/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs,
19186/// since a key frame's own header always forces `primary_ref_frame ==
19187/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table
19188/// alongside the picture, for the caller to save into whichever reference
19189/// slots this frame's `refresh_frame_flags` names.
19190/// The order the 64x64 superblock quadrants of a tile are decoded in.
19191///
19192/// At `sb_size == 64` this is plain raster order over the tile's own
19193/// superblock grid. At `sb_size == 128` libaom's `decode_partition` recurses
19194/// each 128x128 superblock in raster order and visits its four 64x64
19195/// quadrants (TL, TR, BL, BR) before moving to the next superblock, so the
19196/// 64-level bodies must run in that nested order. `row_start` marks the first
19197/// item of each *superblock* row (where the left neighbour context resets),
19198/// `sb_start` the first item of each superblock (where the 128 root's own
19199/// loop-restoration units and partition symbol are read).
19200fn sb_visit_order(r0: u32, r1: u32, c0: u32, c1: u32, sb128: bool) -> Vec<(u32, u32, bool, bool)> {
19201 let mut out = Vec::new();
19202 if !sb128 {
19203 for r in r0..r1 {
19204 for c in c0..c1 {
19205 out.push((r, c, c == c0, true));
19206 }
19207 }
19208 return out;
19209 }
19210 let mut r = r0;
19211 while r < r1 {
19212 let mut first_in_row = true;
19213 let mut c = c0;
19214 while c < c1 {
19215 let mut first_in_sb = true;
19216 for qr in 0..2 {
19217 for qc in 0..2 {
19218 let (rr, cc) = (r + qr, c + qc);
19219 if rr >= r1 || cc >= c1 {
19220 continue;
19221 }
19222 out.push((rr, cc, first_in_row, first_in_sb));
19223 first_in_row = false;
19224 first_in_sb = false;
19225 }
19226 }
19227 c += 2;
19228 }
19229 r += 2;
19230 }
19231 out
19232}
19233
19234// lane-sb128 r2: the 128x128 superblock root, shared by the key-frame and
19235// the inter tile loop. Its loop-restoration units are read once for the whole
19236// 128x128 (spec 5.11.57 is called with the superblock's own size), then one
19237// partition symbol off the `BLOCK_128X128` CDF (8 symbols, no HORZ_4/VERT_4)
19238// decides the root -- only SPLIT recurses into the four 64x64 quadrants this
19239// decoder codes, the other seven arms refuse by name.
19240thread_local! {
19241 /// How many 128x128 superblock roots resolved to `PARTITION_NONE` -- one
19242 /// whole 128x128 block (lane-sb128b r1's gate counter).
19243 pub(crate) static PART128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
19244 /// 128 roots that resolved to PARTITION_HORZ (two 128x64 pieces, or one
19245 /// when the bottom half is out of frame) -- lane-sb128c r7.
19246 pub(crate) static PART128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
19247 /// 128 roots that resolved to PARTITION_VERT (two 64x128 pieces).
19248 pub(crate) static PART128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
19249 /// Of those, the ones decided by the GATHERED bit at a frame edge -- the
19250 /// only shape a 1080p (mi_rows = 270) stream reaches.
19251 pub(crate) static PART128_EDGE_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
19252 pub(crate) static PART128_EDGE_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
19253 /// lane-sb128c r9: 128 roots that resolved to one of the four AB shapes,
19254 /// in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order.
19255 pub(crate) static PART128_AB_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
19256}
19257
19258/// [`PART128_AB_HITS`], for a gate's own before/after delta.
19259pub(crate) fn part128_ab_hits() -> [usize; 4] {
19260 PART128_AB_HITS.with(std::cell::Cell::get)
19261}
19262
19263/// [`PART128_NONE_HITS`], for a gate's own before/after delta.
19264#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
19265pub(crate) fn part128_none_hits() -> usize {
19266 PART128_NONE_HITS.with(std::cell::Cell::get)
19267}
19268
19269/// [`PART128_HORZ_HITS`], for a gate's own before/after delta.
19270#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
19271pub(crate) fn part128_horz_hits() -> usize {
19272 PART128_HORZ_HITS.with(std::cell::Cell::get)
19273}
19274
19275/// [`PART128_VERT_HITS`], for a gate's own before/after delta.
19276#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
19277pub(crate) fn part128_vert_hits() -> usize {
19278 PART128_VERT_HITS.with(std::cell::Cell::get)
19279}
19280
19281/// [`PART128_EDGE_HORZ_HITS`] -- gathered-bit HORZ at the bottom frame edge.
19282pub(crate) fn part128_edge_horz_hits() -> usize {
19283 PART128_EDGE_HORZ_HITS.with(std::cell::Cell::get)
19284}
19285
19286/// [`PART128_EDGE_VERT_HITS`] -- gathered-bit VERT at the right frame edge.
19287pub(crate) fn part128_edge_vert_hits() -> usize {
19288 PART128_EDGE_VERT_HITS.with(std::cell::Cell::get)
19289}
19290
19291thread_local! {
19292 /// How many CHROMA transform units were coded inside a block whose uv
19293 /// plane block is more than one unit (lane-sb128b r2 -- only a 128x128
19294 /// block, four per plane).
19295 pub(crate) static CHROMA_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
19296}
19297
19298/// [`CHROMA_SPLIT_TX_HITS`], for a gate's own before/after delta.
19299#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
19300pub(crate) fn chroma_split_tx_hits() -> usize {
19301 CHROMA_SPLIT_TX_HITS.with(std::cell::Cell::get)
19302}
19303
19304fn read_sb128_root(
19305 dec: &mut SymbolDecoder,
19306 cdfs: &mut Cdfs,
19307 neighbours: &Neighbours,
19308 lr: &LoopRestorationParams,
19309 lr_grid: &mut crate::restoration::RestorationGrid,
19310 lr_reference: &mut [(
19311 crate::restoration::WienerInfo,
19312 crate::restoration::SgrprojInfo,
19313 ); 3],
19314 sb_r: u32,
19315 sb_c: u32,
19316 mi_cols: u32,
19317 mi_rows: u32, fctx: &crate::decode::FrameCtx,
19318) -> Result<usize> {
19319 let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI);
19320 crate::restoration::read_lr(
19321 dec,
19322 cdfs,
19323 lr,
19324 lr_grid,
19325 lr_reference,
19326 mi_r128,
19327 mi_c128,
19328 SB_MI * 2, fctx,
19329 );
19330 let at128 = ((mi_r128 / SUB_MI) as usize, (mi_c128 / SUB_MI) as usize);
19331 let ctx128 = neighbours.partition_ctx(at128, 128);
19332 let (has_cols128, has_rows128) = (mi_c128 + SB_MI < mi_cols, mi_r128 + SB_MI < mi_rows);
19333 let part128 = if has_cols128 && has_rows128 {
19334 PART128_SYMBOLS.with(|c| c.set(c.get() + 1));
19335 let p = dec.symbol(&mut cdfs.partition_w128[ctx128]);
19336 if crate::envflags::env_flag!("EC_AV1_TRACE") {
19337 eprintln!("TRACE partition_w128 ctx={ctx128} value={p}");
19338 }
19339 p
19340 } else {
19341 // lane-sb128 r4: the gathered half-out-of-frame reads DECIDE the
19342 // partition, they are not a forced split -- exactly the discarded-bit
19343 // defect the 64 root carries a comment about at `partition_w64`'s
19344 // gathered arm. Value 1 is SPLIT; 0 is HORZ (rows out of frame) or
19345 // VERT (cols out of frame), which the refusal below then names
19346 // instead of silently reconstructing a split.
19347 PART128_GATHERED_SYMBOLS.with(|c| c.set(c.get() + 1));
19348 match (has_cols128, has_rows128) {
19349 (true, false) => {
19350 if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &VERT_ALIKE128)) == 1 {
19351 PARTITION_SPLIT
19352 } else {
19353 PART128_EDGE_HORZ_HITS.with(|c| c.set(c.get() + 1));
19354 PARTITION_HORZ
19355 }
19356 }
19357 (false, true) => {
19358 if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &HORZ_ALIKE128)) == 1 {
19359 PARTITION_SPLIT
19360 } else {
19361 PART128_EDGE_VERT_HITS.with(|c| c.set(c.get() + 1));
19362 PARTITION_VERT
19363 }
19364 }
19365 _ => {
19366 PART128_GATHERED_SYMBOLS.with(|c| c.set(c.get() - 1));
19367 bump_edge_both_cut(3);
19368 PARTITION_SPLIT
19369 }
19370 }
19371 };
19372 // lane-sb128b r1: `PARTITION_NONE` -- one 128x128 block -- is decoded by
19373 // the key-frame caller below. The six remaining arms (HORZ/VERT and the
19374 // four AB shapes) still need the rect/AB machinery at this size.
19375 // lane-sb128c r7: HORZ (two 128x64) and VERT (two 64x128) now decode on
19376 // both tile paths. The four AB shapes (libaom `decode_partition`'s
19377 // PARTITION_HORZ_A..VERT_B, decodeframe.c) still need the mixed
19378 // 128x64 + 64x64 + 64x64 visit order and stay refused by name; a 128
19379 // root has no 1:4 arm at all (`PARTITION_HORZ_4`/`VERT_4` are excluded
19380 // for BLOCK_128X128 by `av1_get_partition_cdf`'s 8-symbol alphabet,
19381 // which stops at VERT_B).
19382 match part128 {
19383 PARTITION_SPLIT => PART128_SPLIT_HITS.with(|c| c.set(c.get() + 1)),
19384 PARTITION_NONE => PART128_NONE_HITS.with(|c| c.set(c.get() + 1)),
19385 PARTITION_HORZ => PART128_HORZ_HITS.with(|c| c.set(c.get() + 1)),
19386 PARTITION_VERT => PART128_VERT_HITS.with(|c| c.set(c.get() + 1)),
19387 // lane-sb128c r9: the four AB shapes at the 128 root -- one
19388 // 128x64/64x128 half plus two 64x64 quadrants, decoded by both tile
19389 // paths below in libaom `decode_partition`'s own visit order.
19390 p if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&p) => {
19391 PART128_AB_HITS.with(|c| {
19392 let mut h = c.get();
19393 h[p - PARTITION_HORZ_A] += 1;
19394 c.set(h);
19395 });
19396 }
19397 _ => {
19398 return Err(unsupported(
19399 "a 128x128 superblock partition value outside the 8-symbol alphabet",
19400 ));
19401 }
19402 }
19403 Ok(part128)
19404}
19405
19406pub(crate) fn decode_key_frame_tile_with_cdfs(
19407 tiles: &[&[u8]],
19408 tile_info: &TileInfo,
19409 mi_cols: u32,
19410 mi_rows: u32,
19411 base_q_idx: u8,
19412 // lane-sbpart r11: this frame header's own per-plane DC/AC quantizer
19413 // deltas (spec 5.9.12), threaded to [`QUANT_DELTAS`] at the top of every
19414 // tile alongside [`CURRENT_Q_IDX`].
19415 deltas: crate::quant::QuantDeltas,
19416 frame_width: u32,
19417 frame_height: u32,
19418 enable_filter_intra: bool,
19419 enable_edge_filter: bool,
19420 cdef: &CdefParams,
19421 loop_filter: &LoopFilterParams,
19422 lr: &LoopRestorationParams,
19423 initial_cdfs: Option<Cdfs>,
19424 tx_select: bool,
19425 reduced_tx_set: bool,
19426 allow_screen_content_tools: bool,
19427 allow_intrabc: bool,
19428 // lane-realworld r4: this frame header's own `delta` (spec 5.9.17/5.9.18)
19429 // -- only `q_present`/`q_res` are actually read ([`maybe_read_delta_q`]);
19430 // `stream.rs` still refuses a frame with `lf_present` set before this
19431 // function is ever called.
19432 delta: DeltaParams, fctx: &crate::decode::FrameCtx,
19433) -> Result<(Picture, Cdfs)> {
19434 // lane-frame80: [`TX_SELECT_INTER`] is set by the INTER tile decoder
19435 // only, so a key frame decoded after an inter frame on this thread would
19436 // otherwise inherit it and read its `tx_depth` context off the inter
19437 // frame's stale `TXFM_CONTEXT` bands.
19438 fctx.tx_select_inter.with(|c| c.set(false));
19439 if mi_cols == 0 || mi_rows == 0 {
19440 return Err(unsupported("a frame with no mode-info grid"));
19441 }
19442 fctx.enable_edge_filter.with(|f| f.set(enable_edge_filter));
19443 let sb128 = sb128(fctx);
19444 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
19445 fctx.intrabc_mi_grid.with(|g| {
19446 *g.borrow_mut() = allow_intrabc.then(|| {
19447 (
19448 crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize),
19449 mi_cols as usize,
19450 mi_rows as usize,
19451 )
19452 });
19453 });
19454 fctx.intrabc_dv.with(|c| c.set(None));
19455 fctx.cdef_bits.with(|c| c.set(cdef.bits));
19456 fctx.cdef_sb_cols.with(|c| c.set(sb_cols as usize));
19457 fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
19458 fctx.delta_q_present.with(|c| c.set(delta.q_present));
19459 fctx.delta_q_res.with(|c| c.set(1i32 << delta.q_res));
19460 fctx.delta_lf_present.with(|c| c.set(delta.lf_present));
19461 fctx.delta_lf_res.with(|c| c.set(1i32 << delta.lf_res));
19462 fctx.delta_lf_multi.with(|c| c.set(delta.lf_multi));
19463 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
19464 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
19465 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
19466
19467 let mut y = PlaneBuf {
19468 data: std::borrow::Cow::Owned(vec![0u16; width * height]),
19469 width,
19470 height,
19471 true_width,
19472 true_height,
19473 tile_x0: 0,
19474 tile_y0: 0,
19475 tile_x1: width,
19476 tile_y1: height,
19477 };
19478 let mut u = PlaneBuf {
19479 data: std::borrow::Cow::Owned(vec![0u16; width * height / 4]),
19480 width: width / 2,
19481 height: height / 2,
19482 true_width: true_width / 2,
19483 true_height: true_height / 2,
19484 tile_x0: 0,
19485 tile_y0: 0,
19486 tile_x1: width / 2,
19487 tile_y1: height / 2,
19488 };
19489 let mut v = PlaneBuf {
19490 data: std::borrow::Cow::Owned(vec![0u16; width * height / 4]),
19491 width: width / 2,
19492 height: height / 2,
19493 true_width: true_width / 2,
19494 true_height: true_height / 2,
19495 tile_x0: 0,
19496 tile_y0: 0,
19497 tile_x1: width / 2,
19498 tile_y1: height / 2,
19499 };
19500
19501 let scan32 = default_scan(TX32);
19502 let scan16 = default_scan(TX16);
19503 let scan8 = default_scan(TX8);
19504 let scan4 = default_scan(TX4);
19505
19506 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
19507 let mut result_cdfs = base_cdfs.clone();
19508 let mut neighbours = Neighbours::new(
19509 cols32 as usize * 2,
19510 rows32 as usize * 2,
19511 mi_cols as usize,
19512 mi_rows as usize, fctx,
19513 );
19514 // spec 7.16/libaom `av1_alloc_restoration_struct`: the unit grid is
19515 // sized from `av1_get_upsampled_plane_size`, i.e. the UPSCALED width --
19516 // loop restoration runs after the superres upscale.
19517 let mut lr_grid = crate::restoration::RestorationGrid::new(
19518 lr,
19519 superres(fctx).map_or(frame_width, |(w, _)| w),
19520 frame_height,
19521 );
19522
19523 // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its
19524 // own byte range and its own fresh copy of the frame's initial CDFs
19525 // (spec 5.11.2 `decode_tile`'s `init_symbol`); only the tile named by
19526 // `context_update_tile_id` has its end-of-tile adapted table kept as the
19527 // frame's own output (spec `exit_symbol`) -- every other tile's
19528 // adaptation is discarded, matching the refusal this replaces.
19529 for (tile_idx, &tile_bytes) in tiles.iter().enumerate() {
19530 let tile_num = tile_idx as u32;
19531 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
19532 let mi_row0 = tile_info.mi_row_starts[trow as usize];
19533 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
19534 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
19535 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
19536 // Tile boundaries are always superblock-aligned in mi units (spec
19537 // 5.9.15's uniform/non-uniform derivation both only ever emit
19538 // multiples of the superblock's own mi size), so plain division is
19539 // exact here -- no rounding needed.
19540 // `mi_row0`/`mi_col0` (this tile's own start, `0` or an interior
19541 // tile boundary) are always superblock-aligned by spec 5.9.15; the
19542 // frame's own true final edge (`mi_row_starts`/`mi_col_starts`'
19543 // last entry) is not, so the upper bound needs `div_ceil` the same
19544 // way the whole-frame `sb_rows`/`sb_cols` above does, to keep the
19545 // trailing partial superblock row/column in scope.
19546 let (sb_r0, sb_r1) = ((mi_row0 / SB_MI).min(sb_rows), mi_row1.div_ceil(SB_MI).min(sb_rows));
19547 let (sb_c0, sb_c1) = ((mi_col0 / SB_MI).min(sb_cols), mi_col1.div_ceil(SB_MI).min(sb_cols));
19548
19549 // lane-t900 r19: spec 5.11.2 `decode_tile` resets `RefLrWiener` /
19550 // `RefSgrXqd` to the midpoint filter at the top of EVERY tile, not
19551 // once per frame. Carried across a tile boundary, the loop-restoration
19552 // coefficients of the next tile decode off the previous tile's
19553 // reference -- same symbol count, so entropy and reconstruction stay
19554 // exact and only the filtered pixels of every tile after the first
19555 // are wrong.
19556 let mut lr_reference = [(
19557 crate::restoration::WienerInfo::default(),
19558 crate::restoration::SgrprojInfo::default(),
19559 ); 3];
19560 let mut cdfs = base_cdfs.clone();
19561 // spec `decode_tile`: `CurrentQIndex` resets to the frame's own
19562 // `base_q_idx` at the top of every tile, not once per frame.
19563 fctx.current_q_idx.with(|c| c.set(i32::from(base_q_idx)));
19564 fctx.quant_deltas.with(|c| c.set(deltas));
19565 fctx.current_delta_lf.with(|c| c.set([0; 4]));
19566 if crate::envflags::env_flag!("EC_AV1_TRACE") {
19567 eprintln!(
19568 "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
19569 tile_bytes.len(),
19570 &tile_bytes[..tile_bytes.len().min(8)]
19571 );
19572 }
19573 let mut dec = SymbolDecoder::new(tile_bytes);
19574 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize, fctx);
19575 y.set_tile_origin(
19576 mi_col0 as usize * 4,
19577 mi_row0 as usize * 4,
19578 (mi_col1 as usize * 4).min(y.width),
19579 (mi_row1 as usize * 4).min(y.height),
19580 );
19581 u.set_tile_origin(
19582 mi_col0 as usize * 2,
19583 mi_row0 as usize * 2,
19584 (mi_col1 as usize * 2).min(u.width),
19585 (mi_row1 as usize * 2).min(u.height),
19586 );
19587 v.set_tile_origin(
19588 mi_col0 as usize * 2,
19589 mi_row0 as usize * 2,
19590 (mi_col1 as usize * 2).min(v.width),
19591 (mi_row1 as usize * 2).min(v.height),
19592 );
19593 TILE_HITS.with(|c| c.set(c.get() + 1));
19594
19595 // lane-sb128b r1: set when the 128 root resolved to `PARTITION_NONE` --
19596 // its one block covers all four 64x64 quadrants, so the remaining three
19597 // visits of this superblock code nothing at all.
19598 let mut sb128_none = false;
19599 // lane-wave1 step (ii): at one reconstruction thread the recorded writes
19600 // are performed at their push sites (nothing reaches the queue below).
19601 let _recon_inline = ReconInline::install(fctx, &mut y, &mut u, &mut v);
19602 // lane-wave1 step (ii): one job per superblock (per 128x128 superblock
19603 // when `sb128`, since a 128 block writes across its four 64x64 visits).
19604 let wave_shift = u32::from(sb128);
19605 let (wave_r0, wave_c0) = ((sb_r0 >> wave_shift) as usize, (sb_c0 >> wave_shift) as usize);
19606 let (wave_rows, wave_cols) = if sb_r1 > sb_r0 && sb_c1 > sb_c0 {
19607 (
19608 ((sb_r1 - 1) >> wave_shift) as usize - wave_r0 + 1,
19609 ((sb_c1 - 1) >> wave_shift) as usize - wave_c0 + 1,
19610 )
19611 } else {
19612 (0, 0)
19613 };
19614 let _wave = WaveGuard::install(fctx, &mut y, &mut u, &mut v, wave_rows, wave_cols);
19615 let waving = fctx.wave.with(|w| w.borrow().is_some());
19616 let mut wave_job = (0usize, 0usize);
19617 for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) {
19618 // lane-wave1: the previous superblock's recorded writes -- handed to
19619 // the wavefront workers, or replayed here at one recon thread (where
19620 // the queue is empty, every write having run at its push site).
19621 if waving {
19622 if sb_start {
19623 wave_submit(fctx, wave_job.0, wave_job.1);
19624 wave_job = (
19625 (sb_r >> wave_shift) as usize - wave_r0,
19626 (sb_c >> wave_shift) as usize - wave_c0,
19627 );
19628 }
19629 } else {
19630 flush_recon(fctx, &mut y, &mut u, &mut v);
19631 }
19632 if row_start {
19633 neighbours.start_row();
19634 }
19635 if sb_start {
19636 sb128_none = false;
19637 }
19638 if sb128_none {
19639 continue;
19640 }
19641 {
19642 // lane-sb128 r1: the 128 root. Its loop-restoration units are read
19643 // once for the whole 128x128 (spec 5.11.57 is called with the
19644 // superblock's own size), then one partition symbol off the
19645 // `BLOCK_128X128` CDF (8 symbols) decides the root -- only SPLIT
19646 // recurses into the four 64x64 quadrants this decoder codes.
19647 if sb128 && sb_start {
19648 let part128 = read_sb128_root(
19649 &mut dec,
19650 &mut cdfs,
19651 &neighbours,
19652 lr,
19653 &mut lr_grid,
19654 &mut lr_reference,
19655 sb_r,
19656 sb_c,
19657 mi_cols,
19658 mi_rows, fctx,
19659 )?;
19660 if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part128) {
19661 // lane-sb128c r9: the four AB shapes at the 128 root.
19662 // libaom `decode_partition` (decodeframe.c) codes each as
19663 // two `bsize2` (64x64) squares plus one `subsize`
19664 // (128x64 / 64x128) half, visited HORZ_A = TL, TR, bottom
19665 // half; HORZ_B = top half, BL, BR; VERT_A = TL, BL, right
19666 // half; VERT_B = left half, TR, BR. AB values only come
19667 // from the FULL alphabet symbol, which is only read when
19668 // both halves of the root are inside the frame, so no
19669 // piece needs libaom's `i > 0` frame-edge break (a piece
19670 // may still overhang the bottom/right, which
19671 // `PlaneBuf::reconstruct`'s r8 clip handles).
19672 sb128_none = true;
19673 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
19674 let (br, bc) = (at128.0 + 4, at128.1 + 4);
19675 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
19676 // Only the VERTICAL arms reorder the squares (TL, BL, TR,
19677 // BR), so only they switch libaom's `has_tr_vert_*` /
19678 // `has_bl_vert_*` tables (lane-sb128c r6 visit order).
19679 let _vert_ab =
19680 (part128 == PARTITION_VERT_A || part128 == PARTITION_VERT_B)
19681 .then(crate::encode::Reach::vert_ab_partition);
19682 // One `cdef_idx` literal per CODED BLOCK, at the first
19683 // non-skip one of each 64x64 CDEF unit; the 128x64 /
19684 // 64x128 half covers two units and its read lands in the
19685 // unit holding its origin, so that value is copied to the
19686 // other one (libaom: every mi of the block points at the
19687 // same `MB_MODE_INFO`).
19688 let cdef_copy = |src: (usize, usize), dst: (usize, usize)| {
19689 fctx.cdef_idx_grid.with(|g| {
19690 let mut g = g.borrow_mut();
19691 let cols = fctx.cdef_sb_cols.with(|c| c.get());
19692 if cols == 0 {
19693 return;
19694 }
19695 let (si, di) = (
19696 (q_r + src.0) * cols + q_c + src.1,
19697 (q_r + dst.0) * cols + q_c + dst.1,
19698 );
19699 if q_c + src.1 < cols
19700 && q_c + dst.1 < cols
19701 && si < g.len()
19702 && di < g.len()
19703 {
19704 g[di] = g[si];
19705 }
19706 });
19707 };
19708 macro_rules! square64 {
19709 ($at:expr) => {{
19710 fctx.cdef_transmitted.with(|c| c.set(false));
19711 decode_block(
19712 &mut dec,
19713 &mut cdfs,
19714 &mut neighbours,
19715 $at,
19716 SB,
19717 TxbSet::Luma64,
19718 TxbSet::Chroma32,
19719 TX32,
19720 TX32,
19721 (&scan32, &scan32),
19722 false,
19723 &mut y,
19724 &mut u,
19725 &mut v,
19726 base_q_idx,
19727 enable_filter_intra,
19728 allow_screen_content_tools,
19729 allow_intrabc,
19730 &scan32,
19731 &scan16,
19732 &scan8,
19733 &scan4,
19734 tx_select,
19735 reduced_tx_set, fctx,
19736 )?
19737 }};
19738 }
19739 macro_rules! half128 {
19740 ($at:expr, $bw:expr, $bh:expr, $src:expr, $dst:expr) => {{
19741 fctx.cdef_transmitted.with(|c| c.set(false));
19742 decode_block_128rect(
19743 &mut dec,
19744 &mut cdfs,
19745 &mut neighbours,
19746 $at,
19747 $bw,
19748 $bh,
19749 &mut y,
19750 &mut u,
19751 &mut v,
19752 base_q_idx,
19753 enable_filter_intra,
19754 allow_screen_content_tools,
19755 tx_select,
19756 reduced_tx_set, fctx,
19757 )?;
19758 cdef_copy($src, $dst);
19759 }};
19760 }
19761 match part128 {
19762 PARTITION_HORZ_A => {
19763 square64!(at128);
19764 square64!((at128.0, bc));
19765 half128!((br, at128.1), 128, 64, (1, 0), (1, 1));
19766 }
19767 PARTITION_HORZ_B => {
19768 half128!(at128, 128, 64, (0, 0), (0, 1));
19769 square64!((br, at128.1));
19770 square64!((br, bc));
19771 }
19772 PARTITION_VERT_A => {
19773 square64!(at128);
19774 square64!((br, at128.1));
19775 half128!((at128.0, bc), 64, 128, (0, 1), (1, 1));
19776 }
19777 _ => {
19778 half128!(at128, 64, 128, (0, 0), (1, 0));
19779 square64!((at128.0, bc));
19780 square64!((br, bc));
19781 }
19782 }
19783 continue;
19784 }
19785 if matches!(part128, PARTITION_HORZ | PARTITION_VERT) {
19786 // lane-sb128c r8: libaom `decode_partition`
19787 // (decodeframe.c:1554) codes PARTITION_HORZ at the 128
19788 // root as `subsize = BLOCK_128X64` at (mi_row, mi_col)
19789 // plus a second one at (mi_row + hbs, mi_col) only
19790 // `if (mi_row + hbs < mi_rows)`; PARTITION_VERT mirrors it
19791 // on the column. `hbs` is `mi_size_high[BLOCK_128X128]/2`
19792 // = 16 mi. Both halves together cover the whole root, so
19793 // the remaining three 64x64 quadrant visits code nothing
19794 // (same flag the NONE arm sets).
19795 sb128_none = true;
19796 let horz = part128 == PARTITION_HORZ;
19797 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
19798 let (bw, bh) = if horz { (128usize, 64usize) } else { (64, 128) };
19799 for i in 0..2 {
19800 let at = if horz {
19801 (at128.0 + i * 4, at128.1)
19802 } else {
19803 (at128.0, at128.1 + i * 4)
19804 };
19805 let (blk_mi_r, blk_mi_c) = (at.0 * (SUB / MI), at.1 * (SUB / MI));
19806 if i > 0
19807 && (blk_mi_r >= mi_rows as usize || blk_mi_c >= mi_cols as usize)
19808 {
19809 break;
19810 }
19811 // Each half reads its OWN `cdef_idx` literal
19812 // (libaom `read_cdef` keys the `-1` test on the
19813 // block's own `MB_MODE_INFO`, and the two halves have
19814 // different ones).
19815 fctx.cdef_transmitted.with(|c| c.set(false));
19816 decode_block_128rect(
19817 &mut dec,
19818 &mut cdfs,
19819 &mut neighbours,
19820 at,
19821 bw,
19822 bh,
19823 &mut y,
19824 &mut u,
19825 &mut v,
19826 base_q_idx,
19827 enable_filter_intra,
19828 allow_screen_content_tools,
19829 tx_select,
19830 reduced_tx_set, fctx,
19831 )?;
19832 }
19833 // One `cdef_idx` per BLOCK, copied to every 64x64 CDEF
19834 // unit it covers (the inter path's own fan-out).
19835 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
19836 fctx.cdef_idx_grid.with(|g| {
19837 let mut g = g.borrow_mut();
19838 let cols = fctx.cdef_sb_cols.with(|c| c.get());
19839 if cols == 0 {
19840 return;
19841 }
19842 for (src, dst) in if horz {
19843 [((0, 0), (0, 1)), ((1, 0), (1, 1))]
19844 } else {
19845 [((0, 0), (1, 0)), ((0, 1), (1, 1))]
19846 } {
19847 let (si, di) = (
19848 (q_r + src.0) * cols + q_c + src.1,
19849 (q_r + dst.0) * cols + q_c + dst.1,
19850 );
19851 if q_c + src.1 < cols
19852 && q_c + dst.1 < cols
19853 && si < g.len()
19854 && di < g.len()
19855 {
19856 g[di] = g[si];
19857 }
19858 }
19859 });
19860 continue;
19861 }
19862 if part128 == PARTITION_NONE {
19863 // One 128x128 intra block: four TX_64X64 luma units and a
19864 // single 64x64 chroma unit per plane (`av1_get_max_uv_txsize`
19865 // of a 128x128 block is TX_64X64 over its 64x64 uv plane
19866 // block). No CfL, no filter intra, no palette at this size --
19867 // [`read_intra_mode`]'s own size gates already say so.
19868 sb128_none = true;
19869 fctx.cdef_transmitted.with(|c| c.set(false));
19870 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
19871 decode_block(
19872 &mut dec,
19873 &mut cdfs,
19874 &mut neighbours,
19875 at128,
19876 SB * 2,
19877 TxbSet::Luma64,
19878 TxbSet::Chroma32,
19879 TX32,
19880 TX32,
19881 (&scan32, &scan32),
19882 false,
19883 &mut y,
19884 &mut u,
19885 &mut v,
19886 base_q_idx,
19887 enable_filter_intra,
19888 allow_screen_content_tools,
19889 allow_intrabc,
19890 &scan32,
19891 &scan16,
19892 &scan8,
19893 &scan4,
19894 tx_select,
19895 reduced_tx_set, fctx,
19896 )?;
19897 // libaom writes one `cdef_strength` into the block's own
19898 // `MB_MODE_INFO`, which every mi cell of the block --
19899 // hence all four 64x64 CDEF units -- points at; our grid
19900 // is per-unit, so the read (which only ever lands in the
19901 // top-left unit, `read_cdef`'s index 0) is copied across.
19902 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
19903 fctx.cdef_idx_grid.with(|g| {
19904 let mut g = g.borrow_mut();
19905 let cols = fctx.cdef_sb_cols.with(|c| c.get());
19906 if cols > 0 && q_r * cols + q_c < g.len() {
19907 let idx = g[q_r * cols + q_c];
19908 for (dr, dc) in [(0, 1), (1, 0), (1, 1)] {
19909 let i = (q_r + dr) * cols + q_c + dc;
19910 if q_c + dc < cols && i < g.len() {
19911 g[i] = idx;
19912 }
19913 }
19914 }
19915 });
19916 continue;
19917 }
19918 }
19919 if !sb128 {
19920 crate::restoration::read_lr(
19921 &mut dec,
19922 &mut cdfs,
19923 lr,
19924 &mut lr_grid,
19925 &mut lr_reference,
19926 sb_r * SB_MI,
19927 sb_c * SB_MI,
19928 SB_MI, fctx,
19929 );
19930 }
19931 fctx.cdef_transmitted.with(|c| c.set(false));
19932 let at = (sb_r as usize * 4, sb_c as usize * 4);
19933 let ctx = neighbours.partition_ctx(at, SB);
19934 let (has_cols, has_rows) = (
19935 sb_c * SB_MI + SB_MI / 2 < mi_cols,
19936 sb_r * SB_MI + SB_MI / 2 < mi_rows,
19937 );
19938 // Recomputed at this superblock's own half (spec
19939 // `decode_partition`): a full alphabet symbol when both halves are
19940 // inside the true frame, a single gathered bit when just one is
19941 // (the superblock cannot be left whole, so this is forced split),
19942 // and nothing at all (SPLIT inferred, no bits) when neither is —
19943 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
19944 // three-way write exactly.
19945 let part = if has_cols && has_rows {
19946 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
19947 if crate::envflags::env_flag!("EC_AV1_TRACE") {
19948 eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
19949 }
19950 p
19951 } else {
19952 // lane-hgkf r1 (class `parsed-then-discarded`, same finding as
19953 // the unmerged lane-golomb r1): the gathered bit IS the
19954 // partition -- libaom `ec_read_partition_impl` returns
19955 // PARTITION_HORZ (resp. VERT) for 0 and only SPLIT for 1.
19956 // Forcing SPLIT desynced the last superblock row of every
19957 // frame whose height is not a multiple of 64: the ReelB key frames (3840x1608) diverge at mi_row=400 mi_col=0,
19958 // the first block of that row.
19959 match (has_cols, has_rows) {
19960 (true, false) => {
19961 trace_edge((sb_r * SB_MI) as usize, (sb_c * SB_MI) as usize, 12, ctx, dec.debug_state().0 as u32);
19962 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
19963 bump_edge32(4 + b.min(1) as usize);
19964 bump_edge_part(b.min(1) as usize);
19965 if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ }
19966 }
19967 (false, true) => {
19968 trace_edge((sb_r * SB_MI) as usize, (sb_c * SB_MI) as usize, 12, ctx, dec.debug_state().0 as u32);
19969 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
19970 bump_edge32(4 + b.min(1) as usize);
19971 bump_edge_part(b.min(1) as usize);
19972 if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT }
19973 }
19974 _ => {
19975 bump_edge_both_cut(2);
19976 PARTITION_SPLIT
19977 }
19978 }
19979 };
19980 match part {
19981 PARTITION_NONE => {
19982 decode_block(
19983 &mut dec,
19984 &mut cdfs,
19985 &mut neighbours,
19986 at,
19987 SB,
19988 TxbSet::Luma64,
19989 TxbSet::Chroma32,
19990 TX32,
19991 TX32,
19992 (&scan32, &scan32),
19993 false,
19994 &mut y,
19995 &mut u,
19996 &mut v,
19997 base_q_idx,
19998 enable_filter_intra,
19999 allow_screen_content_tools,
20000 allow_intrabc,
20001 &scan32,
20002 &scan16,
20003 &scan8,
20004 &scan4,
20005 tx_select,
20006 reduced_tx_set, fctx,
20007 )?;
20008 }
20009 PARTITION_SPLIT => {
20010 for q in 0..4 {
20011 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
20012 if r32 >= rows32 || c32 >= cols32 {
20013 continue;
20014 }
20015 let at32 = (r32 as usize * 2, c32 as usize * 2);
20016 let ctx32 = neighbours.partition_ctx(at32, BLOCK);
20017 let (has_cols32, has_rows32) = (
20018 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
20019 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
20020 );
20021 let part32 = if has_cols32 && has_rows32 {
20022 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
20023 if crate::envflags::env_flag!("EC_AV1_TRACE") {
20024 let (rng, _) = dec.debug_state();
20025 eprintln!(
20026 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p} rng={rng}",
20027 r32 * BLOCK_MI,
20028 c32 * BLOCK_MI
20029 );
20030 }
20031 p
20032 } else {
20033 // lane-hgkf r1: the 32-level frame-edge bit is the
20034 // partition too (same libaom reader as the
20035 // superblock level above).
20036 match (has_cols32, has_rows32) {
20037 (true, false) => {
20038 trace_edge((r32 * BLOCK_MI) as usize, (c32 * BLOCK_MI) as usize, 9, ctx32, dec.debug_state().0 as u32);
20039 let b = dec.symbol_fixed(&gather(
20040 &cdfs.partition_w32[ctx32],
20041 VERT_ALIKE,
20042 ));
20043 bump_edge32(b.min(1) as usize);
20044 bump_edge_part(2 + b.min(1) as usize);
20045 if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ }
20046 }
20047 (false, true) => {
20048 trace_edge((r32 * BLOCK_MI) as usize, (c32 * BLOCK_MI) as usize, 9, ctx32, dec.debug_state().0 as u32);
20049 let b = dec.symbol_fixed(&gather(
20050 &cdfs.partition_w32[ctx32],
20051 HORZ_ALIKE,
20052 ));
20053 bump_edge32(b.min(1) as usize);
20054 bump_edge_part(2 + b.min(1) as usize);
20055 if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT }
20056 }
20057 _ => {
20058 bump_edge_both_cut(1);
20059 PARTITION_SPLIT
20060 }
20061 }
20062 };
20063 match part32 {
20064 PARTITION_NONE => {
20065 decode_block(
20066 &mut dec,
20067 &mut cdfs,
20068 &mut neighbours,
20069 at32,
20070 BLOCK,
20071 TxbSet::Luma32,
20072 TxbSet::Chroma16,
20073 TX32,
20074 TX16,
20075 (&scan32, &scan16),
20076 true,
20077 &mut y,
20078 &mut u,
20079 &mut v,
20080 base_q_idx,
20081 enable_filter_intra,
20082 allow_screen_content_tools,
20083 allow_intrabc,
20084 &scan32,
20085 &scan16,
20086 &scan8,
20087 &scan4,
20088 tx_select,
20089 reduced_tx_set, fctx,
20090 )?;
20091 }
20092 PARTITION_SPLIT => {
20093 for sub in 0..4 {
20094 let (sr, sc) =
20095 (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
20096 if (sr as u32) * SUB_MI >= mi_rows
20097 || (sc as u32) * SUB_MI >= mi_cols
20098 {
20099 continue;
20100 }
20101 let (has_cols16, has_rows16) = (
20102 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
20103 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
20104 );
20105 let at16 = (sr, sc);
20106 let ctx16 = neighbours.partition_ctx(at16, SUB);
20107 if has_cols16 && has_rows16 {
20108 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
20109 if crate::envflags::env_flag!("EC_AV1_TRACE") {
20110 eprintln!(
20111 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}",
20112 at16.0, at16.1
20113 );
20114 }
20115 if part16 == PARTITION_NONE {
20116 decode_block(
20117 &mut dec,
20118 &mut cdfs,
20119 &mut neighbours,
20120 at16,
20121 SUB,
20122 TxbSet::Luma16,
20123 TxbSet::Chroma8,
20124 TX16,
20125 TX8,
20126 (&scan16, &scan8),
20127 true,
20128 &mut y,
20129 &mut u,
20130 &mut v,
20131 base_q_idx,
20132 enable_filter_intra,
20133 allow_screen_content_tools,
20134 allow_intrabc,
20135 &scan32,
20136 &scan16,
20137 &scan8,
20138 &scan4,
20139 tx_select,
20140 reduced_tx_set, fctx,
20141 )?;
20142 continue;
20143 }
20144 if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part16) {
20145 // lane-ab16 r1: the four AB (T-shaped) partitions at the 16x16
20146 // level -- two 8x8 squares plus one 16x8/8x16 strip. libaom's
20147 // `decode_partition` visit order (decodeframe.c):
20148 // HORZ_A: TL 8x8, TR 8x8, bottom 16x8
20149 // HORZ_B: top 16x8, BL 8x8, BR 8x8
20150 // VERT_A: TL 8x8, BL 8x8, right 8x16
20151 // VERT_B: left 8x16, TR 8x8, BR 8x8
20152 // The squares go through `decode_leaf8`, the strip through
20153 // `decode_leaf_rect` (real, non-skip 16x8/8x16 coefficients --
20154 // lane-rectx r2-r4; the older `decode_block_rect` this VERT_B arm
20155 // used refuses the non-skip case at this size). Both writers keep
20156 // mi-granular mode/skip/palette records, so a later block's
20157 // `above_mi`/`left_mi` sees the real sub-block, not the coarse
20158 // 16x16 cell.
20159 //
20160 // VERT_A/VERT_B visit TL,BL,TR,BR, so the bottom-left square's
20161 // top-right neighbour is the partition's own not-yet-decoded
20162 // rectangle: libaom switches those squares onto `has_tr_vert_*`/
20163 // `has_bl_vert_*` (`reconintra.c` `get_has_tr_table`), which is
20164 // `Reach::vert_ab_partition()` (lane-part32 r5, cherry-picked here).
20165 let arm = part16 - PARTITION_HORZ_A;
20166 bump_ab16(arm);
20167 if part16 == PARTITION_VERT_B {
20168 VERT_B_INTRA_HITS.with(|c| c.set(c.get() + 1));
20169 }
20170 let _vert_guard = if part16 == PARTITION_VERT_A || part16 == PARTITION_VERT_B {
20171 Some(crate::encode::Reach::vert_ab_partition())
20172 } else {
20173 None
20174 };
20175 let (mi_row0, mi_col0) = (sr * SUB_MI as usize, sc * SUB_MI as usize);
20176 macro_rules! ab_leaf8 {
20177 ($mi:expr, $prev:expr) => {
20178 decode_leaf8(
20179 &mut dec,
20180 &mut cdfs,
20181 &mut neighbours,
20182 at16,
20183 $mi,
20184 (&scan8, &scan4),
20185 $prev,
20186 &mut y,
20187 &mut u,
20188 &mut v,
20189 base_q_idx,
20190 enable_filter_intra,
20191 allow_screen_content_tools,
20192 allow_intrabc,
20193 tx_select,
20194 reduced_tx_set, fctx,
20195 )?
20196 };
20197 }
20198 macro_rules! ab_strip {
20199 ($mi:expr, $bw:expr, $bh:expr, $prev:expr) => {
20200 decode_leaf_rect(
20201 &mut dec,
20202 &mut cdfs,
20203 &mut neighbours,
20204 at16,
20205 $mi,
20206 $bw,
20207 $bh,
20208 $prev,
20209 &mut y,
20210 &mut u,
20211 &mut v,
20212 enable_filter_intra,
20213 allow_screen_content_tools,
20214 base_q_idx,
20215 tx_select,
20216 reduced_tx_set, fctx,
20217 )?
20218 };
20219 }
20220 let tl = (mi_row0, mi_col0);
20221 let tr = (mi_row0, mi_col0 + 2);
20222 let bl = (mi_row0 + 2, mi_col0);
20223 let br = (mi_row0 + 2, mi_col0 + 2);
20224 let mut done: Vec<((usize, usize), usize)> = Vec::new();
20225 match part16 {
20226 PARTITION_HORZ_A => {
20227 let m_tl = ab_leaf8!(tl, done.last().copied());
20228 done.push((tl, m_tl));
20229 let m_tr = ab_leaf8!(tr, done.last().copied());
20230 done.push((tr, m_tr));
20231 let m_bot = ab_strip!(bl, 16, 8, Some((tl, m_tl)));
20232 done.push((bl, m_bot));
20233 }
20234 PARTITION_HORZ_B => {
20235 let m_top = ab_strip!(tl, 16, 8, None);
20236 done.push((tl, m_top));
20237 let m_bl = ab_leaf8!(bl, done.last().copied());
20238 done.push((bl, m_bl));
20239 let m_br = ab_leaf8!(br, done.last().copied());
20240 done.push((br, m_br));
20241 }
20242 PARTITION_VERT_A => {
20243 let m_tl = ab_leaf8!(tl, done.last().copied());
20244 done.push((tl, m_tl));
20245 let m_bl = ab_leaf8!(bl, done.last().copied());
20246 done.push((bl, m_bl));
20247 let m_right = ab_strip!(tr, 8, 16, Some((tl, m_tl)));
20248 done.push((tr, m_right));
20249 }
20250 _ => {
20251 let m_left = ab_strip!(tl, 8, 16, None);
20252 done.push((tl, m_left));
20253 let m_tr = ab_leaf8!(tr, done.last().copied());
20254 done.push((tr, m_tr));
20255 let m_br = ab_leaf8!(br, done.last().copied());
20256 done.push((br, m_br));
20257 }
20258 }
20259 // Same coarse-slot write-back the real SPLIT path takes: the
20260 // 16x16 cell's single `above_mode`/`left_mode` entry gets the
20261 // sub-block on the parent's bottom / right edge (the mi-exact map
20262 // above wins wherever it has an entry).
20263 write_back_split_modes(&mut neighbours, &done, (mi_row0, mi_col0), (sr, sc));
20264 continue;
20265 }
20266 if part16 == PARTITION_HORZ {
20267 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
20268 let (mi_row0, mi_col0) = (
20269 sr as u32 * SUB_MI,
20270 sc as u32 * SUB_MI,
20271 );
20272 let top = (mi_row0 as usize, mi_col0 as usize);
20273 let bot = (mi_row0 as usize + 2, mi_col0 as usize);
20274 let mode_top = decode_leaf_rect(
20275 &mut dec,
20276 &mut cdfs,
20277 &mut neighbours,
20278 at16,
20279 top,
20280 16,
20281 8,
20282 None,
20283 &mut y,
20284 &mut u,
20285 &mut v,
20286 enable_filter_intra,
20287 allow_screen_content_tools,
20288 base_q_idx,
20289 tx_select,
20290 reduced_tx_set, fctx,
20291 )?;
20292 let mode_bot = decode_leaf_rect(
20293 &mut dec,
20294 &mut cdfs,
20295 &mut neighbours,
20296 at16,
20297 bot,
20298 16,
20299 8,
20300 Some((top, mode_top)),
20301 &mut y,
20302 &mut u,
20303 &mut v,
20304 enable_filter_intra,
20305 allow_screen_content_tools,
20306 base_q_idx,
20307 tx_select,
20308 reduced_tx_set, fctx,
20309 )?;
20310 neighbours.above_mode[sc] = mode_bot;
20311 neighbours.left_mode[sr] = mode_bot;
20312 continue;
20313 }
20314 if part16 == PARTITION_VERT {
20315 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
20316 let (mi_row0, mi_col0) = (
20317 sr as u32 * SUB_MI,
20318 sc as u32 * SUB_MI,
20319 );
20320 let left = (mi_row0 as usize, mi_col0 as usize);
20321 let right = (mi_row0 as usize, mi_col0 as usize + 2);
20322 let mode_left = decode_leaf_rect(
20323 &mut dec,
20324 &mut cdfs,
20325 &mut neighbours,
20326 at16,
20327 left,
20328 8,
20329 16,
20330 None,
20331 &mut y,
20332 &mut u,
20333 &mut v,
20334 enable_filter_intra,
20335 allow_screen_content_tools,
20336 base_q_idx,
20337 tx_select,
20338 reduced_tx_set, fctx,
20339 )?;
20340 let mode_right = decode_leaf_rect(
20341 &mut dec,
20342 &mut cdfs,
20343 &mut neighbours,
20344 at16,
20345 right,
20346 8,
20347 16,
20348 Some((left, mode_left)),
20349 &mut y,
20350 &mut u,
20351 &mut v,
20352 enable_filter_intra,
20353 allow_screen_content_tools,
20354 base_q_idx,
20355 tx_select,
20356 reduced_tx_set, fctx,
20357 )?;
20358 neighbours.above_mode[sc] = mode_right;
20359 neighbours.left_mode[sr] = mode_right;
20360 continue;
20361 }
20362 if part16 == PARTITION_HORZ_4
20363 || part16 == PARTITION_VERT_4
20364 {
20365 decode_rect4_16(
20366 &mut dec,
20367 &mut cdfs,
20368 &mut neighbours,
20369 at16,
20370 part16 == PARTITION_HORZ_4,
20371 &mut y,
20372 &mut u,
20373 &mut v,
20374 enable_filter_intra,
20375 allow_screen_content_tools,
20376 base_q_idx,
20377 tx_select,
20378 reduced_tx_set, fctx,
20379 )?;
20380 continue;
20381 }
20382 // lane-r14 r2 (verifier note): every
20383 // one of the 10 symbols this CDF can
20384 // produce is handled above, so SPLIT
20385 // is the only value that reaches
20386 // here -- the refusal that used to
20387 // stand here was unreachable and is
20388 // gone from `refusal_inventory`.
20389 debug_assert_eq!(part16, PARTITION_SPLIT);
20390 // A real (non-straddle) SPLIT of a
20391 // whole 16x16 into four 8x8 leaves --
20392 // the same recursion the straddle
20393 // path below already runs when the
20394 // true frame edge forces it, just
20395 // over all four positions instead of
20396 // the one or two the edge leaves.
20397 let (mi_row0, mi_col0) =
20398 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
20399 // Each 8x8 leaf's intra-mode context
20400 // must see its own siblings: the
20401 // bottom-left leaf's ABOVE neighbour
20402 // is leaf 0, not the previously
20403 // decoded leaf 1 (and the bottom-right
20404 // leaf's above is leaf 1, while
20405 // `prev_leaf` only ever carried the
20406 // immediately preceding one). The
20407 // coarse `above_mode`/`left_mode`
20408 // arrays hold one slot per 16x16, so
20409 // the sibling modes are swapped in
20410 // around each leaf call and restored
20411 // after; the loop tail writes the last
20412 // leaf's mode as before.
20413 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
20414 for i in 0..4 {
20415 let (mr, mc) =
20416 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
20417 let leaf_mi = (mr as usize, mc as usize);
20418 let li = i as usize;
20419 let saved_modes =
20420 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
20421 if li >= 2 {
20422 if let Some((below, _)) = sib_modes[li - 2] {
20423 neighbours.above_mode[sc] = below;
20424 }
20425 }
20426 if li % 2 == 1 {
20427 if let Some((_, right)) = sib_modes[li - 1] {
20428 neighbours.left_mode[sr] = right;
20429 }
20430 }
20431 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
20432 let part8 =
20433 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
20434 if crate::envflags::env_flag!("EC_AV1_TRACE") {
20435 eprintln!(
20436 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
20437 );
20438 }
20439 let leaf_mode = if part8 == PARTITION_NONE {
20440 decode_leaf8(
20441 &mut dec,
20442 &mut cdfs,
20443 &mut neighbours,
20444 at16,
20445 leaf_mi,
20446 (&scan8, &scan4),
20447 None,
20448 &mut y,
20449 &mut u,
20450 &mut v,
20451 base_q_idx,
20452 enable_filter_intra,
20453 allow_screen_content_tools,
20454 allow_intrabc,
20455 tx_select,
20456 reduced_tx_set, fctx,
20457 ).map(|m| (m, m))?
20458 } else if part8 == PARTITION_SPLIT {
20459 decode_leaf_split4(
20460 &mut dec,
20461 &mut cdfs,
20462 &mut neighbours,
20463 at16,
20464 leaf_mi,
20465 &scan4,
20466 None,
20467 &mut y,
20468 &mut u,
20469 &mut v,
20470 base_q_idx,
20471 enable_filter_intra,
20472 allow_intrabc,
20473 reduced_tx_set, fctx,
20474 )?
20475 } else if part8 == PARTITION_HORZ
20476 || part8 == PARTITION_VERT
20477 {
20478 decode_leaf_rect8(
20479 &mut dec,
20480 &mut cdfs,
20481 &mut neighbours,
20482 at16,
20483 leaf_mi,
20484 part8 == PARTITION_VERT,
20485 &scan4,
20486 &mut y,
20487 &mut u,
20488 &mut v,
20489 base_q_idx,
20490 enable_filter_intra,
20491 allow_intrabc,
20492 tx_select,
20493 reduced_tx_set, fctx,
20494 )?
20495 } else {
20496 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
20497 };
20498 neighbours.above_mode[sc] = saved_modes.0;
20499 neighbours.left_mode[sr] = saved_modes.1;
20500 sib_modes[li] = Some(leaf_mode);
20501 }
20502 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
20503 neighbours.above_mode[sc] = below;
20504 }
20505 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
20506 neighbours.left_mode[sr] = right;
20507 }
20508 continue;
20509 }
20510 // The true edge falls inside this 16x16
20511 // leaf itself (mod-32==8 target sizes,
20512 // lane-av1-rect): one axis only -- an 8x8
20513 // leaf never itself straddles, so the
20514 // block splits cleanly along whichever
20515 // axis is short.
20516 // lane-edgeboth r1: when the true frame
20517 // edge cuts BOTH axes libaom's
20518 // `decode_partition` takes
20519 // `else if (!has_rows && !has_cols)
20520 // partition = PARTITION_SPLIT;` -- no
20521 // symbol of any kind is read, and the four
20522 // 8x8 children are then visited by the
20523 // same loop below, whose
20524 // `mr < mi_rows && mc < mi_cols` filter IS
20525 // libaom's own
20526 // `if (mi_row >= mi_rows || mi_col >= mi_cols) return;`
20527 // early return, so the three out-of-frame
20528 // quadrants get no neighbour or tx-grid
20529 // write.
20530 if !has_cols16 && !has_rows16 {
20531 bump_edge_both_cut(0);
20532 } else {
20533 // lane-golomb r1 (class
20534 // `parsed-then-discarded`): the gathered
20535 // bit IS the partition -- 0 names
20536 // PARTITION_HORZ (resp. VERT), only 1 is
20537 // SPLIT (libaom `ec_read_partition_impl`).
20538 // This path can only walk the four SPLIT
20539 // leaves, so a 0 refuses by name instead
20540 // of desyncing.
20541 trace_edge(sr * SUB_MI as usize, sc * SUB_MI as usize, 6, ctx16, dec.debug_state().0 as u32);
20542 let edge_split = if has_cols16 {
20543 dec.symbol_fixed(&gather(
20544 &cdfs.partition_w16[ctx16],
20545 VERT_ALIKE,
20546 ))
20547 } else {
20548 dec.symbol_fixed(&gather(
20549 &cdfs.partition_w16[ctx16],
20550 HORZ_ALIKE,
20551 ))
20552 };
20553 // lane-hgkf r1: slots 2/3 of
20554 // [`EDGE_PART_HITS`], the gate's proof the
20555 // non-SPLIT edge arm actually decoded.
20556 bump_edge_part(if edge_split == 1 { 3 } else { 2 });
20557 if edge_split == 0 {
20558 // lane-oddh r1: the strip IS decodable
20559 // -- libaom's `decode_partition` codes
20560 // only the FIRST half of an edge
20561 // HORZ/VERT (the second call is
20562 // guarded by the same has_rows/
20563 // has_cols test that made the
20564 // partition non-square), so one
20565 // 16x8 (resp. 8x16) strip covers the
20566 // whole visible band of a frame whose
20567 // height (resp. width) is 8 mod 16 --
20568 // the user's 3840x1608 film.
20569 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
20570 EDGE_RECT_STRIP_HITS.with(|c| c.set(c.get() + 1));
20571 let (mi_row0, mi_col0) =
20572 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
20573 let (bw, bh) = if has_cols16 { (16, 8) } else { (8, 16) };
20574 let mode = decode_leaf_rect(
20575 &mut dec,
20576 &mut cdfs,
20577 &mut neighbours,
20578 at16,
20579 (mi_row0 as usize, mi_col0 as usize),
20580 bw,
20581 bh,
20582 None,
20583 &mut y,
20584 &mut u,
20585 &mut v,
20586 enable_filter_intra,
20587 allow_screen_content_tools,
20588 base_q_idx,
20589 tx_select,
20590 reduced_tx_set, fctx,
20591 )?;
20592 neighbours.above_mode[sc] = mode;
20593 neighbours.left_mode[sr] = mode;
20594 continue;
20595 }
20596 }
20597 let (mi_row0, mi_col0) =
20598 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
20599 let leaf_positions: Vec<(u32, u32)> = (0..4)
20600 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
20601 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
20602 .collect();
20603 // See the sibling-mode note in the clean
20604 // SPLIT path above.
20605 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
20606 for (mr, mc) in leaf_positions {
20607 let leaf_mi = (mr as usize, mc as usize);
20608 let li = (((mr - mi_row0) / 2) * 2 + (mc - mi_col0) / 2)
20609 as usize;
20610 let saved_modes =
20611 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
20612 if li >= 2 {
20613 if let Some((below, _)) = sib_modes[li - 2] {
20614 neighbours.above_mode[sc] = below;
20615 }
20616 }
20617 if li % 2 == 1 {
20618 if let Some((_, right)) = sib_modes[li - 1] {
20619 neighbours.left_mode[sr] = right;
20620 }
20621 }
20622 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
20623 let pre8 = dec.debug_state().0;
20624 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
20625 if crate::envflags::env_flag!("EC_AV1_TRACE") {
20626 eprintln!(
20627 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8} pre_rng={pre8}"
20628 );
20629 }
20630 let leaf_mode = if part8 == PARTITION_NONE {
20631 decode_leaf8(
20632 &mut dec,
20633 &mut cdfs,
20634 &mut neighbours,
20635 at16,
20636 leaf_mi,
20637 (&scan8, &scan4),
20638 None,
20639 &mut y,
20640 &mut u,
20641 &mut v,
20642 base_q_idx,
20643 enable_filter_intra,
20644 allow_screen_content_tools,
20645 allow_intrabc,
20646 tx_select,
20647 reduced_tx_set, fctx,
20648 ).map(|m| (m, m))?
20649 } else if part8 == PARTITION_SPLIT {
20650 decode_leaf_split4(
20651 &mut dec,
20652 &mut cdfs,
20653 &mut neighbours,
20654 at16,
20655 leaf_mi,
20656 &scan4,
20657 None,
20658 &mut y,
20659 &mut u,
20660 &mut v,
20661 base_q_idx,
20662 enable_filter_intra,
20663 allow_intrabc,
20664 reduced_tx_set, fctx,
20665 )?
20666 } else if part8 == PARTITION_HORZ
20667 || part8 == PARTITION_VERT
20668 {
20669 decode_leaf_rect8(
20670 &mut dec,
20671 &mut cdfs,
20672 &mut neighbours,
20673 at16,
20674 leaf_mi,
20675 part8 == PARTITION_VERT,
20676 &scan4,
20677 &mut y,
20678 &mut u,
20679 &mut v,
20680 base_q_idx,
20681 enable_filter_intra,
20682 allow_intrabc,
20683 tx_select,
20684 reduced_tx_set, fctx,
20685 )?
20686 } else {
20687 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
20688 };
20689 neighbours.above_mode[sc] = saved_modes.0;
20690 neighbours.left_mode[sr] = saved_modes.1;
20691 sib_modes[li] = Some(leaf_mode);
20692 }
20693 // `record()`'s `above_mode`/`left_mode`
20694 // write is a no-op at an 8x8 leaf's own
20695 // side, so force the write once the whole
20696 // 16x16 slot's leaves are done, from the
20697 // last leaf (mirrors the writer's r15
20698 // fix).
20699 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
20700 neighbours.above_mode[sc] = below;
20701 }
20702 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
20703 neighbours.left_mode[sr] = right;
20704 }
20705 }
20706 }
20707 PARTITION_HORZ => {
20708 // lane-intradisp r1: two true 32x16 strips.
20709 decode_block_rect(
20710 &mut dec,
20711 &mut cdfs,
20712 &mut neighbours,
20713 at32,
20714 32,
20715 16,
20716 &mut y,
20717 &mut u,
20718 &mut v,
20719 enable_filter_intra,
20720 allow_screen_content_tools,
20721 base_q_idx,
20722 tx_select,
20723 reduced_tx_set, fctx,
20724 )?;
20725 if !has_rows32 {
20726 bump_edge32(2);
20727 }
20728 // lane-hgkf r1: at the frame edge only the first half of the strip is
20729 // coded (libaom `decode_partition` guards the second half with the same
20730 // test that made this partition non-square).
20731 if has_rows32 {
20732 decode_block_rect(
20733 &mut dec,
20734 &mut cdfs,
20735 &mut neighbours,
20736 (at32.0 + 1, at32.1),
20737 32,
20738 16,
20739 &mut y,
20740 &mut u,
20741 &mut v,
20742 enable_filter_intra,
20743 allow_screen_content_tools,
20744 base_q_idx,
20745 tx_select,
20746 reduced_tx_set, fctx,
20747 )?;
20748 }
20749 }
20750 PARTITION_VERT => {
20751 // lane-intradisp r1: mirror of PARTITION_HORZ
20752 // above with width/height swapped.
20753 decode_block_rect(
20754 &mut dec,
20755 &mut cdfs,
20756 &mut neighbours,
20757 at32,
20758 16,
20759 32,
20760 &mut y,
20761 &mut u,
20762 &mut v,
20763 enable_filter_intra,
20764 allow_screen_content_tools,
20765 base_q_idx,
20766 tx_select,
20767 reduced_tx_set, fctx,
20768 )?;
20769 if !has_cols32 {
20770 bump_edge32(3);
20771 }
20772 // lane-hgkf r1: at the frame edge only the first half of the strip is
20773 // coded (libaom `decode_partition` guards the second half with the same
20774 // test that made this partition non-square).
20775 if has_cols32 {
20776 decode_block_rect(
20777 &mut dec,
20778 &mut cdfs,
20779 &mut neighbours,
20780 (at32.0, at32.1 + 1),
20781 16,
20782 32,
20783 &mut y,
20784 &mut u,
20785 &mut v,
20786 enable_filter_intra,
20787 allow_screen_content_tools,
20788 base_q_idx,
20789 tx_select,
20790 reduced_tx_set, fctx,
20791 )?;
20792 }
20793 }
20794 PARTITION_HORZ_A => {
20795 // lane-part32 r1: two 16x16 squares on top +
20796 // a true 32x16 strip below (mirrors
20797 // decode_inter_block's cd6cb6d HORZ_A: TL,
20798 // TR, bottom strip).
20799 INTRA_HORZ_A_HITS.with(|c| c.set(c.get() + 1));
20800 decode_block(
20801 &mut dec,
20802 &mut cdfs,
20803 &mut neighbours,
20804 at32,
20805 SUB,
20806 TxbSet::Luma16,
20807 TxbSet::Chroma8,
20808 TX16,
20809 TX8,
20810 (&scan16, &scan8),
20811 true,
20812 &mut y,
20813 &mut u,
20814 &mut v,
20815 base_q_idx,
20816 enable_filter_intra,
20817 allow_screen_content_tools,
20818 allow_intrabc,
20819 &scan32,
20820 &scan16,
20821 &scan8,
20822 &scan4,
20823 tx_select,
20824 reduced_tx_set, fctx,
20825 )?;
20826 decode_block(
20827 &mut dec,
20828 &mut cdfs,
20829 &mut neighbours,
20830 (at32.0, at32.1 + 1),
20831 SUB,
20832 TxbSet::Luma16,
20833 TxbSet::Chroma8,
20834 TX16,
20835 TX8,
20836 (&scan16, &scan8),
20837 true,
20838 &mut y,
20839 &mut u,
20840 &mut v,
20841 base_q_idx,
20842 enable_filter_intra,
20843 allow_screen_content_tools,
20844 allow_intrabc,
20845 &scan32,
20846 &scan16,
20847 &scan8,
20848 &scan4,
20849 tx_select,
20850 reduced_tx_set, fctx,
20851 )?;
20852 decode_block_rect(
20853 &mut dec,
20854 &mut cdfs,
20855 &mut neighbours,
20856 (at32.0 + 1, at32.1),
20857 32,
20858 16,
20859 &mut y,
20860 &mut u,
20861 &mut v,
20862 enable_filter_intra,
20863 allow_screen_content_tools,
20864 base_q_idx,
20865 tx_select,
20866 reduced_tx_set, fctx,
20867 )?;
20868 }
20869 PARTITION_HORZ_B => {
20870 // lane-part32 r1: a true 32x16 strip on top +
20871 // two 16x16 squares below (mirrors HORZ_A
20872 // with the strip/squares order flipped, same
20873 // shape as libaom decode_partition's HORZ_B).
20874 INTRA_HORZ_B_HITS.with(|c| c.set(c.get() + 1));
20875 decode_block_rect(
20876 &mut dec,
20877 &mut cdfs,
20878 &mut neighbours,
20879 at32,
20880 32,
20881 16,
20882 &mut y,
20883 &mut u,
20884 &mut v,
20885 enable_filter_intra,
20886 allow_screen_content_tools,
20887 base_q_idx,
20888 tx_select,
20889 reduced_tx_set, fctx,
20890 )?;
20891 decode_block(
20892 &mut dec,
20893 &mut cdfs,
20894 &mut neighbours,
20895 (at32.0 + 1, at32.1),
20896 SUB,
20897 TxbSet::Luma16,
20898 TxbSet::Chroma8,
20899 TX16,
20900 TX8,
20901 (&scan16, &scan8),
20902 true,
20903 &mut y,
20904 &mut u,
20905 &mut v,
20906 base_q_idx,
20907 enable_filter_intra,
20908 allow_screen_content_tools,
20909 allow_intrabc,
20910 &scan32,
20911 &scan16,
20912 &scan8,
20913 &scan4,
20914 tx_select,
20915 reduced_tx_set, fctx,
20916 )?;
20917 decode_block(
20918 &mut dec,
20919 &mut cdfs,
20920 &mut neighbours,
20921 (at32.0 + 1, at32.1 + 1),
20922 SUB,
20923 TxbSet::Luma16,
20924 TxbSet::Chroma8,
20925 TX16,
20926 TX8,
20927 (&scan16, &scan8),
20928 true,
20929 &mut y,
20930 &mut u,
20931 &mut v,
20932 base_q_idx,
20933 enable_filter_intra,
20934 allow_screen_content_tools,
20935 allow_intrabc,
20936 &scan32,
20937 &scan16,
20938 &scan8,
20939 &scan4,
20940 tx_select,
20941 reduced_tx_set, fctx,
20942 )?;
20943 }
20944 PARTITION_VERT_A => {
20945 // lane-part32 r1: mirror of HORZ_A with
20946 // width/height swapped (TL, BL, right 16x32
20947 // strip).
20948 INTRA_VERT_A_HITS.with(|c| c.set(c.get() + 1));
20949 let _vert_ab = crate::encode::Reach::vert_ab_partition();
20950 decode_block(
20951 &mut dec,
20952 &mut cdfs,
20953 &mut neighbours,
20954 at32,
20955 SUB,
20956 TxbSet::Luma16,
20957 TxbSet::Chroma8,
20958 TX16,
20959 TX8,
20960 (&scan16, &scan8),
20961 true,
20962 &mut y,
20963 &mut u,
20964 &mut v,
20965 base_q_idx,
20966 enable_filter_intra,
20967 allow_screen_content_tools,
20968 allow_intrabc,
20969 &scan32,
20970 &scan16,
20971 &scan8,
20972 &scan4,
20973 tx_select,
20974 reduced_tx_set, fctx,
20975 )?;
20976 decode_block(
20977 &mut dec,
20978 &mut cdfs,
20979 &mut neighbours,
20980 (at32.0 + 1, at32.1),
20981 SUB,
20982 TxbSet::Luma16,
20983 TxbSet::Chroma8,
20984 TX16,
20985 TX8,
20986 (&scan16, &scan8),
20987 true,
20988 &mut y,
20989 &mut u,
20990 &mut v,
20991 base_q_idx,
20992 enable_filter_intra,
20993 allow_screen_content_tools,
20994 allow_intrabc,
20995 &scan32,
20996 &scan16,
20997 &scan8,
20998 &scan4,
20999 tx_select,
21000 reduced_tx_set, fctx,
21001 )?;
21002 decode_block_rect(
21003 &mut dec,
21004 &mut cdfs,
21005 &mut neighbours,
21006 (at32.0, at32.1 + 1),
21007 16,
21008 32,
21009 &mut y,
21010 &mut u,
21011 &mut v,
21012 enable_filter_intra,
21013 allow_screen_content_tools,
21014 base_q_idx,
21015 tx_select,
21016 reduced_tx_set, fctx,
21017 )?;
21018 }
21019 PARTITION_VERT_B => {
21020 // lane-part32 r1: a true 16x32 strip on the
21021 // left + two 16x16 squares on the right
21022 // (libaom decode_partition VERT_B: left
21023 // strip, TR, BR).
21024 INTRA_VERT_B_HITS.with(|c| c.set(c.get() + 1));
21025 let _vert_ab = crate::encode::Reach::vert_ab_partition();
21026 decode_block_rect(
21027 &mut dec,
21028 &mut cdfs,
21029 &mut neighbours,
21030 at32,
21031 16,
21032 32,
21033 &mut y,
21034 &mut u,
21035 &mut v,
21036 enable_filter_intra,
21037 allow_screen_content_tools,
21038 base_q_idx,
21039 tx_select,
21040 reduced_tx_set, fctx,
21041 )?;
21042 decode_block(
21043 &mut dec,
21044 &mut cdfs,
21045 &mut neighbours,
21046 (at32.0, at32.1 + 1),
21047 SUB,
21048 TxbSet::Luma16,
21049 TxbSet::Chroma8,
21050 TX16,
21051 TX8,
21052 (&scan16, &scan8),
21053 true,
21054 &mut y,
21055 &mut u,
21056 &mut v,
21057 base_q_idx,
21058 enable_filter_intra,
21059 allow_screen_content_tools,
21060 allow_intrabc,
21061 &scan32,
21062 &scan16,
21063 &scan8,
21064 &scan4,
21065 tx_select,
21066 reduced_tx_set, fctx,
21067 )?;
21068 decode_block(
21069 &mut dec,
21070 &mut cdfs,
21071 &mut neighbours,
21072 (at32.0 + 1, at32.1 + 1),
21073 SUB,
21074 TxbSet::Luma16,
21075 TxbSet::Chroma8,
21076 TX16,
21077 TX8,
21078 (&scan16, &scan8),
21079 true,
21080 &mut y,
21081 &mut u,
21082 &mut v,
21083 base_q_idx,
21084 enable_filter_intra,
21085 allow_screen_content_tools,
21086 allow_intrabc,
21087 &scan32,
21088 &scan16,
21089 &scan8,
21090 &scan4,
21091 tx_select,
21092 reduced_tx_set, fctx,
21093 )?;
21094 }
21095 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
21096 // lane-tx64x16 r3: the 1:4 pair at the 32x32
21097 // level -- four 32x8 (or 8x32) strips in
21098 // raster order, `quarter_step` = 2 mi, with
21099 // libaom `decode_partition`'s own `i > 0`
21100 // frame-edge break.
21101 let horz = part32 == PARTITION_HORZ_4;
21102 let base_mi = (at32.0 * (SUB / MI), at32.1 * (SUB / MI));
21103 let mut prev: Option<((usize, usize), usize)> = None;
21104 for i in 0..4 {
21105 let strip_mi = if horz {
21106 (base_mi.0 + i * 2, base_mi.1)
21107 } else {
21108 (base_mi.0, base_mi.1 + i * 2)
21109 };
21110 if i > 0
21111 && (strip_mi.0 >= mi_rows as usize
21112 || strip_mi.1 >= mi_cols as usize)
21113 {
21114 break;
21115 }
21116 let (bw, bh) = if horz { (32, 8) } else { (8, 32) };
21117 let (mode, _uv) = decode_block_rect4(
21118 &mut dec,
21119 &mut cdfs,
21120 &mut neighbours,
21121 strip_mi,
21122 bw,
21123 bh,
21124 prev,
21125 &mut y,
21126 &mut u,
21127 &mut v,
21128 enable_filter_intra,
21129 allow_screen_content_tools,
21130 base_q_idx,
21131 tx_select, fctx,
21132 )?;
21133 prev = Some((strip_mi, mode));
21134 }
21135 }
21136 _ => {
21137 return Err(unsupported(format!(
21138 "a 32x32 partition type this decoder does not code (value={part32})"
21139 )));
21140 }
21141 }
21142 }
21143 }
21144 PARTITION_HORZ => {
21145 // lane-sbpart r2: two true 64x32 strips.
21146 decode_block_rect64(
21147 &mut dec,
21148 &mut cdfs,
21149 &mut neighbours,
21150 at,
21151 64,
21152 32,
21153 &mut y,
21154 &mut u,
21155 &mut v,
21156 enable_filter_intra,
21157 allow_screen_content_tools,
21158 base_q_idx,
21159 tx_select,
21160 reduced_tx_set, fctx,
21161 )?;
21162 if !has_rows {
21163 bump_edge32(6);
21164 }
21165 // lane-golomb r1: at the frame edge only the first half of the
21166 // strip is coded (libaom `decode_partition` guards the second
21167 // with the same has_rows test that made this partition non-square).
21168 if has_rows {
21169 decode_block_rect64(
21170 &mut dec,
21171 &mut cdfs,
21172 &mut neighbours,
21173 (at.0 + 2, at.1),
21174 64,
21175 32,
21176 &mut y,
21177 &mut u,
21178 &mut v,
21179 enable_filter_intra,
21180 allow_screen_content_tools,
21181 base_q_idx,
21182 tx_select,
21183 reduced_tx_set, fctx,
21184 )?;
21185 }
21186 }
21187 PARTITION_VERT => {
21188 // lane-sbpart r2: mirror of PARTITION_HORZ above with
21189 // width/height swapped.
21190 decode_block_rect64(
21191 &mut dec,
21192 &mut cdfs,
21193 &mut neighbours,
21194 at,
21195 32,
21196 64,
21197 &mut y,
21198 &mut u,
21199 &mut v,
21200 enable_filter_intra,
21201 allow_screen_content_tools,
21202 base_q_idx,
21203 tx_select,
21204 reduced_tx_set, fctx,
21205 )?;
21206 if !has_cols {
21207 bump_edge32(7);
21208 }
21209 // lane-golomb r1: at the frame edge only the first half of the
21210 // strip is coded (libaom `decode_partition` guards the second
21211 // with the same has_cols test that made this partition non-square).
21212 if has_cols {
21213 decode_block_rect64(
21214 &mut dec,
21215 &mut cdfs,
21216 &mut neighbours,
21217 (at.0, at.1 + 2),
21218 32,
21219 64,
21220 &mut y,
21221 &mut u,
21222 &mut v,
21223 enable_filter_intra,
21224 allow_screen_content_tools,
21225 base_q_idx,
21226 tx_select,
21227 reduced_tx_set, fctx,
21228 )?;
21229 }
21230 }
21231 PARTITION_HORZ_A | PARTITION_HORZ_B | PARTITION_VERT_A | PARTITION_VERT_B => {
21232 // lane-part32 r4: the four superblock-level AB arms, each
21233 // two 32x32 squares plus one 64x32/32x64 strip, in
21234 // libaom's own `decode_partition` order (decodeframe.c:
21235 // HORZ_A = TL, TR, bottom strip; HORZ_B = top strip, BL,
21236 // BR; VERT_A = TL, BL, right strip; VERT_B = left strip,
21237 // TR, BR). The pieces are exactly the ones already proven
21238 // by the `PARTITION_NONE`-under-SPLIT (32x32 square) and
21239 // `PARTITION_HORZ`/`VERT` (rect64 strip) arms above.
21240 SB_AB_HITS.with(|c| {
21241 let mut h = c.get();
21242 h[part - PARTITION_HORZ_A] += 1;
21243 c.set(h);
21244 });
21245 // lane-part32 r5: only the two VERTICAL arms reorder the
21246 // square sub-blocks (TL, BL, TR, BR), so only they switch
21247 // libaom's `has_tr`/`has_bl` tables.
21248 let _vert_ab = (part == PARTITION_VERT_A || part == PARTITION_VERT_B)
21249 .then(crate::encode::Reach::vert_ab_partition);
21250 macro_rules! square32 {
21251 ($at:expr) => {
21252 decode_block(
21253 &mut dec,
21254 &mut cdfs,
21255 &mut neighbours,
21256 $at,
21257 BLOCK,
21258 TxbSet::Luma32,
21259 TxbSet::Chroma16,
21260 TX32,
21261 TX16,
21262 (&scan32, &scan16),
21263 true,
21264 &mut y,
21265 &mut u,
21266 &mut v,
21267 base_q_idx,
21268 enable_filter_intra,
21269 allow_screen_content_tools,
21270 allow_intrabc,
21271 &scan32,
21272 &scan16,
21273 &scan8,
21274 &scan4,
21275 tx_select,
21276 reduced_tx_set, fctx,
21277 )?
21278 };
21279 }
21280 macro_rules! strip64 {
21281 ($at:expr, $bw:expr, $bh:expr) => {
21282 decode_block_rect64(
21283 &mut dec,
21284 &mut cdfs,
21285 &mut neighbours,
21286 $at,
21287 $bw,
21288 $bh,
21289 &mut y,
21290 &mut u,
21291 &mut v,
21292 enable_filter_intra,
21293 allow_screen_content_tools,
21294 base_q_idx,
21295 tx_select,
21296 reduced_tx_set, fctx,
21297 )?
21298 };
21299 }
21300 let (br, bc) = (at.0 + 2, at.1 + 2);
21301 match part {
21302 PARTITION_HORZ_A => {
21303 square32!(at);
21304 square32!((at.0, bc));
21305 strip64!((br, at.1), 64, 32);
21306 }
21307 PARTITION_HORZ_B => {
21308 strip64!(at, 64, 32);
21309 square32!((br, at.1));
21310 square32!((br, bc));
21311 }
21312 PARTITION_VERT_A => {
21313 square32!(at);
21314 square32!((br, at.1));
21315 strip64!((at.0, bc), 32, 64);
21316 }
21317 _ => {
21318 strip64!(at, 32, 64);
21319 square32!((at.0, bc));
21320 square32!((br, bc));
21321 }
21322 }
21323 }
21324 PARTITION_HORZ_4 | PARTITION_VERT_4 => {
21325 // lane-tx64x16: the 1:4 pair at 64x64 -- four 64x16 (or
21326 // 16x64) strips in raster order. `decode_partition`
21327 // (`decodeframe.c`) steps by `quarter_step = mi_size / 4`
21328 // (4 mi = 16 px = one SUB unit here) and BREAKS at the
21329 // frame edge for `i > 0`, so a partial superblock codes
21330 // only the strips whose origin is inside the frame.
21331 let horz = part == PARTITION_HORZ_4;
21332 for i in 0..4 {
21333 let step_mi = i * (SB_MI as usize / 4);
21334 let (this_r_mi, this_c_mi) = if horz {
21335 (sb_r as usize * SB_MI as usize + step_mi, sb_c as usize * SB_MI as usize)
21336 } else {
21337 (sb_r as usize * SB_MI as usize, sb_c as usize * SB_MI as usize + step_mi)
21338 };
21339 if i > 0
21340 && (this_r_mi >= mi_rows as usize || this_c_mi >= mi_cols as usize)
21341 {
21342 break;
21343 }
21344 let strip_at = if horz { (at.0 + i, at.1) } else { (at.0, at.1 + i) };
21345 let (bw, bh) = if horz { (64, 16) } else { (16, 64) };
21346 decode_block_rect64(
21347 &mut dec,
21348 &mut cdfs,
21349 &mut neighbours,
21350 strip_at,
21351 bw,
21352 bh,
21353 &mut y,
21354 &mut u,
21355 &mut v,
21356 enable_filter_intra,
21357 allow_screen_content_tools,
21358 base_q_idx,
21359 tx_select,
21360 reduced_tx_set, fctx,
21361 )?;
21362 }
21363 }
21364 _ => {
21365 return Err(unsupported(
21366 "a superblock-level partition value outside PARTITION_NONE..PARTITION_VERT_4",
21367 ));
21368 }
21369 }
21370 }
21371 }
21372 if waving {
21373 wave_submit(fctx, wave_job.0, wave_job.1);
21374 }
21375 flush_recon(fctx, &mut y, &mut u, &mut v);
21376
21377 if tile_num == tile_info.context_update_tile_id {
21378 result_cdfs = cdfs;
21379 }
21380 }
21381
21382 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
21383 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
21384 // that isolate whether a decode-order frame's mismatch already exists
21385 // in reconstruction (this dump) vs is introduced by the loop filter
21386 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
21387 // Decode-order frame marker for the EC_OBMC / EC_TRACE_MODE ladders.
21388 if crate::envflags::env_flag!("EC_OBMC")
21389 || crate::envflags::env_flag!("EC_TRACE_MODE")
21390 || crate::envflags::env_flag!("EC_PRED")
21391 {
21392 eprintln!(
21393 "EC_PICT idx={}",
21394 PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst)
21395 );
21396 }
21397 dump_stage16("EC_AV1_PREFILT_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
21398 if let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_DUMP") {
21399 use std::io::Write;
21400 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
21401 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
21402 let narrow = |p: &PlaneBuf<'_>| -> Vec<u8> { p.data.iter().map(|&s| s as u8).collect() };
21403 let _ = f.write_all(&narrow(&y));
21404 let _ = f.write_all(&narrow(&u));
21405 let _ = f.write_all(&narrow(&v));
21406 }
21407 } else {
21408 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
21409 }
21410 if let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_WIDE_DUMP") {
21411 use std::io::Write;
21412 static IDX2: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
21413 let idx = IDX2.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
21414 let crop_wide = |plane: &PlaneBuf<'_>| -> Vec<u8> {
21415 let mut out = Vec::with_capacity(plane.true_width * plane.true_height);
21416 for row in 0..plane.true_height {
21417 out.extend(plane.data[row * plane.width..][..plane.true_width].iter().map(|&s| s as u8));
21418 }
21419 out
21420 };
21421 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
21422 let _ = f.write_all(&crop_wide(&y));
21423 let _ = f.write_all(&crop_wide(&u));
21424 let _ = f.write_all(&crop_wide(&v));
21425 }
21426 }
21427 apply_deblock(
21428 &mut y,
21429 &mut u,
21430 &mut v,
21431 loop_filter,
21432 &neighbours,
21433 frame_width as usize,
21434 frame_height as usize, fctx,
21435 );
21436 // lane-perf4: loop restoration is the only reader of the pre-CDEF planes,
21437 // and a frame that restores nothing copied every plane twice for nothing
21438 // (three `PlaneBuf` clones here plus the `cdef.to_vec()` inside
21439 // [`crate::restoration::apply_loop_restoration_plane`], which returns its
21440 // input unchanged when the plane's type is `None`). Clone only when some
21441 // plane actually restores.
21442 let lr_active = (0..3).any(|p| {
21443 lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None
21444 && lr.loop_restoration_size[p] != 0
21445 });
21446 let deblocked =
21447 lr_active.then(|| (plane_snapshot(&y, 0), plane_snapshot(&u, 1), plane_snapshot(&v, 1)));
21448 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
21449 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
21450 // dump above these bisect WHICH filter stage introduced a mismatch.
21451 dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v);
21452 dump_stage16("EC_AV1_POSTDEBLOCK_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
21453 apply_cdef(
21454 &mut y,
21455 &mut u,
21456 &mut v,
21457 cdef,
21458 &neighbours,
21459 (frame_width as usize, frame_height as usize), fctx,
21460 );
21461 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
21462 dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize);
21463 // spec 7.16 (libaom `superres_post_decode`, decodeframe.c: called
21464 // between `av1_cdef_frame` and `av1_loop_restoration_filter_frame`):
21465 // the horizontal upscale runs HERE -- after CDEF, before loop
21466 // restoration, not after the whole filter chain. Both the post-CDEF
21467 // frame and the post-deblock frame that LR substitutes at its stripe
21468 // boundaries are upscaled (`save_deblock_boundary_lines` runs
21469 // `av1_upscale_normative_rows` over its saved rows when the frame is
21470 // scaled), so every LR coordinate from here on is in upscaled space.
21471 let mut deblocked = deblocked;
21472 let mut lr_w = frame_width as usize;
21473 if let Some((upscaled_w, _)) = superres(fctx) {
21474 let bd = u32::from(bit_depth(fctx));
21475 let (uw, fw, fh) = (upscaled_w as usize, frame_width as usize, frame_height as usize);
21476 let up = |p: &PlaneBuf<'_>, in_w: usize, in_h: usize, out_w: usize| PlaneBuf {
21477 data: std::borrow::Cow::Owned(crate::superres::upscale_plane_strided(
21478 &p.data, p.width, in_w, in_h, p.true_width, out_w, bd,
21479 )),
21480 width: out_w,
21481 height: in_h,
21482 true_width: out_w,
21483 true_height: in_h,
21484 tile_x0: 0,
21485 tile_y0: 0,
21486 tile_x1: out_w,
21487 tile_y1: in_h,
21488 };
21489 let (cw, ch, cuw) = (fw.div_ceil(2), fh.div_ceil(2), uw.div_ceil(2));
21490 y = up(&y, fw, fh, uw);
21491 u = up(&u, cw, ch, cuw);
21492 v = up(&v, cw, ch, cuw);
21493 if let Some((dy, du, dv)) = deblocked.take() {
21494 deblocked = Some((up(&dy, fw, fh, uw), up(&du, cw, ch, cuw), up(&dv, cw, ch, cuw)));
21495 }
21496 lr_w = uw;
21497 crate::superres::note_upscaled_picture();
21498 }
21499 if let Some((deblocked_y, deblocked_u, deblocked_v)) = &deblocked {
21500 apply_loop_restoration(
21501 &mut y, &mut u, &mut v, deblocked_y, deblocked_u, deblocked_v, lr, &lr_grid,
21502 (lr_w, frame_height as usize), fctx,
21503 );
21504 }
21505 if let Some((db_y, db_u, db_v)) = deblocked {
21506 // LIFO pool: return in reverse so the next frame's `y`/`u`/`v`
21507 // snapshots pop buffers of their own size and never resize.
21508 scratch_return(db_v.data.into_owned());
21509 scratch_return(db_u.data.into_owned());
21510 scratch_return(db_y.data.into_owned());
21511 }
21512
21513 let (fw, fh) = (lr_w, frame_height as usize);
21514 // An upscaled frame is already at its final size with no mi-aligned
21515 // margin beyond it (the upscale consumed those columns), so the
21516 // wide-margin stash below has nothing left to hand out.
21517 let (true_width, true_height) = if superres(fctx).is_some() {
21518 (fw, fh)
21519 } else {
21520 (true_width, true_height)
21521 };
21522 if fw == width && fh == height {
21523 fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None);
21524 return Ok((
21525 Picture {
21526 width,
21527 height,
21528 y: y.data.into_owned(),
21529 u: u.data.into_owned(),
21530 v: v.data.into_owned(),
21531 },
21532 result_cdfs,
21533 ));
21534 }
21535 let crop = |plane: &PlaneBuf<'_>, w: usize, h: usize| -> Vec<u16> {
21536 let mut out = Vec::with_capacity(w * h);
21537 for row in 0..h {
21538 out.extend(plane.data[row * plane.width..][..w].iter().copied());
21539 }
21540 out
21541 };
21542 // lane-superres r3: `true_width`/`true_height` (`mi_cols`/`mi_rows` * 4)
21543 // is the real reconstructed extent -- columns `[fw, true_width)` hold
21544 // genuine decoded samples (the last coding block straddles the frame
21545 // edge whenever `frame_width` isn't 8-sample aligned), not padding.
21546 // libaom's superres upscale runs on that buffer's own border-extended
21547 // margin, so it reads those real columns, not a synthetic replicate of
21548 // column `fw - 1`. Stash them for `stream.rs`'s superres path (a real
21549 // aomenc 43->64 stream pinned column-by-column against libaom's own
21550 // `av1_convolve_horiz_rs_c` via `scripts/superres-pin-harness.c` --
21551 // `row6-realedgeval` proved the replicate-of-`fw-1` padding this
21552 // decoder used before was off by 1 at the columns the tap window
21553 // reaches into that real margin; `None` when there is no margin (this
21554 // frame's `true_width`/`true_height` already equal `fw`/`fh`, e.g. a
21555 // non-superres frame whose width just isn't 32-block aligned).
21556 fctx.last_frame_wide_margin.with(|m| {
21557 *m.borrow_mut() = if true_width > fw || true_height > fh {
21558 let yc = crop(&y, true_width, true_height);
21559 if let Ok(path) = crate::envflags::var("EC_AV1_MARGIN_DUMP") {
21560 use std::io::Write;
21561 static IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
21562 let idx = IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
21563 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
21564 // corner-cut: this diagnostic dump stays 8-bit-narrowed
21565 // regardless of the stream's real bit depth (debug-only,
21566 // never read by a gate); widen if a >8-bit margin dump
21567 // is ever needed.
21568 let _ = f.write_all(&yc.iter().map(|&s| s as u8).collect::<Vec<u8>>());
21569 }
21570 }
21571 Some(Picture {
21572 width: true_width,
21573 height: true_height,
21574 y: yc,
21575 u: crop(&u, true_width.div_ceil(2), true_height.div_ceil(2)),
21576 v: crop(&v, true_width.div_ceil(2), true_height.div_ceil(2)),
21577 })
21578 } else {
21579 None
21580 }
21581 });
21582 Ok((
21583 Picture {
21584 width: fw,
21585 height: fh,
21586 y: crop_owned(y, fw, fh),
21587 u: crop_owned(u, fw.div_ceil(2), fh.div_ceil(2)),
21588 v: crop_owned(v, fw.div_ceil(2), fh.div_ceil(2)),
21589 },
21590 result_cdfs,
21591 ))
21592}
21593
21594/// `av1_get_pred_context_switchable_interp`'s context for `interp_filter[dir]`
21595/// -- `above`/`left` are the neighbour's own resolved index for this
21596/// direction (0..=2, or `3` = no info, spec `SWITCHABLE_FILTERS`).
21597/// `is_compound` folds in libaom `av1_get_pred_context_switchable_interp`'s
21598/// own `ctx_offset` term (`INTER_FILTER_COMP_OFFSET` = 4, added when *this*
21599/// block itself has a second reference) -- lane-av1idx: a stale "this
21600/// decoder never codes a compound reference" assumption baked this to
21601/// always-0, which desynced the CDF context bucket (not the decoded value
21602/// outright, hence small pixel deltas rather than a hard desync) the moment
21603/// lane-av1blend unmasked plain-average compound blocks on a Switchable-
21604/// filter frame.
21605fn switchable_interp_ctx(above: u8, left: u8, dir: usize, is_compound: bool) -> usize {
21606 let base = dir * 8 + if is_compound { 4 } else { 0 };
21607 let term = if left == above {
21608 left
21609 } else if left == 3 {
21610 above
21611 } else if above == 3 {
21612 left
21613 } else {
21614 3
21615 };
21616 base + term as usize
21617}
21618
21619/// Resolves the interpolation filter kernel(s) an inter block's motion
21620/// compensation reads (spec 5.11.10/5.11.20): a fixed-filter frame
21621/// (`interp_fixed = Some`) never reads a symbol; a `Switchable` frame
21622/// (`interp_fixed = None`) reads `interp_filter[0]` and, when
21623/// `enable_dual_filter`, a second `interp_filter[1]` -- unless
21624/// `force_regular` (this block's own `needs_interp_filter() == 0` case: a
21625/// `GLOBALMV` block, whose global motion is always `IDENTITY` in this
21626/// decoder's scope, spec 5.11.10's `large && YMode == GLOBALMV` branch),
21627/// which forces `EIGHTTAP` without reading anything.
21628#[allow(clippy::too_many_arguments)]
21629fn resolve_interp_filter(
21630 dec: &mut SymbolDecoder,
21631 cdfs: &mut Cdfs,
21632 interp_fixed: Option<mc::InterpFilterKind>,
21633 enable_dual_filter: bool,
21634 force_regular: bool,
21635 above: [u8; 2],
21636 left: [u8; 2],
21637 is_compound: bool,
21638) -> (mc::InterpFilterKind, mc::InterpFilterKind, [u8; 2]) {
21639 if let Some(kind) = interp_fixed {
21640 return (kind, kind, [3, 3]);
21641 }
21642 if force_regular {
21643 return (
21644 mc::InterpFilterKind::Regular,
21645 mc::InterpFilterKind::Regular,
21646 [0, 0],
21647 );
21648 }
21649 // libaom `av1_extract_interp_filter`/`read_mb_interp_filter`: the
21650 // symbol read at `dir=0` becomes the block's *vertical* (`y_filter`)
21651 // kernel, `dir=1` the *horizontal* (`x_filter`) one -- `dir` is not
21652 // "horizontal then vertical" despite `predict_with_filters`' own
21653 // `h_kind`/`v_kind` argument order, which is why this function returns
21654 // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`).
21655 let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound);
21656 if crate::envflags::env_flag!("EC_AV1_IFDBG") {
21657 eprintln!(
21658 "IFDBG dir=0 ctx={ctx0} above={above:?} left={left:?} cdf={:?}",
21659 &cdfs.switchable_interp[ctx0][..3]
21660 );
21661 }
21662 let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8;
21663 let sym1 = if enable_dual_filter {
21664 let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound);
21665 if crate::envflags::env_flag!("EC_AV1_IFDBG") {
21666 eprintln!(
21667 "IFDBG dir=1 ctx={ctx1} above={above:?} left={left:?} cdf={:?} sym0={sym0}",
21668 &cdfs.switchable_interp[ctx1][..3]
21669 );
21670 }
21671 dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8
21672 } else {
21673 sym0
21674 };
21675 if enable_dual_filter && sym0 != sym1 {
21676 DUAL_FILTER_DIFF_HITS.with(|c| c.set(c.get() + 1));
21677 }
21678 if crate::envflags::env_flag!("EC_TRACE_MODE") {
21679 eprintln!(
21680 "EC_IF ctx0={ctx0} above={above:?} left={left:?} sym0={sym0} sym1={sym1} rng={}",
21681 dec.debug_state().0
21682 );
21683 }
21684 (
21685 mc::InterpFilterKind::from_switchable_symbol(sym1 as usize),
21686 mc::InterpFilterKind::from_switchable_symbol(sym0 as usize),
21687 [sym0, sym1],
21688 )
21689}
21690
21691/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`),
21692/// duplicating [`crate::tile`]'s private copy of the same rule.
21693pub(crate) fn intra_inter_ctx(
21694 has_above: bool,
21695 has_left: bool,
21696 above_inter: bool,
21697 left_inter: bool,
21698) -> usize {
21699 match (has_above, has_left) {
21700 (true, true) => {
21701 let (above_intra, left_intra) = (!above_inter, !left_inter);
21702 if above_intra && left_intra {
21703 3
21704 } else {
21705 usize::from(above_intra || left_intra)
21706 }
21707 }
21708 (true, false) => 2 * usize::from(!above_inter),
21709 (false, true) => 2 * usize::from(!left_inter),
21710 (false, false) => 0,
21711 }
21712}
21713
21714/// `CLASS0_SIZE << (class + 2)`, duplicating `crate::tile`'s private
21715/// `mv_class_base` (spec 3): the magnitude an `MV_CLASS_n` component's own
21716/// bits start counting from.
21717fn mv_class_base(class: usize) -> i32 {
21718 if class == 0 { 0 } else { 2i32 << (class + 2) }
21719}
21720
21721/// One motion vector component's non-zero diff (spec 5.11.32
21722/// `read_mv_component`), the inverse of [`crate::tile`]'s private
21723/// `write_mv_component`.
21724fn read_mv_component(
21725 dec: &mut SymbolDecoder,
21726 c: &mut MvComponentCdfs,
21727 allow_high_precision_mv: bool,
21728 force_integer_mv: bool,
21729) -> i32 {
21730 let sign = dec.symbol(&mut c.sign);
21731 let class = dec.symbol(&mut c.class);
21732 let local = if class == 0 {
21733 let bit = dec.symbol(&mut c.class0_bit);
21734 // spec 5.11.32 `mv_class0_fr`: not coded at all when the frame
21735 // forces integer motion vectors -- implicitly `3` (the top
21736 // fractional value) rather than read, else every symbol after it
21737 // in the tile desyncs by one read.
21738 let fr = if force_integer_mv {
21739 3
21740 } else {
21741 dec.symbol(&mut c.class0_fr[bit])
21742 };
21743 // spec 5.11.32 `mv_class0_hp`: read only when the frame allows
21744 // high-precision motion vectors, else implicitly 1 (the low bit
21745 // stays at half-pel precision) -- this crate's own writer always
21746 // leaves the flag off, but a foreign stream can set it per frame.
21747 let hp = if allow_high_precision_mv {
21748 dec.symbol(&mut c.class0_hp)
21749 } else {
21750 1
21751 };
21752 (bit << 3) | (fr << 1) | hp
21753 } else {
21754 let mut d = 0;
21755 for i in 0..class {
21756 d |= dec.symbol(&mut c.bit[i]) << i;
21757 }
21758 // spec 5.11.32 `mv_fr`: same force_integer_mv carve-out as
21759 // `mv_class0_fr` above.
21760 let fr = if force_integer_mv { 3 } else { dec.symbol(&mut c.fr) };
21761 let hp = if allow_high_precision_mv {
21762 dec.symbol(&mut c.hp)
21763 } else {
21764 1
21765 };
21766 (d << 3) | (fr << 1) | hp
21767 };
21768 let mag = mv_class_base(class) + local as i32 + 1;
21769 if sign == 1 { -mag } else { mag }
21770}
21771
21772/// A motion vector coded as a residual against `pred` (spec 5.11.32
21773/// `read_mv`), the inverse of [`crate::tile`]'s private `write_mv`.
21774fn read_mv(
21775 dec: &mut SymbolDecoder,
21776 mv_comp: &mut [MvComponentCdfs; 2],
21777 mv_joint: &mut [u16; 5],
21778 pred: (i32, i32),
21779 allow_high_precision_mv: bool,
21780 force_integer_mv: bool,
21781) -> (i32, i32) {
21782 let joint = dec.symbol(mv_joint);
21783 let mut diff = (0, 0);
21784 if joint == 2 || joint == 3 {
21785 diff.0 = read_mv_component(dec, &mut mv_comp[0], allow_high_precision_mv, force_integer_mv);
21786 }
21787 if joint == 1 || joint == 3 {
21788 diff.1 = read_mv_component(dec, &mut mv_comp[1], allow_high_precision_mv, force_integer_mv);
21789 }
21790 (pred.0 + diff.0, pred.1 + diff.1)
21791}
21792
21793/// One intrabc block's block vector (spec 5.11.13 `read_intrabc_info` ->
21794/// `assign_mv` with `use_intrabc`, libaom `assign_dv`/`av1_find_ref_dv`).
21795///
21796/// The predictor is the ordinary MV stack built against `INTRA_FRAME`
21797/// (`av1_find_mv_refs(..., INTRA_FRAME, ...)`): `nearestmv`, or `nearmv`
21798/// when that is zero, or -- when both are -- the fixed fallback DV one
21799/// superblock up, or `INTRABC_DELAY_PIXELS` (256) plus one superblock to the
21800/// left when this is the tile's first superblock row. The predictor is then
21801/// rounded to full pel, and the difference reads off the *dv* nmv context
21802/// (libaom `ndvc`) at full-pel precision (`MV_SUBPEL_NONE`: no `fr`/`hp`
21803/// symbols, exactly this decoder's `force_integer_mv` carve-out). No DRL
21804/// symbol is coded for a DV, so none of this can move the bitstream
21805/// position -- only the reconstructed vector.
21806fn read_intrabc_dv(
21807 dec: &mut SymbolDecoder,
21808 cdfs: &mut Cdfs,
21809 mi_r: usize,
21810 mi_c: usize,
21811 side: usize, fctx: &crate::decode::FrameCtx,
21812) -> (i32, i32) {
21813 const INTRABC_DELAY_PIXELS: i32 = 256;
21814 let n4 = side / MI;
21815 let stack_pred = fctx.intrabc_mi_grid.with(|g| {
21816 let g = g.borrow();
21817 g.as_ref().map(|(grid, mi_cols, mi_rows)| {
21818 let stack = crate::mvstack::find_mv_stack(
21819 grid, mi_r, mi_c, n4, n4, 0, /* INTRA_FRAME */
21820 *mi_cols, *mi_rows,
21821 );
21822 if stack.nearest_mv == (0, 0) {
21823 stack.near_mv
21824 } else {
21825 stack.nearest_mv
21826 }
21827 })
21828 });
21829 let mut pred = stack_pred.unwrap_or((0, 0));
21830 if pred == (0, 0) {
21831 // `av1_find_ref_dv` (mvref_common.c). Tile row start is 0 here (the
21832 // single-tile-row case every intrabc gate stream is).
21833 // lane-t900 r34: `av1_find_ref_dv` takes `mib_size` -- the SEQUENCE's
21834 // superblock size in mi units -- so a 128x128 superblock stream's
21835 // fallback DV is one 128-px superblock up (or 128+256 px left on the
21836 // tile's first superblock row), never the 64 this hardcoded.
21837 let sb_mi = sb_mi_cur(fctx) as i32;
21838 let sb_px = sb_mi * MI as i32;
21839 pred = if (mi_r as i32) < sb_mi {
21840 (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8)
21841 } else {
21842 (-sb_px * 8, 0)
21843 };
21844 }
21845 // "Ref DV should not have sub-pel" (`assign_dv`): floor to full pel.
21846 let pred = ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8);
21847 read_mv(dec, &mut cdfs.dv_comp, &mut cdfs.dv_joint, pred, false, true)
21848}
21849
21850/// A 1/8-pel motion vector component converted to the 1/16-pel offset
21851/// [`mc::predict`] takes, duplicating [`crate::encode`]'s private `mv_to_q4`
21852/// (its own doc comment explains the `*2`/`*1` luma/chroma split).
21853fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
21854 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
21855}
21856
21857impl PlaneBuf<'_> {
21858 /// Adds `residual` onto an already-computed `prediction` (motion
21859 /// compensation's output, rather than [`predict`]'s intra one), writing
21860 /// the clamped reconstruction into the plane at `(x, y)` -- the inter
21861 /// counterpart of [`PlaneBuf::reconstruct`].
21862 /// [`Self::reconstruct_mc_rect`], writing only a `w`x`h` sub-rectangle of the
21863 /// `side`x`side` `prediction`/`residual` buffers (which stay `side`-square
21864 /// for stride/indexing) -- lane-partitions r1: a true rectangular HORZ/
21865 /// VERT strip is predicted at its enclosing square `side` (matching
21866 /// `HORZ_B`'s already-accepted square-context corner-cut, lane-warp r5)
21867 /// but only its own true `w`x`h` footprint is committed to the plane, so
21868 /// two strips sharing a square's coordinate origin never clobber each
21869 /// other's real pixels.
21870 fn reconstruct_mc_rect(
21871 &mut self,
21872 x: usize,
21873 y: usize,
21874 side: usize,
21875 w: usize,
21876 h: usize,
21877 prediction: &[u16],
21878 residual: &[i32], fctx: &crate::decode::FrameCtx,
21879 ) {
21880 // lane-sb128c r7: a 128x64 half of a 128 root at the BOTTOM frame edge
21881 // is the first block shape whose true footprint overhangs the padded
21882 // coding surface (mi_rows = 198 -> a plane 800 rows tall, block rows
21883 // 768..832). libaom reconstructs those rows into the frame buffer's
21884 // border; nothing reads them back, so they are simply dropped here.
21885 let (h, w) = (h.min(self.height.saturating_sub(y)), w.min(self.width.saturating_sub(x)));
21886 // lane-perf4: one row of each operand at a time. `side` is the
21887 // prediction/residual stride and `self.width` the plane's, so the
21888 // three row bases are computed once per row instead of a
21889 // multiply-add per sample (the samples themselves are unchanged).
21890 let max = crate::decode::sample_max(fctx);
21891 for row in 0..h {
21892 let src = row * side;
21893 let dst = (y + row) * self.width + x;
21894 let pred = &prediction[src..src + w];
21895 let res = &residual[src..src + w];
21896 let out = &mut self.data.to_mut()[dst..dst + w];
21897 for ((o, &p), &r) in out.iter_mut().zip(pred).zip(res) {
21898 *o = (i32::from(p) + r).clamp(0, max) as u16;
21899 }
21900 }
21901 }
21902}
21903
21904/// Reads one inter-coded plane's transform block and reconstructs it by
21905/// adding its residual onto a motion-compensated `prediction` -- the inter
21906/// counterpart of [`read_plane`] (every inter transform this decoder reads is
21907/// `side`-square with no oversized-64 case, so there is no padded-grid
21908/// branch to mirror).
21909#[allow(clippy::too_many_arguments)]
21910fn read_inter_plane(
21911 dec: &mut SymbolDecoder,
21912 cdfs: &mut Cdfs,
21913 set: TxbSet,
21914 scan: &[u16],
21915 plane_idx: usize,
21916 around: (bool, bool, i32),
21917 tx_mode: usize,
21918 // lane-wave1 step (i): unread -- this reader records its write
21919 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
21920 // stays in the signature so every call site still proves the plane is
21921 // exclusively held while its coefficients are parsed.
21922 _plane: &mut PlaneBuf<'static>,
21923 x: usize,
21924 y: usize,
21925 side: usize,
21926 _base_q_idx: u8,
21927 prediction: Pred<'_>,
21928 // lane-chromau: this block's own luma transform's *actual coded*
21929 // `tx_type` -- `av1_get_tx_type` (libaom `blockd.h`): an inter block's
21930 // chroma plane never codes its own `tx_type` symbol, but (unlike an
21931 // intra block, which falls back to `Intra_Mode_To_Tx_Type`) it inherits
21932 // the colocated luma transform's coded type, narrowed to the extended
21933 // set the CHROMA size selects ([`reduce_inherited_chroma_tx_type`]).
21934 // `None` for the luma call itself
21935 // (`plane_idx == 0`), where the `TxbSet`'s own symbol (or the true
21936 // `DCT_DCT` default at 32-point+) already resolves it without help.
21937 inherited_luma_tx_type: Option<TxType>,
21938 // lane-txselect: the luma `txb_skip_ctx` of a transform unit smaller than
21939 // its own block (spec `get_txb_ctx_general`'s `plane_bsize != tx_size`
21940 // branch, [`Neighbours::luma_skip_ctx`]) -- `None` for the whole-block
21941 // transform every non-var-tx caller reads, whose plane-0 context is the
21942 // lone-transform-unit 0.
21943 luma_skip_ctx: Option<usize>, fctx: &crate::decode::FrameCtx,
21944) -> Result<(Vec<i32>, TxType)> {
21945 let skip_ctx = if plane_idx == 0 {
21946 luma_skip_ctx.unwrap_or(0)
21947 } else {
21948 // lane-sb128c r1: on a CHROMA plane this same parameter carries
21949 // `get_txb_ctx`'s own offset instead -- `combine_entropy_contexts(..)`
21950 // is +7 normally and +10 when the plane block is LARGER than the
21951 // transform (a 128x128 block's 64x64 uv plane block with TX_32X32
21952 // units, AV1's only such case), and the `txb_skip_chroma_32` table
21953 // carries the offset-10 rows at +3 (lane-sb128b r3).
21954 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
21955 };
21956 let mut coding = cdfs.txb(set, tx_mode);
21957 let default_tx_type = match inherited_luma_tx_type {
21958 Some(t) => reduce_inherited_chroma_tx_type(t, side, side, fctx),
21959 None => TxType::DctDct,
21960 };
21961 let (grid, tx_type) = read_coeffs(
21962 dec,
21963 &mut coding,
21964 scan,
21965 skip_ctx,
21966 dc_sign_ctx(around.2),
21967 default_tx_type,
21968 None,
21969 )?;
21970 note_chroma_class1(plane_idx, tx_type);
21971 if crate::envflags::env_flag!("EC_TRACE_TXTYPE") {
21972 eprintln!("OUR_TXTYPE plane={plane_idx} x={x} y={y} side={side} tx_type={tx_type:?} inh={inherited_luma_tx_type:?}");
21973 }
21974 // lane-inter8 r1: a 64-point transform covers the whole 64x64 area but
21975 // codes only its top-left 32x32 of frequencies (spec 5.11.40) -- the
21976 // caller hands the 32-point `scan` there, and the coded corner goes into
21977 // the top-left of the true `side`-sized grid before dequantization
21978 // (dqDenom is keyed by the true size, not the corner's), mirroring
21979 // [`read_plane`]'s own `tx_side != side` branch. Every other transform
21980 // this decoder codes has `tx_side == side`, so this is inert below 64.
21981 let tx_side = side.min(32);
21982 let grid = if tx_side == side {
21983 grid
21984 } else {
21985 let mut full = vec![0i32; side * side];
21986 for row in 0..tx_side {
21987 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
21988 }
21989 full
21990 };
21991 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
21992 let tx = TxParams {
21993 w: side, h: side, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta,
21994 ac_delta, tx_type, stride: 0,
21995 };
21996 push_mc_rect_tx(plane_idx, x, y, side, side, side, prediction, tx, &grid, fctx);
21997 Ok((grid, tx_type))
21998}
21999
22000/// Spec 5.11.25's `single_ref_p1`..`p6` tree (reachable only once `comp_mode`
22001/// is known `SINGLE_REFERENCE` -- `decode_stream` refuses any frame with
22002/// `reference_select` set before this is ever called, so that read is never
22003/// needed here). `above_ref`/`left_ref` are `-1` for an intra/unavailable
22004/// neighbour, else the `1..=7` reference that neighbour coded (lane-av1refs).
22005fn read_single_ref(
22006 dec: &mut SymbolDecoder,
22007 cdfs: &mut Cdfs,
22008 above_ref: i8,
22009 above_ref1: Option<i8>,
22010 left_ref: i8,
22011 left_ref1: Option<i8>,
22012) -> i8 {
22013 let above = (above_ref > 0).then_some(above_ref);
22014 let left = (left_ref > 0).then_some(left_ref);
22015 let p1 = dec.symbol(&mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0]);
22016 let ref_frame = if p1 == 1 {
22017 let p2 = dec.symbol(&mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1]);
22018 if p2 == 1 {
22019 ALTREF_FRAME
22020 } else {
22021 let p6 = dec.symbol(&mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5]);
22022 if p6 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
22023 }
22024 } else {
22025 let p3 = dec.symbol(&mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2]);
22026 if p3 == 1 {
22027 let p5 = dec.symbol(&mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4]);
22028 if p5 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
22029 } else {
22030 let p4 = dec.symbol(&mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3]);
22031 if p4 == 1 { LAST2_FRAME } else { LAST_FRAME }
22032 }
22033 };
22034 if ref_frame != LAST_FRAME {
22035 NON_LAST_REF_HITS.with(|c| c.set(c.get() + 1));
22036 let c = match ref_frame {
22037 LAST2_FRAME => &LAST2_HITS,
22038 LAST3_FRAME => &LAST3_HITS,
22039 GOLDEN_FRAME => &GOLDEN_HITS,
22040 BWDREF_FRAME => &BWDREF_HITS,
22041 ALTREF2_FRAME => &ALTREF2_HITS,
22042 ALTREF_FRAME => &ALTREF_HITS,
22043 _ => unreachable!("read_single_ref only ever returns LAST_FRAME..=ALTREF_FRAME"),
22044 };
22045 c.with(|v| v.set(v.get() + 1));
22046 }
22047 ref_frame
22048}
22049
22050/// Spec 5.11.25's `comp_mode` (lane-av1comp): whether an inter block reads
22051/// `SINGLE_REFERENCE` or `COMPOUND_REFERENCE`, only reached once a frame's
22052/// `reference_select` header bit lets a block choose per-block instead of
22053/// fixing the mode. `above`/`left` are `None` for an intra/unavailable
22054/// neighbour, [`NeighbourRef`] for a coded one -- [`reference_mode_ctx`]'s
22055/// own doc. Called from [`decode_inter_block`] once its own `reference_select`
22056/// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same
22057/// way with a coarser (`LAST_FRAME`-only) neighbour shape.
22058/// Resolves a compound reference's own planes -- the same `ref_frame ==
22059/// LAST_FRAME -> ref_y/u/v, else other_refs[ref_frame]` lookup
22060/// [`decode_inter_block`]'s single-ref path already does, factored out so
22061/// the compound path can call it twice (lane-av1comp).
22062fn ref_planes<'a>(
22063 ref_frame: i8,
22064 ref_y: &'a PlaneBuf<'a>,
22065 ref_u: &'a PlaneBuf<'a>,
22066 ref_v: &'a PlaneBuf<'a>,
22067 other_refs: &'a RefSlots,
22068) -> Result<(&'a PlaneBuf<'a>, &'a PlaneBuf<'a>, &'a PlaneBuf<'a>)> {
22069 if ref_frame == LAST_FRAME {
22070 Ok((ref_y, ref_u, ref_v))
22071 } else {
22072 match other_refs[ref_frame as usize] {
22073 Some((ry, ru, rv)) => Ok((ry, ru, rv)),
22074 None => Err(unsupported(
22075 "a reference frame selected with no picture at this frame's own \
22076 ref_frame_idx slot for it",
22077 )),
22078 }
22079 }
22080}
22081
22082/// libaom `foreach_overlappable_nb_above` (`obmc.h`): walks the mi row
22083/// directly above this block's own column span, one bordering block at a
22084/// time (stepping by that neighbour's own `MiInfo::size`, which is always
22085/// `<= 16` since no block this decoder ever codes exceeds 64x64), collecting
22086/// every *inter* neighbour found (an intra or unset cell is skipped, one mi
22087/// unit at a time, and does not itself count as a step). `max_neighbors`
22088/// caller-bounds the scan: `1` for the eligibility check (any hit at all),
22089/// `av1_build_obmc_inter_prediction`'s own `max_neighbor_obmc` table for the
22090/// real blend pass. lane-intra16x4 r2: libaom's own "4-wide block, treat as
22091/// half of a chroma pair" merge (`obmc.h`'s `mi_step == 1` special case) IS
22092/// ported below -- the round-1 note that no block is narrower than 8px stopped
22093/// being true when the 1:4 partitions landed. A 16x4 / 4x16 strip has
22094/// `mi_size_high`/`mi_size_wide` 1, so libaom snaps the walk back to the pair's
22095/// even index, reads the ODD (chroma-carrying) half as the neighbour and steps
22096/// by 2. Measured: the 16x16 block right of a 16x16-level HORZ_4 partition
22097/// whose strip 0 is inter and strips 1..3 intra counted that inter strip as
22098/// overlappable here, while libaom's pair merge reads the INTRA strip 1 and
22099/// counts none -- so we read a `motion_mode` symbol libaom never wrote (class
22100/// `symbol-consumption-gap`), desyncing the tile at the next coefficient.
22101fn overlappable_above(
22102 grid: &MiGrid,
22103 mi_row: usize,
22104 mi_col: usize,
22105 bw4: usize,
22106 mi_cols: usize,
22107 max_neighbors: usize,
22108) -> Vec<(usize, usize, MiInfo, usize)> {
22109 // lane-alloc: bounded by `max_neighbors`, so size it once.
22110 let mut out = Vec::with_capacity(max_neighbors);
22111 if mi_row == 0 {
22112 return out;
22113 }
22114 let end_col = (mi_col + bw4).min(mi_cols);
22115 let mut col = mi_col;
22116 while col < end_col && out.len() < max_neighbors {
22117 let cell = grid.get(mi_row - 1, col);
22118 let mut step = cell.map_or(1, |c| c.size as usize).max(1).min(SB_MI as usize);
22119 let mut nb = cell;
22120 // lane-obmcrec r1: the mi the neighbour's `MiInfo` is actually taken
22121 // from -- the pair merge below moves it, and libaom reads that same
22122 // `mbmi`'s `interp_filters` (`av1_setup_build_prediction_by_above_pred`).
22123 let mut src = col;
22124 if step == 1 {
22125 // The pair merge: the walk snaps back to the pair's even column
22126 // and the ODD half (the chroma-carrying one) is the neighbour for
22127 // both -- a 4-wide 1:4 strip is never an OBMC source on its own.
22128 col &= !1;
22129 src = col + 1;
22130 nb = grid.get(mi_row - 1, src);
22131 step = 2;
22132 }
22133 if let Some(info) = nb {
22134 if info.is_inter {
22135 if src != col {
22136 OBMC_PAIR_FILTER_HITS.with(|c| c.set(c.get() + 1));
22137 }
22138 // lane-t900 r14: libaom passes `AOMMIN(xd->width, mi_step)`
22139 // as `op_mi_size` -- the block's OWN width, never the
22140 // frame-edge clamp `end_col` carries. Clamping here shrank the
22141 // neighbour PREDICTION at a frame edge, which picks the
22142 // 4-tap kernel below 8 px (class narrow-block-sharp-kernel);
22143 // the destination clip stays in `obmc_blend`.
22144 out.push((col - mi_col, step.min(bw4), *info, src - mi_col));
22145 }
22146 }
22147 col += step;
22148 }
22149 out
22150}
22151
22152/// `foreach_overlappable_nb_left`'s left-column mirror of
22153/// [`overlappable_above`] -- see its doc for the shared corner-cut.
22154fn overlappable_left(
22155 grid: &MiGrid,
22156 mi_row: usize,
22157 mi_col: usize,
22158 bh4: usize,
22159 mi_rows: usize,
22160 max_neighbors: usize,
22161) -> Vec<(usize, usize, MiInfo, usize)> {
22162 // lane-alloc: bounded by `max_neighbors`, so size it once.
22163 let mut out = Vec::with_capacity(max_neighbors);
22164 if mi_col == 0 {
22165 return out;
22166 }
22167 let end_row = (mi_row + bh4).min(mi_rows);
22168 let mut row = mi_row;
22169 while row < end_row && out.len() < max_neighbors {
22170 let cell = grid.get(row, mi_col - 1);
22171 // Vertical walk steps by the neighbour's HEIGHT -- a 32x16 strip's
22172 // width (8) would swallow the strip below it.
22173 let mut step = cell.map_or(1, |c| c.size_h as usize).max(1).min(SB_MI as usize);
22174 let mut nb = cell;
22175 // lane-obmcrec r1: see `overlappable_above`'s `src`.
22176 let mut src = row;
22177 if step == 1 {
22178 // The pair merge, left-column mirror: a 4-TALL neighbour (a 16x4
22179 // strip) is half of a chroma pair and the pair's SECOND row is the
22180 // neighbour for both.
22181 row &= !1;
22182 src = row + 1;
22183 nb = grid.get(src, mi_col - 1);
22184 step = 2;
22185 }
22186 if let Some(info) = nb {
22187 if info.is_inter {
22188 if src != row {
22189 OBMC_PAIR_FILTER_HITS.with(|c| c.set(c.get() + 1));
22190 }
22191 // lane-t900 r14: `AOMMIN(xd->height, mi_step)` -- see
22192 // `overlappable_above`.
22193 out.push((row - mi_row, step.min(bh4), *info, src - mi_row));
22194 }
22195 }
22196 row += step;
22197 }
22198 out
22199}
22200
22201/// The warp-sample gather's own `has_top_right` probe (libaom `av1_findSamples`
22202/// calls the same `mvref_common.c` function the MV stack does). lane-sb128 r2:
22203/// this used to hardcode `SB_MI` (a 64x64 superblock) -- at `sb_size == 128`
22204/// libaom's mask loop runs one level further and strips the top-right sample
22205/// off blocks whose neighbour IS decoded, so a warped 128-superblock frame
22206/// picked up wrong warp parameters (frame 6 of the 128 inter gate). Delegates
22207/// to the single sb-aware port in [`crate::mvstack::has_top_right`]; `bs` is
22208/// the block's own side in 4x4 (`mi`) units (square inter leaves only here).
22209fn has_top_right(mi_row: usize, mi_col: usize, bs: usize, fctx: &crate::decode::FrameCtx) -> bool {
22210 crate::mvstack::has_top_right(mi_row, mi_col, bs, bs, fctx)
22211}
22212
22213/// `av1_findSamples` (`mvref_common.c`), full port: the up to
22214/// `LEAST_SQUARES_SAMPLES_MAX` (8) above/left/top-left/top-right neighbour
22215/// samples (`record_samples`) that share this block's own single reference
22216/// frame and are themselves single-ref -- `mbmi->num_proj_ref` is
22217/// `.len()` of the returned vec. `bw4` is the block's own side in 4x4 units
22218/// (square, so also `bh4`; a real block's `xd->width`/`xd->height` in
22219/// libaom are also mi units of that same square side here). Each sample's
22220/// own `bw`/`bh` (fed to [`crate::warp::record_sample`]'s offset formula)
22221/// come from the *neighbour* cell's own coded size, not this block's.
22222#[allow(clippy::too_many_arguments)]
22223fn find_samples(
22224 grid: &MiGrid,
22225 mi_row: usize,
22226 mi_col: usize,
22227 bw4: usize,
22228 bh4: usize,
22229 mi_cols: usize,
22230 mi_rows: usize,
22231 ref_frame: i8, fctx: &crate::decode::FrameCtx,
22232) -> Vec<crate::warp::Sample> {
22233 const MAX: usize = crate::warp::LEAST_SQUARES_SAMPLES_MAX;
22234 let up_available = mi_row > 0;
22235 let left_available = mi_col > 0;
22236 let mut samples = Vec::with_capacity(MAX);
22237 // lane-t900 r9: `EC_PROJ_MI=<mi_row>,<mi_col>` lists this block's warp
22238 // sample candidates in libaom's own order (above, left, top-left,
22239 // top-right) -- `num_proj_ref >= 1` is what picks the 3-symbol
22240 // motion_mode alphabet over the 2-symbol obmc one.
22241 // lane-alloc: the `format!` (and the map lookup's `String` clone) ran on
22242 // every warp block; the flag itself is a process constant.
22243 let proj_dbg = crate::envflags::env_flag!("EC_PROJ_MI")
22244 && crate::envflags::var("EC_PROJ_MI")
22245 .is_ok_and(|v| v == format!("{mi_row},{mi_col}"));
22246 let single_ref_match = |info: &MiInfo| {
22247 let m = info.ref_frame == ref_frame && info.ref_frame1.is_none();
22248 if proj_dbg {
22249 eprintln!(
22250 "EC_PROJ cand ref={} ref1={:?} size={} size_h={} is_inter={} want={ref_frame} match={m}",
22251 info.ref_frame, info.ref_frame1, info.size, info.size_h, info.is_inter
22252 );
22253 }
22254 m
22255 };
22256 let mut do_tl = true;
22257 let mut do_tr = true;
22258 let rec = |info: &MiInfo, row_offset: i32, sign_r: i32, col_offset: i32, sign_c: i32| {
22259 let nb_bw = (info.size * 4) as i32;
22260 // lane-rect r2: the neighbour's own true height -- a rect strip
22261 // neighbour donates its sample at ITS center (aom pts y=-72 for a
22262 // 32x16 above strip; the square assumption put it at -136).
22263 let nb_bh = (info.size_h * 4) as i32;
22264 crate::warp::record_sample(nb_bw, nb_bh, info.mv, row_offset, sign_r, col_offset, sign_c)
22265 };
22266
22267 'outer: {
22268 if up_available {
22269 let above = grid.get(mi_row - 1, mi_col);
22270 let superblock_width = above.map_or(1, |c| c.size as usize).max(1);
22271 if bw4 <= superblock_width {
22272 let col_offset = -((mi_col % superblock_width) as isize);
22273 if col_offset < 0 {
22274 do_tl = false;
22275 }
22276 if col_offset + superblock_width as isize > bw4 as isize {
22277 do_tr = false;
22278 }
22279 if let Some(info) = above {
22280 if single_ref_match(info) {
22281 samples.push(rec(info, 0, -1, col_offset as i32, 1));
22282 if samples.len() >= MAX {
22283 break 'outer;
22284 }
22285 }
22286 }
22287 } else {
22288 let mut i = 0usize;
22289 let limit = bw4.min(mi_cols.saturating_sub(mi_col));
22290 while i < limit {
22291 let cell = grid.get(mi_row - 1, mi_col + i);
22292 let sw = cell.map_or(1, |c| c.size as usize).max(1);
22293 if let Some(info) = cell {
22294 if single_ref_match(info) {
22295 samples.push(rec(info, 0, -1, i as i32, 1));
22296 if samples.len() >= MAX {
22297 break 'outer;
22298 }
22299 }
22300 }
22301 i += sw;
22302 }
22303 }
22304 }
22305
22306 if left_available {
22307 let left = grid.get(mi_row, mi_col - 1);
22308 let superblock_height = left.map_or(1, |c| c.size_h as usize).max(1);
22309 if bh4 <= superblock_height {
22310 let row_offset = -((mi_row % superblock_height) as isize);
22311 if row_offset < 0 {
22312 do_tl = false;
22313 }
22314 if let Some(info) = left {
22315 if single_ref_match(info) {
22316 samples.push(rec(info, row_offset as i32, 1, 0, -1));
22317 if samples.len() >= MAX {
22318 break 'outer;
22319 }
22320 }
22321 }
22322 } else {
22323 let mut i = 0usize;
22324 let limit = bh4.min(mi_rows.saturating_sub(mi_row));
22325 while i < limit {
22326 let cell = grid.get(mi_row + i, mi_col - 1);
22327 let sh = cell.map_or(1, |c| c.size_h as usize).max(1);
22328 if let Some(info) = cell {
22329 if single_ref_match(info) {
22330 samples.push(rec(info, i as i32, 1, 0, -1));
22331 if samples.len() >= MAX {
22332 break 'outer;
22333 }
22334 }
22335 }
22336 i += sh;
22337 }
22338 }
22339 }
22340
22341 if do_tl && left_available && up_available {
22342 if let Some(info) = grid.get(mi_row - 1, mi_col - 1) {
22343 if single_ref_match(info) {
22344 samples.push(rec(info, 0, -1, 0, -1));
22345 if samples.len() >= MAX {
22346 break 'outer;
22347 }
22348 }
22349 }
22350 }
22351
22352 // lane-t900 r9: libaom passes `AOMMAX(xd->width, xd->height)` here
22353 // (`mvref_common.c:1235`), NOT the block's width -- a rect block's
22354 // top-right reach is probed at its LONGER side. With `bw4` a 64x128
22355 // block found a top-right sample libaom never sees, so
22356 // `num_proj_ref >= 1` picked the 3-symbol `motion_mode_cdf` where
22357 // libaom reads the 2-symbol `obmc_cdf` (class
22358 // wrong-alphabet-same-value).
22359 let tr_reach = crate::mvstack::has_top_right(mi_row, mi_col, bw4, bh4, fctx);
22360 if do_tr && bw4 != bh4 && tr_reach != has_top_right(mi_row, mi_col, bw4, fctx) {
22361 TR_REACH_LONGER_SIDE_HITS.with(|c| c.set(c.get() + 1));
22362 }
22363 if do_tr && tr_reach {
22364 let tr_col = mi_col + bw4;
22365 if mi_row > 0 && tr_col < mi_cols {
22366 if let Some(info) = grid.get(mi_row - 1, tr_col) {
22367 if single_ref_match(info) {
22368 samples.push(rec(info, 0, -1, bw4 as i32, 1));
22369 }
22370 }
22371 }
22372 }
22373 }
22374 samples
22375}
22376
22377/// `mbmi->num_proj_ref`: [`find_samples`]'s own count, all that
22378/// `motion_mode_allowed` needs to pick the 3-symbol `motion_mode_cdf` over
22379/// the 2-symbol `obmc_cdf` (spec 5.11.24).
22380#[allow(clippy::too_many_arguments)]
22381fn num_proj_ref(
22382 grid: &MiGrid,
22383 mi_row: usize,
22384 mi_col: usize,
22385 bw4: usize,
22386 bh4: usize,
22387 mi_cols: usize,
22388 mi_rows: usize,
22389 ref_frame: i8, fctx: &crate::decode::FrameCtx,
22390) -> u8 {
22391 find_samples(grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame, fctx).len() as u8
22392}
22393
22394/// `av1_get_obmc_mask` (`reconinter.c`): the per-position blend weight
22395/// (`AOM_BLEND_A64` numerator, out of 64) for the neighbour's own
22396/// contribution's *complement* -- i.e. `dst = (mask*orig + (64-mask)*nbr +
22397/// 32) >> 6`, low near the shared border (heavier neighbour weight) rising
22398/// to 64 (no neighbour contribution) away from it. Only the lengths this
22399/// decoder's own overlap sizes ever produce (luma 8/16/32, chroma 4/8/16)
22400/// are transcribed.
22401fn obmc_mask(len: usize) -> &'static [u8] {
22402 // lane-gmaffine r1: the two SHORT masks (libaom `reconinter.c`
22403 // `obmc_mask_1`/`obmc_mask_2`) -- an 8x8 leaf's chroma plane is 4x4, so
22404 // its overlap is 2 (and 1 at a half-block edge). Unreachable until this
22405 // round wired interior 16x16 splits down to real 8x8 leaves, where the
22406 // old `unreachable!()` below fired as a hard panic.
22407 const M1: [u8; 1] = [64];
22408 // lane-inter8 r1: `obmc_mask_2` (`reconinter.c` 753) -- reached by the
22409 // LEFT pass of an 8x8 block's chroma plane (overlap 4 luma columns, 2
22410 // chroma), which only became live once 8x8 inter leaves stopped being
22411 // refused.
22412 const M2: [u8; 2] = [45, 64];
22413 const M4: [u8; 4] = [39, 50, 59, 64];
22414 const M8: [u8; 8] = [36, 42, 48, 53, 57, 61, 64, 64];
22415 const M16: [u8; 16] = [
22416 34, 37, 40, 43, 46, 49, 52, 54, 56, 58, 60, 61, 64, 64, 64, 64,
22417 ];
22418 const M32: [u8; 32] = [
22419 33, 35, 36, 38, 40, 41, 43, 44, 45, 47, 48, 50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 60,
22420 61, 62, 64, 64, 64, 64, 64, 64, 64, 64,
22421 ];
22422 match len {
22423 1 => &M1,
22424 2 => &M2,
22425 4 => &M4,
22426 8 => &M8,
22427 16 => &M16,
22428 32 => &M32,
22429 _ => unreachable!("obmc overlap length outside this decoder's own block-size range"),
22430 }
22431}
22432
22433/// A bordering block's own resolved interp filter kernel, `(h, v)` --
22434/// mirrors [`resolve_interp_filter`]'s own return order from its stored
22435/// `[u8; 2]` (`Neighbours::above_filter`/`left_filter`, `[sym0, sym1]` =
22436/// `[v_sym, h_sym]`). The `[3, 3]` sentinel is only ever stored for an intra
22437/// neighbour (excluded by [`overlappable_above`]/[`overlappable_left`]'s
22438/// `is_inter` gate) or when `interp_fixed` is `Some` for the whole frame
22439/// (handled here first) -- so a sentinel reaching the kernel lookup means the
22440/// stream desynced upstream, and this refuses instead of panicking.
22441fn neighbour_filter(
22442 interp_fixed: Option<mc::InterpFilterKind>,
22443 sym: [u8; 2],
22444) -> Result<(mc::InterpFilterKind, mc::InterpFilterKind)> {
22445 if let Some(kind) = interp_fixed {
22446 return Ok((kind, kind));
22447 }
22448 // lane-golomb r9: this used to hand the sentinel straight to
22449 // `from_switchable_symbol`, which PANICS on any value above 2 -- a crash
22450 // on stream data (measured on a real 192x68 cq40 aomenc stream, where an
22451 // inter leaf below 8x8 desyncs upstream and leaves an unrecorded filter
22452 // behind). A decoder must refuse such a stream by name, never abort the
22453 // process; the desync that produces the sentinel belongs to lane-intersub8.
22454 if sym[0] > 2 || sym[1] > 2 {
22455 return Err(unsupported(
22456 "an OBMC neighbour whose switchable interp filter was never recorded",
22457 ));
22458 }
22459 OBMC_FILTER_BAND_READS.with(|c| c.set(c.get() + 1));
22460 Ok((
22461 mc::InterpFilterKind::from_switchable_symbol(sym[1] as usize),
22462 mc::InterpFilterKind::from_switchable_symbol(sym[0] as usize),
22463 ))
22464}
22465
22466/// lane-obmcrec r1 MEASUREMENT rung (`EC_OBMCREC=1`): every OBMC neighbour whose
22467/// recorded switchable-filter symbols are the `[3, 3]` "never recorded" sentinel
22468/// -- names the neighbour's own position/shape/reference so the decode path that
22469/// failed to record its filter can be identified. Read-only, off by default.
22470#[allow(clippy::too_many_arguments)]
22471fn obmcrec_probe(
22472 dir: &str,
22473 mi_row: usize,
22474 mi_col: usize,
22475 write_w: usize,
22476 write_h: usize,
22477 off4: usize,
22478 span4: usize,
22479 nb: &MiInfo,
22480 syms: [u8; 2],
22481 cell: Option<MiInfo>,
22482 fixed: bool,
22483) {
22484 if (syms[0] <= 2 && syms[1] <= 2) || !crate::envflags::env_flag!("EC_OBMCREC") {
22485 return;
22486 }
22487 eprintln!(
22488 "OBMCREC {dir} cur_mi=({mi_row},{mi_col}) cur_wh=({write_w}x{write_h}) off4={off4} \
22489span4={span4} syms={syms:?} fixed={fixed} nb_size=({}x{}) nb_ref={} nb_ref1={:?} nb_mv=({},{}) \
22490nb_newmv={} cell_size={:?} cell_inter={:?} cell_ref={:?} sb_row_off={} sb_col_off={}",
22491 nb.size * 4,
22492 nb.size_h * 4,
22493 nb.ref_frame,
22494 nb.ref_frame1,
22495 nb.mv.0,
22496 nb.mv.1,
22497 nb.is_new_mv,
22498 cell.map(|c| (c.size * 4, c.size_h * 4)),
22499 cell.map(|c| c.is_inter),
22500 cell.map(|c| c.ref_frame),
22501 mi_row % 32,
22502 mi_col % 32,
22503 );
22504}
22505
22506/// One neighbour's own re-prediction over a `w`x`h` region, MC'd fresh
22507/// against its own `mv`/reference/filter (libaom `av1_build_inter_predictor`
22508/// under `av1_setup_build_prediction_by_{above,left}_pred`).
22509#[allow(clippy::too_many_arguments)]
22510fn obmc_neighbour_pred(
22511 refplane: &PlaneBuf<'_>,
22512 x: usize,
22513 y: usize,
22514 mv: (i32, i32),
22515 w: usize,
22516 h: usize,
22517 luma: bool,
22518 h_kind: mc::InterpFilterKind,
22519 v_kind: mc::InterpFilterKind,
22520 // lane-scaledref r1: spec 7.11.3.3's x_scale_fp for THIS neighbour's own
22521 // reference (derived from luma widths, applied unchanged to chroma whose
22522 // x_q4 is already in its own plane's pixel units). `REF_NO_SCALE` takes
22523 // the ordinary stride-1 path bit-exact.
22524 x_scale_fp: i64,
22525 // lane-alloc: the caller keeps one buffer per plane and reuses it across
22526 // every neighbour of both passes -- this was a fresh `vec![0u16; w * h]`
22527 // per neighbour per plane.
22528 out: &mut Vec<u16>,
22529 fctx: &crate::decode::FrameCtx,
22530) {
22531 out.clear();
22532 out.resize(w * h, 0);
22533 if x_scale_fp == mc::REF_NO_SCALE {
22534 mc::predict_with_filters(
22535 &refplane.data,
22536 refplane.width,
22537 refplane.true_width,
22538 refplane.true_height,
22539 mv_to_q4(x, mv.1, luma),
22540 mv_to_q4(y, mv.0, luma),
22541 w,
22542 h,
22543 h_kind,
22544 v_kind,
22545 out, fctx,
22546 );
22547 } else {
22548 mc::predict_scaled(
22549 &refplane.data,
22550 refplane.width,
22551 refplane.true_width,
22552 refplane.true_height,
22553 mv_to_q4(x, mv.1, luma),
22554 mv_to_q4(y, mv.0, luma),
22555 x_scale_fp,
22556 w,
22557 h,
22558 h_kind,
22559 v_kind,
22560 out, fctx,
22561 );
22562 }
22563}
22564
22565/// Blends `tmp` into `dst` (stride `stride`) at `(ox, oy)`, mask varying by
22566/// row (the above-neighbour pass, `aom_blend_a64_vmask`).
22567/// `ii_weights1d` (reconinter.c:524): the interintra smooth-mask falloff.
22568const II_WEIGHTS_1D: [u8; 128] = [
22569 60, 58, 56, 54, 52, 50, 48, 47, 45, 44, 42, 41, 39, 38, 37, 35, 34, 33, 32,
22570 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 22, 21, 20, 19, 19, 18, 18, 17, 16,
22571 16, 15, 15, 14, 14, 13, 13, 12, 12, 12, 11, 11, 10, 10, 10, 9, 9, 9, 8,
22572 8, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4,
22573 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2,
22574 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1,
22575 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
22576];
22577
22578/// lane-interintra r1: non-wedge interintra prediction for one plane
22579/// (reconinter.c `av1_build_interintra_predictor` + `combine_interintra` +
22580/// `build_smooth_interintra_mask`). Builds the intra predictor for the
22581/// block's II mode (DC/V/H/SMOOTH, angle 0, no filter-intra) from `plane`'s
22582/// own decoded edges at `(x, y)`, then blends it over the inter prediction
22583/// in `pred`: `comp = (mask*intra + (64-mask)*inter + 32) >> 6`
22584/// (`aom_blend_a64_mask`, intra as src0). `ii_size_scales[plane_bsize]`
22585/// reduces to `128 / side` for the square plane sizes this decoder reaches.
22586/// lane-wii r2: `wedge == Some(..)` replaces the mode mask with the wedge
22587/// codebook mask (fixed sign 0; luma stride, 2x2 box-averaged for chroma).
22588fn interintra_blend(
22589 plane: &PlaneBuf<'_>,
22590 x: usize,
22591 y: usize,
22592 bw: usize,
22593 bh: usize,
22594 stride: usize,
22595 ii_mode: u8,
22596 wedge: Option<(&'static [u8], usize)>,
22597 pred: &mut [u16], fctx: &crate::decode::FrameCtx,
22598) {
22599 // `interintra_to_intra_mode`: II_DC/II_V/II_H/II_SMOOTH.
22600 let intra_mode = match ii_mode {
22601 0 => crate::intra::DC_PRED,
22602 1 => crate::intra::V_PRED,
22603 2 => crate::intra::H_PRED,
22604 _ => crate::intra::SMOOTH_PRED,
22605 };
22606 let (above, left, corner) = plane.edges_rect(
22607 x,
22608 y,
22609 bw,
22610 bh,
22611 crate::encode::Reach {
22612 above_right: false,
22613 below_left: false,
22614 },
22615 );
22616 let mut intra = vec![0u16; bw * bh];
22617 // Edge filtering never applies here: V/H at delta 0 are plain edge
22618 // copies (angle 90/180 skip the directional walk), DC/SMOOTH carry no
22619 // angle at all.
22620 predict(
22621 intra_mode,
22622 0,
22623 above.as_deref(),
22624 left.as_deref(),
22625 corner,
22626 bw,
22627 bh,
22628 false,
22629 false,
22630 &mut intra, fctx,
22631 );
22632 // `ii_size_scales[bsize]` is keyed on the block's LONGER side
22633 // (`MAX_SB_SIZE >> max(bw,bh)` order), not on the square this decoder
22634 // builds the predictor buffer at.
22635 let scale = 128 / bw.max(bh);
22636 for i in 0..bh {
22637 for j in 0..bw {
22638 let m = u32::from(match wedge {
22639 // lane-wii r2: wedge-interintra mask (aom_blend_a64_mask
22640 // over the wedge codebook, intra as src0, fixed sign 0).
22641 // Luma plane: mask rows are luma-resolution, ms == side.
22642 // 4:2:0 chroma: 2x2 box average (reconinter.c sub8x8 --
22643 // subw == subh == 1).
22644 Some((mask, ms)) if ms == stride => mask[i * stride + j],
22645 Some((mask, ms)) => {
22646 let t = 2 * i * ms + 2 * j;
22647 ((u32::from(mask[t])
22648 + u32::from(mask[t + 1])
22649 + u32::from(mask[t + ms])
22650 + u32::from(mask[t + ms + 1])
22651 + 2)
22652 >> 2) as u8
22653 }
22654 None => match ii_mode {
22655 0 => 32,
22656 1 => II_WEIGHTS_1D[i * scale],
22657 2 => II_WEIGHTS_1D[j * scale],
22658 _ => II_WEIGHTS_1D[i.min(j) * scale],
22659 },
22660 });
22661 let idx = i * stride + j;
22662 pred[idx] = ((m * u32::from(intra[i * bw + j]) + (64 - m) * u32::from(pred[idx]) + 32)
22663 >> 6) as u16;
22664 }
22665 }
22666}
22667
22668/// `w` is the number of columns actually written (clipped to the block's own
22669/// buffer at a frame edge); `ts` is `tmp`'s own stride, the neighbour
22670/// prediction's full width.
22671#[allow(clippy::too_many_arguments)]
22672fn obmc_blend_v(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, ts: usize, tmp: &[u16]) {
22673 let mask = obmc_mask(h);
22674 for row in 0..h {
22675 let m = u32::from(mask[row]);
22676 for col in 0..w {
22677 let d = &mut dst[(oy + row) * stride + ox + col];
22678 let t = u32::from(tmp[row * ts + col]);
22679 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
22680 }
22681 }
22682}
22683
22684/// Blends `tmp` into `dst` at `(ox, oy)`, mask varying by column (the
22685/// left-neighbour pass, `aom_blend_a64_hmask`).
22686fn obmc_blend_h(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u16]) {
22687 let mask = obmc_mask(w);
22688 for row in 0..h {
22689 for col in 0..w {
22690 let m = u32::from(mask[col]);
22691 let d = &mut dst[(oy + row) * stride + ox + col];
22692 let t = u32::from(tmp[row * w + col]);
22693 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
22694 }
22695 }
22696}
22697
22698/// libaom's own `BLOCK_SIZE` enum index for a `w4`x`h4` (mi-unit) block --
22699/// only for the `EC_OBMC` trace rung below, so it reads byte-identical to
22700/// the instrumented aomdec's `backup_mbmi.bsize`.
22701fn ec_obmc_bsize(w4: usize, h4: usize) -> i32 {
22702 match (w4, h4) {
22703 (1, 1) => 0,
22704 (1, 2) => 1,
22705 (2, 1) => 2,
22706 (2, 2) => 3,
22707 (2, 4) => 4,
22708 (4, 2) => 5,
22709 (4, 4) => 6,
22710 (4, 8) => 7,
22711 (8, 4) => 8,
22712 (8, 8) => 9,
22713 (8, 16) => 10,
22714 (16, 8) => 11,
22715 (16, 16) => 12,
22716 (1, 4) => 16,
22717 (4, 1) => 17,
22718 (2, 8) => 18,
22719 (8, 2) => 19,
22720 (4, 16) => 20,
22721 (16, 4) => 21,
22722 _ => -1,
22723 }
22724}
22725
22726/// The `EC_OBMC` rung: one line per blended neighbour, in the instrumented
22727/// aomdec's own byte format (`decodeframe.c`
22728/// `dec_build_prediction_by_{above,left}_pred`), so the two decoders' OBMC
22729/// neighbour lists diff line for line. `filt` is libaom's packed
22730/// `interp_filters.as_int` = `y_filter | (x_filter << 16)`.
22731#[allow(clippy::too_many_arguments)]
22732fn ec_obmc_trace(
22733 dir: &str,
22734 mi_row: usize,
22735 mi_col: usize,
22736 write_w: usize,
22737 write_h: usize,
22738 rel: usize,
22739 op: usize,
22740 nb: &MiInfo,
22741 h_kind: mc::InterpFilterKind,
22742 v_kind: mc::InterpFilterKind,
22743) {
22744 if !crate::envflags::env_flag!("EC_OBMC") {
22745 return;
22746 }
22747 let sym = |k: mc::InterpFilterKind| match k {
22748 mc::InterpFilterKind::Smooth => 1u32,
22749 mc::InterpFilterKind::Sharp => 2,
22750 _ => 0,
22751 };
22752 eprintln!(
22753 "EC_OBMC {dir} mi=({mi_row},{mi_col}) wh=({write_w}x{write_h}) rel={rel} op={op} \
22754nbmv=({},{}) nbref={} nbbsize={} filt={}",
22755 nb.mv.0,
22756 nb.mv.1,
22757 nb.ref_frame,
22758 ec_obmc_bsize(nb.size as usize, nb.size_h as usize),
22759 sym(v_kind) | (sym(h_kind) << 16),
22760 );
22761}
22762
22763/// `av1_build_obmc_inter_prediction` (libaom `reconinter.c`): re-predicts
22764/// the overlap strip against each bordering above/left inter neighbour's own
22765/// mv/ref/filter and blends it into this block's just-built single-reference
22766/// prediction, luma then both 4:2:0 chroma planes -- above pass first, then
22767/// left, each reading only the *original* prediction this function was
22768/// handed (never the other pass's own output), matching libaom's own
22769/// independence between the two. `max_neighbor_obmc`'s own cap table
22770/// (`{0,1,2,3,4,4}` indexed by `mi_size_wide_log2`/`_high_log2`, this
22771/// decoder's own square blocks always index the same value both ways) bounds
22772/// how many bordering blocks actually get blended, separate from the
22773/// eligibility scan's own unbounded ("any at all") walk.
22774#[allow(clippy::too_many_arguments)]
22775fn obmc_blend(
22776 grid: &MiGrid,
22777 neighbours: &Neighbours,
22778 mi_row: usize,
22779 mi_col: usize,
22780 bw4: usize,
22781 bh4: usize,
22782 mi_rows: usize,
22783 mi_cols: usize,
22784 side: usize,
22785 write_w: usize,
22786 write_h: usize,
22787 chroma_side: usize,
22788 px: usize,
22789 py: usize,
22790 cpx: usize,
22791 cpy: usize,
22792 ref_y: &PlaneBuf<'_>,
22793 ref_u: &PlaneBuf<'_>,
22794 ref_v: &PlaneBuf<'_>,
22795 other_refs: &RefSlots,
22796 interp_fixed: Option<mc::InterpFilterKind>,
22797 // lane-scaledref r1: this frame's own coded luma width -- each OBMC
22798 // neighbour is re-predicted against ITS OWN reference, which may be
22799 // scaled differently from this block's (spec 7.11.3.3 / libaom
22800 // `av1_setup_build_prediction_by_above_pred` passing that ref's own
22801 // `scale_factors`).
22802 frame_width: usize,
22803 pred_y: &mut [u16],
22804 pred_u: &mut [u16],
22805 pred_v: &mut [u16], fctx: &crate::decode::FrameCtx,
22806) -> Result<()> {
22807 // lane-rect r2 (libaom av1_build_obmc_inter_prediction): each pass has
22808 // its OWN neighbour cap (width-log2 for above, height-log2 for left) and
22809 // overlap (bh/2 rows above, bw/2 cols left) -- one square `side` was
22810 // right only for square blocks.
22811 // libaom `max_neighbor_obmc[6] = { 0, 1, 2, 3, 4, 4 }` indexed by
22812 // `mi_size_wide_log2[bsize]` (above pass) / `mi_size_high_log2` (left):
22813 // 1 mi -> 0, 2 -> 1, 4 -> 2, 8 -> 3, 16+ -> 4. lane-inter4 r3: the old
22814 // `1..=4 => 2` row was right only for blocks at least 16 px on that axis
22815 // -- a 16x8 leaf's LEFT pass (bh4 = 2) walked up to two neighbours where
22816 // libaom walks one, blending an extra 8-px-tall neighbour into every
22817 // rect leaf with two of them on its left edge (class table-narrowed-to-
22818 // the-reachable-sizes; the square gates could never expose it).
22819 let max_nb = |n4: usize| match n4 {
22820 0..=1 => 0,
22821 2 => 1,
22822 3..=4 => 2,
22823 5..=8 => 3,
22824 _ => 4,
22825 };
22826 // lane-inter4 r4: r3 refused OBMC on a 16x8/8x16 leaf (5302 luma pixels
22827 // of one frame wrong). Re-measured on this tree with an `EC_OBMC` rung in
22828 // both decoders on that exact stream: the neighbour lists agree entry for
22829 // entry (position, span, mv, ref, size, filter) and all six pre-filter
22830 // frames are byte-identical to the instrumented aomdec's. The refusal is
22831 // gone; the counter below is what the gate's `--enable-obmc=1` arm reads.
22832 // The only decode-path change between r3's measurement and this one is the
22833 // lane-interbis merge (`build_motion_field`'s compound slot walk), which
22834 // moves temporal MV candidates -- not bisected further.
22835 if matches!((write_w, write_h), (16, 8) | (8, 16)) {
22836 OBMC_RECT_LEAF_HITS.with(|c| c.set(c.get() + 1));
22837 }
22838 // lane-sb128c r1: libaom caps the overlap strip at a 64x64 block's own
22839 // half (`reconinter.c` 860/899: `AOMMIN(block_size_high[bsize],
22840 // block_size_high[BLOCK_64X64]) >> 1`, and the `block_size_wide` mirror) --
22841 // inert below 128, where a 128x128 block would otherwise blend a 64-row
22842 // strip `obmc_mask` has no table for.
22843 let overlap_above = write_h.min(64) / 2;
22844 let overlap_left = write_w.min(64) / 2;
22845 // lane-inter8 r1 / lane-scaledref r1: `av1_skip_u4x4_pred_in_obmc`
22846 // (`reconinter.c` 820, `DISABLE_CHROMA_U8X8_OBMC == 0` -- "one-sided
22847 // obmc") returns `dir == 0` when the chroma plane's own block is
22848 // BLOCK_4X4/8X4/4X8 (an 8x8, 16x8 or 8x16 luma block at 4:2:0): the
22849 // ABOVE pass skips chroma entirely, the LEFT pass still blends it.
22850 let skip_chroma_above = matches!((write_w, write_h), (8, 8) | (16, 8) | (8, 16));
22851 // lane-alloc: one neighbour-prediction buffer per plane for the whole
22852 // block, reused by every neighbour of the above and left passes.
22853 let (mut tmp_y, mut tmp_u, mut tmp_v) = (Vec::new(), Vec::new(), Vec::new());
22854
22855 // lane-t900 r13 rung: EC_MCB="<plane>:<px>:<py>[:<frame>]" (chroma plane
22856 // 1 only) prints this block's chroma prediction rows before and after the
22857 // OBMC blend, matching the instrumented aomdec's EC_MCB dump.
22858 let ec_mcb: Option<(usize, usize, i64)> = crate::envflags::env_flag!("EC_MCB")
22859 .then(|| crate::envflags::var("EC_MCB").ok())
22860 .flatten()
22861 .and_then(|v| {
22862 let f: Vec<&str> = v.split(':').collect();
22863 if f.len() < 3 || f[0] != "1" {
22864 return None;
22865 }
22866 let (x, y) = (f[1].parse::<usize>().ok()?, f[2].parse::<usize>().ok()?);
22867 let fr = f.get(3).and_then(|s| s.parse::<i64>().ok()).unwrap_or(-1);
22868 let idx = PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst) as i64;
22869 if x >= cpx && x < cpx + write_w / 2 && y >= cpy && y < cpy + write_h / 2
22870 && (fr < 0 || fr == idx)
22871 {
22872 Some((x, y, idx))
22873 } else {
22874 None
22875 }
22876 });
22877 if let Some((_, _, idx)) = ec_mcb {
22878 eprintln!(
22879 "OUR_MCB pre f={idx} cpx={cpx} cpy={cpy} cw={} ch={}",
22880 write_w / 2,
22881 write_h / 2
22882 );
22883 for r in 0..write_h / 2 {
22884 let row: Vec<u16> = (0..write_w / 2).map(|c| pred_u[r * chroma_side + c]).collect();
22885 eprintln!("OUR_MCB prerow{r}: {row:?}");
22886 }
22887 }
22888 for (off4, span4, nb, src4) in overlappable_above(grid, mi_row, mi_col, bw4, mi_cols, max_nb(bw4))
22889 {
22890 // `Neighbours::above_filter` is indexed in `SUB`(16px)-wide columns
22891 // (this decoder's own outer block-loop granularity), one step
22892 // coarser than the mi(4px) units `overlappable_above` walks in --
22893 // divide back down to that column.
22894 // lane-gmaffine r2: the neighbour's OWN mi-granular filter
22895 // (libaom `av1_setup_build_prediction_by_above_pred` reads
22896 // `above_mbmi->interp_filters`); the 16px-granular `Neighbours` slot
22897 // stays as the fallback for paths that do not record one yet
22898 // (compound), which is what every earlier round used.
22899 let above_syms = neighbours.above_filter[mi_col + src4];
22900 obmcrec_probe(
22901 "above", mi_row, mi_col, write_w, write_h, off4, span4, &nb, above_syms,
22902 grid.get(mi_row - 1, mi_col + src4).copied(), interp_fixed.is_some(),
22903 );
22904 let (h_kind, v_kind) = neighbour_filter(interp_fixed, above_syms)?;
22905 ec_obmc_trace("above", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind);
22906 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
22907 let nb_scale = mc::scale_factor(ny.width, frame_width);
22908 if mi_col + off4 + span4 > mi_cols {
22909 OBMC_EDGE_SPAN_HITS.with(|c| c.set(c.get() + 1));
22910 }
22911 let (bw, bh, ox) = (span4 * 4, overlap_above, off4 * 4);
22912 // lane-t900 r14: the prediction is `op_mi_size` wide (kernel choice
22913 // included); only the WRITE is clipped to this block's own buffer.
22914 obmc_neighbour_pred(ny, px + ox, py, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale, &mut tmp_y, fctx);
22915 obmc_blend_v(pred_y, side, ox, 0, bw.min(write_w - ox), bh, bw, &tmp_y);
22916 if !skip_chroma_above {
22917 // lane-t900 r13 (measured, NOT a defect): libaom's min-4 clamp
22918 // (`dec_build_prediction_by_above_pred`) sizes only the OBMC
22919 // PREDICTION buffer; the blend length is the plain half
22920 // (`build_obmc_inter_pred_above`: `overlap >> ss_y`), so flooring
22921 // this at 4 blends rows libaom never blends -- on a 10-bit
22922 // 1920x792 cut that went 36 differing frames -> 266, worst
22923 // 13 B -> 11007 B.
22924 let (cbw, cbh, cox) = (bw / 2, overlap_above / 2, ox / 2);
22925 let cw = cbw.min(write_w / 2 - cox);
22926 obmc_neighbour_pred(nu, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale, &mut tmp_u, fctx);
22927 obmc_blend_v(pred_u, chroma_side, cox, 0, cw, cbh, cbw, &tmp_u);
22928 obmc_neighbour_pred(nv, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale, &mut tmp_v, fctx);
22929 obmc_blend_v(pred_v, chroma_side, cox, 0, cw, cbh, cbw, &tmp_v);
22930 }
22931 }
22932
22933 for (off4, span4, nb, src4) in overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, max_nb(bh4))
22934 {
22935 let left_syms = neighbours.left_filter[mi_row + src4];
22936 obmcrec_probe(
22937 "left", mi_row, mi_col, write_w, write_h, off4, span4, &nb, left_syms,
22938 grid.get(mi_row + src4, mi_col - 1).copied(), interp_fixed.is_some(),
22939 );
22940 let (h_kind, v_kind) = neighbour_filter(interp_fixed, left_syms)?;
22941 ec_obmc_trace("left", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind);
22942 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
22943 let nb_scale = mc::scale_factor(ny.width, frame_width);
22944 if mi_row + off4 + span4 > mi_rows {
22945 OBMC_EDGE_SPAN_HITS.with(|c| c.set(c.get() + 1));
22946 }
22947 let (bw, bh, oy) = (overlap_left, span4 * 4, off4 * 4);
22948 obmc_neighbour_pred(ny, px, py + oy, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale, &mut tmp_y, fctx);
22949 obmc_blend_h(pred_y, side, 0, oy, bw, bh.min(write_h - oy), &tmp_y);
22950 let (cbw, cbh, coy) = (overlap_left / 2, bh / 2, oy / 2);
22951 obmc_neighbour_pred(nu, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale, &mut tmp_u, fctx);
22952 if let Some((_, _, idx)) = ec_mcb {
22953 eprintln!(
22954 "OUR_MCB left f={idx} off4={off4} span4={span4} cbw={cbw} cbh={cbh} coy={coy} mv=({},{}) ref0={}",
22955 nb.mv.0, nb.mv.1, nb.ref_frame
22956 );
22957 for r in 0..cbh {
22958 let row: Vec<u16> = (0..cbw).map(|c| tmp_u[r * cbw + c]).collect();
22959 eprintln!("OUR_MCB lrow{r}: {row:?}");
22960 }
22961 }
22962 let ch = cbh.min(write_h / 2 - coy);
22963 obmc_blend_h(pred_u, chroma_side, 0, coy, cbw, ch, &tmp_u);
22964 obmc_neighbour_pred(nv, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale, &mut tmp_v, fctx);
22965 obmc_blend_h(pred_v, chroma_side, 0, coy, cbw, ch, &tmp_v);
22966 }
22967 if let Some((_, _, idx)) = ec_mcb {
22968 for r in 0..write_h / 2 {
22969 let row: Vec<u16> = (0..write_w / 2).map(|c| pred_u[r * chroma_side + c]).collect();
22970 eprintln!("OUR_MCB post f={idx} row{r}: {row:?}");
22971 }
22972 }
22973 Ok(())
22974}
22975
22976/// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to
22977/// the square block sizes this decoder ever decodes (32/16/8, all
22978/// `min(w,h) >= 8`, `is_comp_ref_allowed` true): `COMPOUND_DIFFWTD` is then
22979/// always `is_interinter_compound_used`, so the function is always `true`
22980/// for `side` -- kept as a named call (rather than inlined `true`) so a
22981/// future sub-8 block size does not silently misdecode a real stream.
22982fn is_any_masked_compound_used_here(bw: usize, bh: usize) -> bool {
22983 // lane-inter16ab r4 (class sweep of the r3 CDF-row defect):
22984 // `is_comp_ref_allowed(bsize)` is `AOMMIN(block_size_wide, block_size_high)
22985 // >= 8` on the block's TRUE footprint -- a 16x4/4x16 strip is NOT allowed,
22986 // so libaom writes no `comp_group_idx` symbol there at all. Keyed off the
22987 // square `side` we read one the reference never wrote.
22988 bw.min(bh) >= 8
22989}
22990
22991/// The `BLOCK_SIZES_ALL` index of a `bw x bh` block (libaom `enum BLOCK_SIZE`,
22992/// `blockd.h`) -- the row every size-indexed inter CDF table
22993/// (`compound_type_cdf`, `wedge_idx_cdf`) is keyed by. Our `decode_inter_block`
22994/// carries the enclosing SQUARE `side` for context purposes (the accepted
22995/// strip corner-cut), so a 16x8 / 8x16 PARTITION_HORZ/VERT strip that reads
22996/// one of those symbols off `side` alone takes BLOCK_16X16's row and desyncs
22997/// (lane-inter16ab r3: a real 16x8 compound strip with `comp_group_idx == 1`,
22998/// decode-order frame 5, our range 64901 vs the oracle's 47271 at the very
22999/// next block's mode read).
23000fn bsize_all_index(bw: usize, bh: usize) -> Option<usize> {
23001 Some(match (bw, bh) {
23002 (4, 4) => 0,
23003 (4, 8) => 1,
23004 (8, 4) => 2,
23005 (8, 8) => 3,
23006 (8, 16) => 4,
23007 (16, 8) => 5,
23008 (16, 16) => 6,
23009 (16, 32) => 7,
23010 (32, 16) => 8,
23011 (32, 32) => 9,
23012 (32, 64) => 10,
23013 (64, 32) => 11,
23014 (64, 64) => 12,
23015 (64, 128) => 13,
23016 (128, 64) => 14,
23017 (128, 128) => 15,
23018 (4, 16) => 16,
23019 (16, 4) => 17,
23020 (8, 32) => 18,
23021 (32, 8) => 19,
23022 (16, 64) => 20,
23023 (64, 16) => 21,
23024 _ => return None,
23025 })
23026}
23027
23028/// `av1_wedge_params_lookup[bsize].wedge_types > 0` (libaom `reconinter.c`):
23029/// the block sizes that carry a wedge codebook at all. A `compound_type`
23030/// symbol is written only for these; every other size infers
23031/// `COMPOUND_DIFFWTD`.
23032fn wedge_used_bsize(bw: usize, bh: usize) -> bool {
23033 matches!(
23034 (bw, bh),
23035 (8, 8) | (8, 16) | (16, 8) | (16, 16) | (16, 32) | (32, 16) | (32, 32) | (8, 32) | (32, 8)
23036 )
23037}
23038
23039
23040
23041
23042/// Whether a compound reference pair is unidirectional (both references on
23043/// the same temporal side of the current frame) -- `has_uni_comp_refs`
23044/// (libaom `av1_reference_frame_utils.h`/`pred_common.c`'s own definition:
23045/// a pair is `UNIDIR_COMP_REFERENCE` exactly when neither reference is
23046/// backward-while-the-other-is-forward, i.e. `is_backward(ref0) ==
23047/// is_backward(ref1)`). Used to build a real
23048/// [`crate::mvstack::NeighbourRef::uni`] once `ref1` is known, matching
23049/// [`crate::mvstack::comp_reference_type_ctx`]'s own `is_backward` calls.
23050fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool {
23051 let backward = |r: i8| (BWDREF_FRAME..=ALTREF_FRAME).contains(&r);
23052 backward(ref0) == backward(ref1)
23053}
23054
23055/// `get_comp_group_idx_context` (libaom `pred_common.h`): sums the
23056/// above/left neighbour contributions [`Neighbours::record_inter`]/
23057/// [`Neighbours::record_compound_ctx`] already precomputed, clamped to 5.
23058/// lane-inter8 r2: `at_mi` is the block's own top-left in 4x4 mi units --
23059/// an 8x8 leaf used to pass its enclosing 16x16's corner here, so all four
23060/// leaves read the same neighbour cell (class context-read-from-one-cell).
23061fn get_comp_group_idx_context(
23062 neighbours: &Neighbours,
23063 at_mi: (usize, usize),
23064 side: usize,
23065) -> usize {
23066 let _ = side;
23067 let (rmi, cmi) = at_mi;
23068 (neighbours.above_comp_group_idx[cmi] as usize + neighbours.left_comp_group_idx[rmi] as usize)
23069 .min(5)
23070}
23071
23072/// `get_comp_index_context` (libaom `pred_common.h`): the above/left
23073/// neighbour bits plus `3 * (fwd == bck)`, where `fwd`/`bck` are this
23074/// block's own two references' distances from the current frame (spec
23075/// 7.11.3.15's `get_relative_dist`, same convention
23076/// [`crate::compound::dist_wtd_comp_weight_assign`] uses).
23077#[allow(clippy::too_many_arguments)]
23078fn get_comp_index_context(
23079 neighbours: &Neighbours,
23080 at_mi: (usize, usize),
23081 side: usize,
23082 order_hint_bits: u32,
23083 cur_order_hint: u32,
23084 ref0_order_hint: u32,
23085 ref1_order_hint: u32,
23086) -> usize {
23087 let _ = side;
23088 let (rmi, cmi) = at_mi;
23089 let fwd =
23090 crate::motion_field::get_relative_dist(order_hint_bits, ref1_order_hint, cur_order_hint)
23091 .abs();
23092 let bck =
23093 crate::motion_field::get_relative_dist(order_hint_bits, cur_order_hint, ref0_order_hint)
23094 .abs();
23095 let offset = usize::from(fwd == bck);
23096 neighbours.above_compound_idx[cmi] as usize
23097 + neighbours.left_compound_idx[rmi] as usize
23098 + 3 * offset
23099}
23100
23101fn read_comp_mode(
23102 dec: &mut SymbolDecoder,
23103 cdfs: &mut Cdfs,
23104 above: Option<NeighbourRef>,
23105 left: Option<NeighbourRef>,
23106) -> bool {
23107 let ctx = reference_mode_ctx(above, left);
23108 let compound = dec.symbol(&mut cdfs.comp_mode[ctx]) == 1;
23109 if compound {
23110 COMP_MODE_HITS.with(|c| c.set(c.get() + 1));
23111 }
23112 compound
23113}
23114
23115/// Spec 5.11.25's `comp_reference_type` + the `uni_comp_ref`/`comp_ref`/
23116/// `comp_bwdref` trees (libaom `decodemv.c`'s `read_ref_frames` compound
23117/// arm), reached once [`read_comp_mode`] has already returned
23118/// `COMPOUND_REFERENCE`. Returns `(RefFrame[0], RefFrame[1])`.
23119/// `above`/`left` are [`comp_reference_type_ctx`]'s own `NeighbourRef`
23120/// convention; `above_ref`/`left_ref` are the scalar `1..=7`/`-1`
23121/// convention [`read_single_ref`] already uses, for every downstream binary
23122/// decision. libaom `pred_common.c`'s own compound context functions
23123/// (`av1_get_pred_context_uni_comp_ref_p[1|2]`, `comp_ref_p[1|2]`,
23124/// `comp_bwdref_p[1]`) turned out to be exactly [`single_ref_p1_ctx`]..
23125/// [`single_ref_p6_ctx`]/[`uni_comp_ref_p1_ctx`] under a different name
23126/// (same vote-the-neighbours-above-left shape, same forward/backward and
23127/// LAST/LAST2/LAST3/GOLDEN groupings) -- lane-av1comp audited each one
23128/// against the C source rather than porting six near-duplicate functions.
23129/// Its caller today only needs the symbols consumed, correctly, to keep the
23130/// arithmetic decoder's own state in sync before refusing the block by name
23131/// -- the returned pair is not yet threaded into any motion-compensation
23132/// path.
23133fn read_compound_ref_frames(
23134 dec: &mut SymbolDecoder,
23135 cdfs: &mut Cdfs,
23136 above: Option<NeighbourRef>,
23137 left: Option<NeighbourRef>,
23138 above_ref: i8,
23139 left_ref: i8,
23140) -> (i8, i8) {
23141 let a = (above_ref > 0).then_some(above_ref);
23142 let l = (left_ref > 0).then_some(left_ref);
23143 // libaom `av1_collect_neighbors_ref_counts` counts BOTH of a compound
23144 // neighbour's references, not just its first -- `a1`/`l1` carry that
23145 // second reference through to every vote below (lane-av1blend r6: a
23146 // missing `a1`/`l1` here was decoding `compound_idx` off the wrong CDF
23147 // row for a block sitting under a skip_mode-forced compound neighbour).
23148 let a1 = above.and_then(|n| n.ref1);
23149 let l1 = left.and_then(|n| n.ref1);
23150 let type_ctx = comp_reference_type_ctx(above, left);
23151 let unidir = dec.symbol(&mut cdfs.comp_ref_type[type_ctx]) == 0;
23152 if unidir {
23153 UNI_COMP_HITS.with(|c| c.set(c.get() + 1));
23154 // uni_comp_ref (p0): forward vs. backward -- av1_get_pred_context_-
23155 // uni_comp_ref_p is single_ref_p1's own forward/backward vote.
23156 let bit = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0]);
23157 if bit == 1 {
23158 (BWDREF_FRAME, ALTREF_FRAME)
23159 } else {
23160 let p1 = dec.symbol(&mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1]);
23161 if p1 == 1 {
23162 // uni_comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
23163 let p2 = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
23164 if p2 == 1 {
23165 (LAST_FRAME, GOLDEN_FRAME)
23166 } else {
23167 (LAST_FRAME, LAST3_FRAME)
23168 }
23169 } else {
23170 (LAST_FRAME, LAST2_FRAME)
23171 }
23172 }
23173 } else {
23174 // comp_ref (p0): LAST/LAST2 vs. LAST3/GOLDEN, same vote as single_ref_p3.
23175 let bit0 = dec.symbol(&mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0]);
23176 let ref0 = if bit0 == 0 {
23177 // comp_ref_p1: LAST vs. LAST2, same vote as single_ref_p4.
23178 let p1 = dec.symbol(&mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1]);
23179 if p1 == 1 { LAST2_FRAME } else { LAST_FRAME }
23180 } else {
23181 // comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
23182 let p2 = dec.symbol(&mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
23183 if p2 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
23184 };
23185 // comp_bwdref (p0): BWDREF/ALTREF2 vs. ALTREF, same vote as single_ref_p2.
23186 let bit1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0]);
23187 let ref1 = if bit1 == 0 {
23188 // comp_bwdref_p1: BWDREF vs. ALTREF2, same vote as single_ref_p6.
23189 let p1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1]);
23190 if p1 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
23191 } else {
23192 ALTREF_FRAME
23193 };
23194 (ref0, ref1)
23195 }
23196}
23197
23198/// Spec 5.11.24's `compound_mode` (lane-av1comp): which of the eight
23199/// `INTER_COMPOUND_MODES` (`NEAREST_NEARESTMV`..`NEW_NEWMV`, returned as
23200/// `0..=7`) a `COMPOUND_REFERENCE` block takes, reached once
23201/// [`read_comp_mode`] has already returned `COMPOUND_REFERENCE`. `ctx` is
23202/// libaom's `av1_mode_context_analyzer`'s compound branch --
23203/// `compound_mode_ctx_map[ref_mv_ctx >> 1][min(new_mv_ctx, COMP_NEWMV_CTXS
23204/// - 1)]` (`mvref_common.h`) -- folded from [`crate::mvstack::
23205/// find_mv_stack_compound`]'s own `new_mv_ctx`/`ref_mv_ctx`. The read symbol
23206/// is not yet turned into an assigned MV pair or motion-compensated --
23207/// lane-av1comp.
23208fn read_inter_compound_mode(
23209 dec: &mut SymbolDecoder,
23210 cdfs: &mut Cdfs,
23211 new_mv_ctx: usize,
23212 ref_mv_ctx: usize,
23213) -> u8 {
23214 let ctx = cdf::COMPOUND_MODE_CTX_MAP[ref_mv_ctx >> 1][new_mv_ctx.min(4)];
23215 COMPOUND_MODE_HITS.with(|c| c.set(c.get() + 1));
23216 dec.symbol(&mut cdfs.inter_compound_mode[ctx]) as u8
23217}
23218
23219/// spec 7.10.2.10 `assign_mv`'s compound branch, plus the compound half of
23220/// `read_drl_idx` (spec 5.11.24) it depends on -- `mode` is
23221/// [`read_inter_compound_mode`]'s own `0..=7` (`NEAREST_NEARESTMV`..
23222/// `NEW_NEWMV`, libaom `enums.h` order). Every `GLOBAL_GLOBALMV` side reads
23223/// as `(0, 0)` since [`crate::stream::decode_stream`] already refuses any
23224/// non-`IDENTITY` global motion model before a tile is ever decoded.
23225///
23226/// Ported straight from libaom `decodemv.c`'s `read_drl_idx` (the
23227/// `NEW_NEWMV`/`have_nearmv_in_inter_mode` branches) and `assign_mv`/its
23228/// caller's `ref_mv[]`/`nearmv[]` setup: the `NEAR_NEWMV`/`NEW_NEARMV`
23229/// `1 + ref_mv_idx` special case is folded into `new_idx` below, matching
23230/// `read_drl_idx`'s own comment about "offsetting the NEARESTMV mode".
23231fn assign_compound_mv(
23232 dec: &mut SymbolDecoder,
23233 cdfs: &mut Cdfs,
23234 comp_stack: &crate::mvstack::CompoundMvStack,
23235 mode: u8,
23236 allow_high_precision_mv: bool,
23237 force_integer_mv: bool,
23238 // lane-gm r2: `gm_get_motion_vector(ref0)`/`(ref1)` at this block's own
23239 // position, spec 7.10.2.10's `GLOBAL_GLOBALMV` assignment.
23240 global_mv: ((i32, i32), (i32, i32)),
23241) -> ((i32, i32), (i32, i32)) {
23242 const NEAREST_NEARESTMV: u8 = 0;
23243 const NEAR_NEARMV: u8 = 1;
23244 const NEAREST_NEWMV: u8 = 2;
23245 const NEW_NEARESTMV: u8 = 3;
23246 const NEAR_NEWMV: u8 = 4;
23247 const NEW_NEARMV: u8 = 5;
23248 const GLOBAL_GLOBALMV: u8 = 6;
23249 const NEW_NEWMV: u8 = 7;
23250
23251 let mut ref_mv_idx = 0usize;
23252 if mode == NEW_NEWMV {
23253 let mut idx = 0usize;
23254 while idx < 2 && comp_stack.entries.len() > idx + 1 {
23255 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
23256 break;
23257 }
23258 idx += 1;
23259 }
23260 ref_mv_idx = idx;
23261 } else if matches!(mode, NEAR_NEARMV | NEAR_NEWMV | NEW_NEARMV) {
23262 let mut idx = 1usize;
23263 while idx < 3 && comp_stack.entries.len() > idx + 1 {
23264 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
23265 break;
23266 }
23267 idx += 1;
23268 }
23269 ref_mv_idx = idx - 1;
23270 }
23271
23272 let near = comp_stack
23273 .entries
23274 .get(ref_mv_idx + 1)
23275 .map_or(comp_stack.near_mv, |e| (e.mv0, e.mv1));
23276 let new_idx = if matches!(mode, NEAR_NEWMV | NEW_NEARMV) {
23277 ref_mv_idx + 1
23278 } else {
23279 ref_mv_idx
23280 };
23281 let new_pred = comp_stack
23282 .entries
23283 .get(new_idx)
23284 .map_or(comp_stack.nearest_mv, |e| (e.mv0, e.mv1));
23285
23286 let read_new = |dec: &mut SymbolDecoder, cdfs: &mut Cdfs, base: (i32, i32)| {
23287 read_mv(
23288 dec,
23289 &mut cdfs.mv_comp,
23290 &mut cdfs.mv_joint,
23291 base,
23292 allow_high_precision_mv,
23293 force_integer_mv,
23294 )
23295 };
23296
23297 match mode {
23298 NEAREST_NEARESTMV => comp_stack.nearest_mv,
23299 NEAR_NEARMV => near,
23300 NEAREST_NEWMV => (comp_stack.nearest_mv.0, read_new(dec, cdfs, new_pred.1)),
23301 NEW_NEARESTMV => (read_new(dec, cdfs, new_pred.0), comp_stack.nearest_mv.1),
23302 NEAR_NEWMV => (near.0, read_new(dec, cdfs, new_pred.1)),
23303 NEW_NEARMV => (read_new(dec, cdfs, new_pred.0), near.1),
23304 GLOBAL_GLOBALMV => global_mv,
23305 _ => (
23306 read_new(dec, cdfs, new_pred.0),
23307 read_new(dec, cdfs, new_pred.1),
23308 ),
23309 }
23310}
23311
23312/// Derives this query block's own [`crate::mvstack::GmMvTable`] -- one
23313/// `gm_get_motion_vector` (spec 7.10.2.1) result per reference frame, at
23314/// THIS block's own `(mi_row, mi_col, bw4, bh4)` (mvstack.rs's own doc: the
23315/// table is always computed at the *querying* block's position, never a
23316/// donating neighbour's).
23317fn build_gm_mv_table(
23318 global_motion: &[ec_av1_syntax::WarpParams; 7],
23319 mi_row: usize,
23320 mi_col: usize,
23321 bw4: usize,
23322 bh4: usize,
23323 allow_high_precision_mv: bool,
23324 force_integer_mv: bool,
23325) -> crate::mvstack::GmMvTable {
23326 std::array::from_fn(|i| {
23327 let gm = &global_motion[i];
23328 crate::warp::gm_get_motion_vector(
23329 gm.model,
23330 &gm.params,
23331 mi_row,
23332 mi_col,
23333 bw4,
23334 bh4,
23335 allow_high_precision_mv,
23336 force_integer_mv,
23337 )
23338 })
23339}
23340
23341/// Decodes one square inter-frame block (32x32 whole or 16x16 leaf): skip,
23342/// `is_inter`, then either the single-reference/MV-stack/motion-vector chain
23343/// and motion-compensated reconstruction, or the inter frame's own intra
23344/// path (`Y_MODE` by size group, not `KF_Y_MODE` by neighbour), mirroring
23345/// [`crate::tile`]'s `sb_coeff_inter_frame_tile`'s whole-block branch and its
23346/// private `write_inter_frame_leaf` -- both share this one function here,
23347/// parameterised by `side`/the transform sets/scan tables/size group they
23348/// each use.
23349///
23350/// # Errors
23351/// Returns an error when a symbol names anything this decoder does not
23352/// reconstruct: a reference other than `LAST_FRAME`, `GLOBALMV` (round 3;
23353/// `NEARESTMV`/`NEARMV`/`NEWMV` are all reconstructed), or an intra
23354/// mode/tx-type outside what [`read_intra_mode`]/[`read_coeffs`] already
23355/// refuse.
23356#[allow(clippy::too_many_arguments)]
23357/// lane-inter4 r1: 16-px-cell coordinates -> MI (4-px) coordinates, the unit
23358/// [`decode_inter_block`]'s `at` now takes.
23359const fn sub16_to_mi(t: (usize, usize)) -> (usize, usize) {
23360 (t.0 * (SUB / MI), t.1 * (SUB / MI))
23361}
23362
23363fn decode_inter_block(
23364 dec: &mut SymbolDecoder,
23365 cdfs: &mut Cdfs,
23366 neighbours: &mut Neighbours,
23367 grid: &mut MiGrid,
23368 at: (usize, usize),
23369 side: usize,
23370 mi_cols: u32,
23371 mi_rows: u32,
23372 y: &mut PlaneBuf<'static>,
23373 u: &mut PlaneBuf<'static>,
23374 v: &mut PlaneBuf<'static>,
23375 ref_y: &PlaneBuf<'_>,
23376 ref_u: &PlaneBuf<'_>,
23377 ref_v: &PlaneBuf<'_>,
23378 // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own
23379 // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]`
23380 // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME`
23381 // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the
23382 // slot's still empty (an error-resilient stream, or too early in the
23383 // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below.
23384 other_refs: &RefSlots,
23385 sign_bias_table: &SignBiasTable,
23386 // lane-gm r2: this frame header's own `global_motion` table (spec
23387 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` same as `sign_bias_table`
23388 // -- feeds `warp::gm_get_motion_vector` for `GLOBALMV`/`GLOBAL_GLOBALMV`
23389 // assignment and the mv-stack's neighbour substitution.
23390 global_motion: &[ec_av1_syntax::WarpParams; 7],
23391 base_q_idx: u8,
23392 luma_set_intra: TxbSet,
23393 luma_set_inter: TxbSet,
23394 chroma_set: TxbSet,
23395 luma_tx: usize,
23396 chroma_tx: usize,
23397 scan_luma: &[u16],
23398 scan_chroma: &[u16],
23399 // lane-inter4 r3: superseded by `size_group_wh(write_w, write_h)` at the
23400 // one site that read it (`y_mode`) -- a rect strip's group comes from its
23401 // true footprint, not the caller's square `side`. Kept in the signature
23402 // rather than editing twenty call sites.
23403 _size_group: usize,
23404 allow_high_precision_mv: bool,
23405 force_integer_mv: bool,
23406 interp_fixed: Option<mc::InterpFilterKind>,
23407 enable_dual_filter: bool,
23408 tpl_frame: Option<&TplFrameArgs>,
23409 // lane-av1comp: this frame header's own `reference_select` bit -- `false`
23410 // means every block is `SINGLE_REFERENCE` by construction and `comp_mode`
23411 // is never read (spec 5.11.25); `true` reads `comp_mode` per block and
23412 // refuses (rather than silently misdecoding) the ones that pick
23413 // `COMPOUND_REFERENCE`, since two-reference motion compensation is not
23414 // wired yet.
23415 reference_select: bool,
23416 // lane-av1comp: `seq_params`' own masked-compound/distance-weighted-
23417 // compound enable bits, gating `comp_group_idx`/`compound_idx`
23418 // (spec 5.11.25) -- always present (unlike `tpl_frame`), since the
23419 // compound blend weights need this frame's own order hint regardless
23420 // of `use_re

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