forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8fd360cTahinli2 months ago2655 commits

decode.rs23509 lines, 1.7 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.
23use crate::hits::{hit, hit_do};
24
25use ec_av1_syntax::{
26 CdefParams, DeltaParams, LoopFilterParams, LoopRestorationParams,
27 SEG_LVL_ALT_LF_Y_V, SEG_LVL_ALT_Q, SegmentationParams, TileInfo,
28};
29use ec_core::{Error, Result};
30
31/// Per-frame decode state, one instance per decoded stream (lane-thread1).
32///
33/// Every field here used to be a `thread_local!` static, which made a decode a
34/// function of the calling THREAD's history rather than of the bitstream alone
35/// -- and made frame-parallel decoding impossible, since a worker thread sees
36/// empty state. The cells keep exactly the interior mutability the statics
37/// had, so every read/write site is byte-identical; what changes is WHERE the
38/// state lives: `stream.rs` owns one `FrameCtx` and threads `&FrameCtx` down
39/// the decode call graph.
40///
41/// `Cell`/`RefCell` make this `!Sync` on purpose: a `FrameCtx` belongs to
42/// exactly one thread's decode, and is never shared between workers.
43/// One frame's in-loop filter intermediates, as [`FrameCtx::capture_stages`]
44/// asks for them: each plane's post-deblock (pre-CDEF) and post-CDEF
45/// (pre-restoration) samples, at the decoder's own plane stride.
46pub(crate) struct FilterStages {
47 /// Post-deblock, pre-CDEF planes (Y, U, V).
48 pub(crate) deblocked: [Vec<u16>; 3],
49 /// Post-CDEF, pre-restoration planes (Y, U, V).
50 pub(crate) cdefed: [Vec<u16>; 3],
51 /// Each plane's stride (and so its width in the buffers above).
52 pub(crate) stride: [usize; 3],
53}
54
55/// Takes whatever the last capturing decode left (see
56/// [`FrameCtx::capture_stages`]).
57#[allow(dead_code)] // read from the encoder's loop restoration search
58pub(crate) fn take_filter_stages(fctx: &FrameCtx) -> Option<FilterStages> {
59 fctx.stages.borrow_mut().take()
60}
61
62pub(crate) struct FrameCtx {
63 /// lane-av1lr: when set, the frame filter chain leaves its post-deblock
64 /// and post-CDEF planes in [`FrameCtx::stages`] for the ENCODER's loop
65 /// restoration search (spec 7.17 reads both: the stripe interior from
66 /// the post-CDEF plane, its 3-row border from the post-deblock one).
67 /// Off for every decode but that search, and off it costs one bool read
68 /// per frame and not a single copy.
69 pub(crate) capture_stages: std::cell::Cell<bool>,
70 pub(crate) stages: std::cell::RefCell<Option<FilterStages>>,
71 pub(crate) sb128_flag: std::cell::Cell<bool>,
72 /// lane-lossless: this frame's `CodedLossless` (spec 5.9.12) -- every
73 /// segment at `qindex == 0` with zero plane deltas. It forces TX_4X4 with
74 /// the Walsh-Hadamard transform on every plane, drops the `tx_type`
75 /// symbol and narrows `is_cfl_allowed` (libaom `read_tx_size`
76 /// (`decodeframe.c`), `read_tx_type` (`decodetxb.c`), `is_cfl_allowed`
77 /// (`blockd.h`)).
78 pub(crate) lossless_flag: std::cell::Cell<bool>,
79 pub(crate) cdef_bits: std::cell::Cell<u8>,
80 pub(crate) bit_depth: std::cell::Cell<u8>,
81 pub(crate) superres: std::cell::Cell<(u32, u32)>,
82 pub(crate) cdef_transmitted: std::cell::Cell<bool>,
83 pub(crate) cdef_sb_cols: std::cell::Cell<usize>,
84 pub(crate) cdef_idx_grid: std::cell::RefCell<Vec<u8>>,
85 pub(crate) delta_q_present: std::cell::Cell<bool>,
86 pub(crate) delta_q_res: std::cell::Cell<i32>,
87 pub(crate) current_q_idx: std::cell::Cell<i32>,
88 pub(crate) quant_deltas: std::cell::Cell<crate::quant::QuantDeltas>,
89 pub(crate) delta_lf_present: std::cell::Cell<bool>,
90 pub(crate) delta_lf_res: std::cell::Cell<i32>,
91 pub(crate) delta_lf_multi: std::cell::Cell<bool>,
92 pub(crate) current_delta_lf: std::cell::Cell<[i32; 4]>,
93 pub(crate) seg: std::cell::RefCell<SegmentationParams>,
94 pub(crate) seg_ids: std::cell::RefCell<Vec<u8>>,
95 pub(crate) prev_seg_ids: std::cell::RefCell<Vec<u8>>,
96 pub(crate) seg_mi_dims: std::cell::Cell<(usize, usize)>,
97 pub(crate) above_seg_pred: std::cell::RefCell<Vec<u8>>,
98 pub(crate) left_seg_pred: std::cell::RefCell<Vec<u8>>,
99 pub(crate) cur_segment_id: std::cell::Cell<u8>,
100 pub(crate) seg_tile_origin: std::cell::Cell<(usize, usize)>,
101 pub(crate) tx_select_inter: std::cell::Cell<bool>,
102 pub(crate) reduced_tx_set_inter: std::cell::Cell<bool>,
103 pub(crate) enable_filter_intra_inter: std::cell::Cell<bool>,
104 pub(crate) palette_pred: std::cell::RefCell<Option<Vec<u16>>>,
105 pub(crate) intrabc_mi_grid: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>>,
106 pub(crate) intrabc_dv: std::cell::Cell<Option<(i32, i32)>>,
107 pub(crate) luma_tx_type: std::cell::Cell<TxType>,
108 pub(crate) intrabc_chroma_tx: std::cell::Cell<Option<TxType>>,
109 pub(crate) intra_in_inter_mode: std::cell::Cell<Option<(usize, bool)>>,
110 pub(crate) inter_strip_chroma: std::cell::Cell<Option<InterStripChroma>>,
111 pub(crate) inter_last_mc:
112 std::cell::Cell<Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>>,
113 pub(crate) enable_edge_filter: std::cell::Cell<bool>,
114 pub(crate) last_frame_wide_margin: std::cell::RefCell<Option<Picture>>,
115 pub(crate) reach_sb_px: std::cell::Cell<usize>,
116 pub(crate) grain_bit_depth: std::cell::Cell<u32>,
117 /// lane-wave1 step (i): this superblock's recorded pixel writes, see
118 /// [`ReconOp`]. Pushed by parse, replayed by [`flush_recon`].
119 pub(crate) recon_ops: std::cell::RefCell<Vec<ReconOp>>,
120 /// The queue buffer [`flush_recon`] just drained, kept for its capacity
121 /// so a superblock's records do not regrow the vector from nothing.
122 pub(crate) recon_spare: std::cell::RefCell<Vec<ReconOp>>,
123 /// lane-recoparse: the coefficient grids of the recorded ops above, one
124 /// buffer instead of a `Vec` per transform unit -- a recorded unit is
125 /// `(offset, len)` into it ([`Residual::Coeffs`]). Written by parse
126 /// before the op is published, read only by whoever replays that op, and
127 /// handed over WITH the ops at every drain point ([`wave_submit`],
128 /// [`flush_recon`]), so offsets are always relative to the live arena.
129 pub(crate) coeff_arena: std::cell::RefCell<Vec<i32>>,
130 /// [`recon_spare`](Self::recon_spare) for the arena, on the inline drain
131 /// path (a submitted job's arena travels to its worker instead).
132 pub(crate) coeff_spare: std::cell::RefCell<Vec<i32>>,
133 /// [`coeff_arena`](Self::coeff_arena) for the recorded PREDICTIONS
134 /// ([`PredSrc::Owned`]): same lifetime, same drain points.
135 pub(crate) pred_arena: std::cell::RefCell<Vec<u16>>,
136 pub(crate) pred_spare: std::cell::RefCell<Vec<u16>>,
137 /// lane-wave1 step (ii): the tile decoder's own planes, registered by
138 /// [`ReconInline`] while reconstruction runs INLINE (one recon thread).
139 /// `None` while the queue is in use (wavefront workers) and outside a
140 /// tile. See [`push_op`].
141 pub(crate) recon_planes: std::cell::Cell<Option<ReconPlanes>>,
142 /// lane-wave1 step (ii): the superblock wavefront this tile's recorded
143 /// writes are handed to, at more than one reconstruction thread.
144 pub(crate) wave: std::cell::RefCell<Option<std::sync::Arc<WaveState>>>,
145 /// lane-wave5 instrumentation only (`EC_AV1_WAVE_STATS`): when the parse
146 /// thread last handed a superblock to the wavefront.
147 pub(crate) wave_mark: std::cell::Cell<Option<std::time::Instant>>,
148}
149
150impl std::fmt::Debug for FrameCtx {
151 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152 f.write_str("FrameCtx")
153 }
154}
155
156impl FrameCtx {
157 /// A fresh context, every field at the default its thread-local
158 /// predecessor was born with.
159 pub(crate) fn new() -> Self {
160 Self {
161 sb128_flag: std::cell::Cell::new(false),
162 lossless_flag: std::cell::Cell::new(false),
163 cdef_bits: std::cell::Cell::new(0),
164 bit_depth: std::cell::Cell::new(8),
165 superres: std::cell::Cell::new((0, 8)),
166 cdef_transmitted: std::cell::Cell::new(false),
167 cdef_sb_cols: std::cell::Cell::new(0),
168 capture_stages: std::cell::Cell::new(false),
169 stages: std::cell::RefCell::new(None),
170 cdef_idx_grid: std::cell::RefCell::new(Vec::new()),
171 delta_q_present: std::cell::Cell::new(false),
172 delta_q_res: std::cell::Cell::new(1),
173 current_q_idx: std::cell::Cell::new(0),
174 quant_deltas: std::cell::Cell::new(crate::quant::QuantDeltas {
175 y_dc: 0,
176 u_dc: 0,
177 u_ac: 0,
178 v_dc: 0,
179 v_ac: 0,
180 }),
181 delta_lf_present: std::cell::Cell::new(false),
182 delta_lf_res: std::cell::Cell::new(1),
183 delta_lf_multi: std::cell::Cell::new(false),
184 current_delta_lf: std::cell::Cell::new([0; 4]),
185 seg: std::cell::RefCell::new(SegmentationParams::default()),
186 seg_ids: std::cell::RefCell::new(Vec::new()),
187 prev_seg_ids: std::cell::RefCell::new(Vec::new()),
188 seg_mi_dims: std::cell::Cell::new((0, 0)),
189 above_seg_pred: std::cell::RefCell::new(Vec::new()),
190 left_seg_pred: std::cell::RefCell::new(Vec::new()),
191 cur_segment_id: std::cell::Cell::new(0),
192 seg_tile_origin: std::cell::Cell::new((0, 0)),
193 tx_select_inter: std::cell::Cell::new(false),
194 reduced_tx_set_inter: std::cell::Cell::new(true),
195 enable_filter_intra_inter: std::cell::Cell::new(false),
196 palette_pred: std::cell::RefCell::new(None),
197 intrabc_mi_grid: std::cell::RefCell::new(None),
198 intrabc_dv: std::cell::Cell::new(None),
199 luma_tx_type: std::cell::Cell::new(TxType::DctDct),
200 intrabc_chroma_tx: std::cell::Cell::new(None),
201 intra_in_inter_mode: std::cell::Cell::new(None),
202 inter_strip_chroma: std::cell::Cell::new(None),
203 inter_last_mc: std::cell::Cell::new(None),
204 enable_edge_filter: std::cell::Cell::new(false),
205 last_frame_wide_margin: std::cell::RefCell::new(None),
206 reach_sb_px: std::cell::Cell::new(crate::encode::SUPERBLOCK),
207 grain_bit_depth: std::cell::Cell::new(8),
208 recon_ops: std::cell::RefCell::new(Vec::new()),
209 recon_spare: std::cell::RefCell::new(Vec::new()),
210 coeff_arena: std::cell::RefCell::new(Vec::new()),
211 coeff_spare: std::cell::RefCell::new(Vec::new()),
212 pred_arena: std::cell::RefCell::new(Vec::new()),
213 pred_spare: std::cell::RefCell::new(Vec::new()),
214 recon_planes: std::cell::Cell::new(None),
215 wave: std::cell::RefCell::new(None),
216 wave_mark: std::cell::Cell::new(None),
217 }
218 }
219}
220
221/// `LocalKey::with` for a plain value: lets every former `STATIC.with(|c| ..)`
222/// site read `fctx.field.with(|c| ..)` unchanged. `LocalKey`'s own inherent
223/// `with` still wins for the scratch pools and gate counters that stay
224/// thread-local.
225pub(crate) trait WithRef {
226 fn with<R>(&self, f: impl FnOnce(&Self) -> R) -> R {
227 f(self)
228 }
229}
230impl<T: ?Sized> WithRef for T {}
231
232/// A [`FrameCtx`] copy for one of [`crate::par`]'s filter worker threads.
233///
234/// `FrameCtx` is `!Sync` on purpose (a decode's state belongs to one thread),
235/// and the post-decode filter chain reads exactly these fields: the bit depth
236/// (every kernel's clamp and threshold shift), the segmentation table
237/// (`segment_id_at`/`lf_level` in the deblocker), the frame's superres state
238/// and the film-grain bit depth. Everything else keeps [`FrameCtx::new`]'s
239/// default -- a field that turns out to be read after all shows up as a hash
240/// mismatch in
241/// `a_real_stream_filters_identically_with_one_and_four_filter_threads`.
242pub(crate) fn filter_ctx_copy(fctx: &FrameCtx) -> FrameCtx {
243 let out = FrameCtx::new();
244 out.bit_depth.set(fctx.bit_depth.get());
245 out.grain_bit_depth.set(fctx.grain_bit_depth.get());
246 out.superres.set(fctx.superres.get());
247 out.seg_mi_dims.set(fctx.seg_mi_dims.get());
248 out.seg.replace(fctx.seg.borrow().clone());
249 out.seg_ids.replace(fctx.seg_ids.borrow().clone());
250 out
251}
252
253use crate::cdf;
254use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
255use crate::encode::{Picture, Reach};
256use crate::intra::predict;
257use crate::mc;
258use crate::msac::SymbolDecoder;
259use crate::mvstack::{
260 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME,
261 MiGrid, MiInfo, NO_REF1, NO_SIGN_BIAS, NeighbourRef, SignBiasTable, comp_reference_type_ctx,
262 find_mv_stack_with_sign_bias, mv16, mv32, reference_mode_ctx,
263 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx,
264 single_ref_p6_ctx, uni_comp_ref_p1_ctx,
265};
266use crate::tile::{INTRA_MODE_CTX, block_grid, has_half};
267use crate::transform::{TxType, dequant_and_inverse_typed_wh};
268
269const PARTITION_NONE: usize = 0;
270const PARTITION_HORZ: usize = 1;
271const PARTITION_VERT: usize = 2;
272const PARTITION_SPLIT: usize = 3;
273const PARTITION_HORZ_A: usize = 4;
274const PARTITION_HORZ_B: usize = 5;
275const PARTITION_VERT_A: usize = 6;
276const PARTITION_VERT_B: usize = 7;
277const PARTITION_HORZ_4: usize = 8;
278const PARTITION_VERT_4: usize = 9;
279const SB_MI: u32 = 16;
280const BLOCK_MI: u32 = 8;
281
282// lane-sb128 r1: this sequence's `use_128x128_superblock` (spec 5.5.1).
283// Every superblock-granular rule below (`delta_q`/`delta_lf`'s "is this the
284// superblock's own top-left mi?", the loop-restoration read's unit span, the
285// partition tree's own root level) keys off it; `SB_MI` stays the 64x64
286// *quadrant* size a 128 superblock is decoded in, which is also what the CDEF
287// grid is indexed by (libaom `read_cdef` reads one `cdef_idx` per 64x64
288// inside a 128 superblock).
289thread_local! {
290 /// lane-frame80: `EC_TRACE_COEFF_FRAME=<decode idx>` narrows the
291 /// `EC_TRACE_COEFF` rungs to a single frame in DECODE order (a 4K stream
292 /// prints gigabytes otherwise). Unset = every frame, as before.
293 static COEFF_TRACE_FRAME: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
294 static COEFF_TRACE_CUR: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
295}
296
297/// Called by [`crate::stream::decode_stream`] before each frame's tiles with
298/// that frame's DECODE-order index.
299pub fn set_coeff_trace_frame(idx: usize) {
300 COEFF_TRACE_FRAME.with(|c| {
301 if c.get().is_none() {
302 let want = match crate::envflags::var("EC_TRACE_COEFF_FRAME") {
303 Ok(v) => v.parse::<usize>().unwrap_or(usize::MAX),
304 // unset: keep tracing every frame, as before this rung existed
305 Err(_) => usize::MAX - 1,
306 };
307 c.set(Some(want));
308 }
309 });
310 COEFF_TRACE_CUR.with(|c| c.set(idx));
311 if crate::envflags::env_flag!("EC_TRACE_COEFF") {
312 eprintln!("EC_COEFF_FRAME decode_idx={idx}");
313 }
314}
315
316pub(crate) fn coeff_trace_on() -> bool {
317 if !crate::envflags::env_flag!("EC_TRACE_COEFF") {
318 return false;
319 }
320 match COEFF_TRACE_FRAME.with(|c| c.get()) {
321 // no `set_coeff_trace_frame` caller (direct tile-decode tests), or the
322 // env var unset: trace every frame.
323 None => true,
324 Some(w) if w >= usize::MAX - 1 => true,
325 Some(w) => COEFF_TRACE_CUR.with(|c| c.get()) == w,
326 }
327}
328
329
330/// Sets [`SB128`] for this thread (called once per frame from `stream.rs`).
331pub(crate) fn set_sb128(v: bool, fctx: &crate::decode::FrameCtx) {
332 fctx.sb128_flag.with(|c| c.set(v));
333 crate::encode::set_reach_superblock_px(if v { 128 } else { 64 }, fctx);
334}
335
336/// Sets [`FrameCtx::lossless_flag`] (called once per frame from `stream.rs`).
337pub(crate) fn set_lossless(v: bool, fctx: &crate::decode::FrameCtx) {
338 fctx.lossless_flag.with(|c| c.set(v));
339}
340
341/// This frame's `CodedLossless` -- see [`FrameCtx::lossless_flag`].
342pub(crate) fn lossless(fctx: &crate::decode::FrameCtx) -> bool {
343 fctx.lossless_flag.with(|c| c.get())
344}
345
346/// The transform side a block of `side` pixels codes: its own (capped at the
347/// caller's own largest) normally, 4 on a lossless frame, where libaom's
348/// `read_tx_size` returns TX_4X4 before it looks at anything else
349/// (`decodeframe.c`: `if (xd->lossless[xd->mi[0]->segment_id]) return
350/// TX_4X4;`).
351pub(crate) fn lossless_tx(px: usize, fctx: &crate::decode::FrameCtx) -> usize {
352 if lossless(fctx) { 4 } else { px }
353}
354
355/// `is_cfl_allowed` (libaom `blockd.h`): CfL is offered on a block up to
356/// 32x32 -- but on a LOSSLESS frame only when the block's CHROMA plane block
357/// is exactly BLOCK_4X4, i.e. (at 4:2:0) a luma block of 8x8 or smaller.
358/// Getting this wrong picks the 14-symbol CFL `uv_mode` alphabet where libaom
359/// picks the 13-symbol one (class `wrong-alphabet-same-value`).
360pub(crate) fn cfl_allowed_px(bw: usize, bh: usize, fctx: &crate::decode::FrameCtx) -> bool {
361 if lossless(fctx) {
362 bw <= 8 && bh <= 8
363 } else {
364 bw <= 32 && bh <= 32
365 }
366}
367
368fn sb128(fctx: &crate::decode::FrameCtx) -> bool {
369 fctx.sb128_flag.with(|c| c.get())
370}
371
372/// This sequence's superblock size in mi units (16 = 64x64, 32 = 128x128).
373pub(crate) fn sb_mi_cur(fctx: &crate::decode::FrameCtx) -> u32 {
374 if sb128(fctx) { SB_MI * 2 } else { SB_MI }
375}
376
377// How many real 128-level partition symbols this decoder has read, and how
378// many superblocks resolved to `PARTITION_SPLIT` (coded or forced) -- the
379// gate's proof a `--sb-size=128` stream exercised the 128 partition root.
380thread_local! {
381 static PART128_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
382 static PART128_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
383 static PART128_GATHERED_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
384}
385
386/// Current value of `PART128_GATHERED_SYMBOLS`: 128 roots that read the
387/// half-out-of-frame gathered split_or_horz/split_or_vert symbol (spec
388/// 5.11.4), which this decoder used to read and throw away.
389#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
390pub(crate) fn part128_gathered_symbols() -> usize {
391 PART128_GATHERED_SYMBOLS.with(|c| c.get())
392}
393
394/// Current value of [`PART128_SYMBOLS`].
395#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
396pub(crate) fn part128_symbols() -> usize {
397 PART128_SYMBOLS.with(|c| c.get())
398}
399
400/// Current value of [`PART128_SPLIT_HITS`].
401#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
402pub(crate) fn part128_split_hits() -> usize {
403 PART128_SPLIT_HITS.with(|c| c.get())
404}
405
406/// [`gather`] over an alphabet of any length -- the 128-level partition CDF
407/// has 8 symbols (no `PARTITION_HORZ_4`/`_VERT_4` at `BLOCK_128X128`, spec
408/// `partition_cdf_length`), so its forced-split gather sums 5 elements where
409/// the 64/32 levels sum 6.
410fn gather_of(cdf: &[u16], elements: &[usize]) -> [u16; 3] {
411 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
412 [32768 - split, 32768, 0]
413}
414
415/// [`VERT_ALIKE`]/[`HORZ_ALIKE`] without the 1:4 arms, for the 128 root.
416const VERT_ALIKE128: [usize; 5] = [2, PARTITION_SPLIT, 4, 6, 7];
417const HORZ_ALIKE128: [usize; 5] = [1, PARTITION_SPLIT, 4, 5, 6];
418
419// How many `use_filter_intra` symbols this decoder has read as `1`, across
420// every call on the current thread -- the cheap counter [`filter_intra_hits`] gate
421// tests read (before/after, not the absolute value) to prove a stream
422// actually exercised the filter-intra predictor rather than silently
423// skipping it.
424thread_local! {
425 static FILTER_INTRA_HITS: std::cell::Cell<usize> =
426 const { std::cell::Cell::new(0) };
427}
428
429/// Current value of [`FILTER_INTRA_HITS`].
430#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
431pub(crate) fn filter_intra_hits() -> usize {
432 FILTER_INTRA_HITS.with(|c| c.get())
433}
434
435// lane-fiinter r1: how many of those `use_filter_intra == 1` symbols belonged
436// to an INTRA block inside an INTER frame (`read_intra_block_mode_info`'s own
437// `read_filter_intra_mode_info` call), which no gate exercised before this
438// round -- every inter gate recipe passed `--enable-filter-intra=0`.
439thread_local! {
440 static INTRA_IN_INTER_FILTER_INTRA_HITS: std::cell::Cell<usize> =
441 const { std::cell::Cell::new(0) };
442}
443
444/// Current value of [`INTRA_IN_INTER_FILTER_INTRA_HITS`].
445#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
446pub(crate) fn intra_in_inter_filter_intra_hits() -> usize {
447 INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.get())
448}
449
450// lane-angleinter r1: how many INTRA blocks inside an INTER frame carried a
451// nonzero `angle_delta_y` / `angle_delta_uv` (`read_intra_angle_info`). Both
452// arms refused a nonzero luma delta before this round, and no inter gate
453// enabled `--enable-angle-delta` (aomenc's own default is 1).
454thread_local! {
455 static INTRA_IN_INTER_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> =
456 const { std::cell::Cell::new(0) };
457 static INTRA_IN_INTER_ANGLE_DELTA_UV_HITS: std::cell::Cell<usize> =
458 const { std::cell::Cell::new(0) };
459}
460
461/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_Y_HITS`].
462#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
463pub(crate) fn intra_in_inter_angle_delta_y_hits() -> usize {
464 INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.get())
465}
466
467/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_UV_HITS`].
468#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
469pub(crate) fn intra_in_inter_angle_delta_uv_hits() -> usize {
470 INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|c| c.get())
471}
472
473// lane-uv8 r1: the three non-DC chroma mode classes an INTRA 8x8 leaf inside
474// an INTER frame ([`decode_inter_block8`]'s intra arm) can carry -- the arm
475// read `uv_mode` and then refused everything but `DC_PRED`. Counted here and
476// nowhere else so the gate's assert cannot be satisfied by a >=16x16 block.
477thread_local! {
478 static INTRA_IN_INTER8_UV_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
479 static INTRA_IN_INTER8_UV_SMOOTH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
480 static INTRA_IN_INTER8_UV_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
481}
482
483thread_local! {
484 static INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
485}
486
487/// Nonzero luma angle deltas coded by an intra 8x8 leaf inside an inter frame
488/// (lane-leaf8tx r1) -- counted only in [`decode_inter_block8`]'s intra arm.
489#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
490pub(crate) fn intra_in_inter8_angle_delta_y_hits() -> usize {
491 INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS.with(|c| c.get())
492}
493
494/// `(directional, smooth/paeth, CfL)` chroma modes coded by an intra 8x8 leaf
495/// inside an inter frame -- see [`INTRA_IN_INTER8_UV_DIR_HITS`].
496#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
497pub(crate) fn intra_in_inter8_uv_hits() -> (usize, usize, usize) {
498 (
499 INTRA_IN_INTER8_UV_DIR_HITS.with(|c| c.get()),
500 INTRA_IN_INTER8_UV_SMOOTH_HITS.with(|c| c.get()),
501 INTRA_IN_INTER8_UV_CFL_HITS.with(|c| c.get()),
502 )
503}
504
505// lane-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into
506// [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a
507// frame-level flag through the recursive block decode -- `0` (the default)
508// makes every call a true no-op, matching every existing gate stream's
509// `cdef_bits == 0` behaviour exactly.
510// lane-realworld r8: the sequence header's `color_config.bit_depth`, set
511// once per `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs`
512// call the same way `CDEF_BITS` is above. `stream.rs`'s own refusal still
513// blocks every non-8-bit stream from reaching a decode call, so this is `8`
514// on every path that runs today -- threading it now (rather than the literal
515// `8`) is stage 1 of widening past that refusal without re-deriving every
516// clamp bound later. `PlaneBuf`'s sample storage stays `u16` regardless of
517// depth (this decoder's own internal choice, matches dav1d/libaom).
518/// `(1 << bit_depth) - 1` — the reconstruction clamp bound for the current
519/// stream's [`BIT_DEPTH`], replacing the crate-wide literal `255`.
520pub(crate) fn sample_max(fctx: &crate::decode::FrameCtx) -> i32 {
521 (1i32 << fctx.bit_depth.with(std::cell::Cell::get)) - 1
522}
523/// The current stream's bit depth, for callers (e.g. dequant) that need the
524/// raw value rather than the derived clamp bound.
525pub(crate) fn bit_depth(fctx: &crate::decode::FrameCtx) -> u8 {
526 fctx.bit_depth.with(std::cell::Cell::get)
527}
528/// Sets [`BIT_DEPTH`] for the current thread, called once per frame from
529/// [`crate::stream`]'s decode loop.
530pub(crate) fn set_bit_depth(bit_depth: u8, fctx: &crate::decode::FrameCtx) {
531 fctx.bit_depth.with(|c| c.set(bit_depth));
532}
533
534 /// This frame's superres state: `(upscaled_width, superres_denom)`, or
535 /// `(0, 8)` when the frame is not scaled. Spec 7.16's upscale runs
536 /// between CDEF and loop restoration, so LOOP RESTORATION -- unit grid,
537 /// `read_lr`'s unit corners and the pixel filters themselves -- works in
538 /// UPSCALED coordinates while deblock and CDEF work in downscaled ones
539 /// (libaom `av1_superres_upscale` in `decodeframe.c`, and
540 /// `av1_loop_restoration_corners_in_sb`'s own `mi_to_num_x`/`denom_x`
541 /// superres arms). Set once per frame from [`crate::stream`]'s decode
542 /// loop, like [`BIT_DEPTH`], and reset to `(0, 8)` on an unscaled frame
543 /// so a later frame never inherits it.
544
545/// Sets [`SUPERRES`] for the current thread. `upscaled_width` is 0 (and
546/// `denom` 8) for a frame that is not superres-scaled.
547pub(crate) fn set_superres(upscaled_width: u32, denom: u32, fctx: &crate::decode::FrameCtx) {
548 fctx.superres.with(|c| c.set((upscaled_width, denom)));
549}
550
551/// `(upscaled_width, superres_denom)` when this frame is superres-scaled
552/// (libaom `av1_superres_scaled`), else `None`.
553pub(crate) fn superres(fctx: &crate::decode::FrameCtx) -> Option<(u32, u32)> {
554 let (w, d) = fctx.superres.with(std::cell::Cell::get);
555 (w > 0 && d != 8).then_some((w, d))
556}
557// Whether this superblock's single CDEF unit (this decoder has no 128x128
558// SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal
559// read -- reset to `false` at the top of each superblock in the two tile
560// loops, spec `read_cdef`'s `cdef_transmitted[index]`.
561// Number of superblock columns in the current tile's grid, so
562// [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into
563// [`CDEF_IDX_GRID`].
564// One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select
565// which of the header's `1 << cdef.bits` strength pairs applies to that
566// superblock's samples.
567// How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`]
568// has read, across every call on the current thread -- the gate's proof that a
569// `cdef_bits > 0` stream actually reached the new reader rather than every
570// superblock coincidentally being all-skip.
571thread_local! {
572 static CDEF_IDX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
573}
574
575// How many times a warp was suppressed for one PLANE because that plane's own
576// block is narrower or shorter than 8 (`av1_init_warp_params`'s own bail-out,
577// reconinter.c) -- the gate's proof that a stream really carries the shape,
578// since the square `side`/`chroma_side` can be 8 or more while the plane's
579// true block is 4 wide (an 8x16 luma block's 4x8 chroma).
580thread_local! {
581 static WARP_PLANE_SUPPRESS_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
582}
583
584/// Current value of [`WARP_PLANE_SUPPRESS_HITS`].
585#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
586pub(crate) fn warp_plane_suppress_hits() -> usize {
587 WARP_PLANE_SUPPRESS_HITS.with(|c| c.get())
588}
589
590/// `av1_init_warp_params` (libaom reconinter.c): warp is decided per PLANE and
591/// bails out at `block_width < 8 || block_height < 8`, so the plane's OWN
592/// block dimensions decide it -- never the square `side`/`chroma_side`, which
593/// for a rectangular luma block (8x16, 16x8) or a PARTITION_HORZ/VERT strip is
594/// bigger than the real block in one axis.
595pub(crate) fn warp_plane_allowed(w: usize, h: usize) -> bool {
596 if w >= 8 && h >= 8 {
597 return true;
598 }
599 hit!(WARP_PLANE_SUPPRESS_HITS);
600 false
601}
602
603/// Current value of [`CDEF_IDX_HITS`].
604#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
605pub(crate) fn cdef_idx_hits() -> usize {
606 CDEF_IDX_HITS.with(|c| c.get())
607}
608
609// lane-t900 r6: gate proof for the three r2-r4 root causes that shipped with no
610// counter -- the in-inter tx-depth context (`tx_size_context_txfm_rect`), the
611// non-chroma-reference block that must LEAVE its neighbours' chroma coefficient
612// contexts alone, and the intra-edge filter neighbour pair taken mi-exact
613// instead of from the coarse 16x16 cell.
614thread_local! {
615 static INTRA_IN_INTER_TXCTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
616 static NON_CHROMA_REF_CTX_SKIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
617 static EDGE_FILTER_MI_FIX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
618}
619
620/// Current value of [`INTRA_IN_INTER_TXCTX_HITS`].
621#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
622pub(crate) fn intra_in_inter_txctx_hits() -> usize {
623 INTRA_IN_INTER_TXCTX_HITS.with(|c| c.get())
624}
625
626/// Current value of [`NON_CHROMA_REF_CTX_SKIP_HITS`].
627#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
628pub(crate) fn non_chroma_ref_ctx_skip_hits() -> usize {
629 NON_CHROMA_REF_CTX_SKIP_HITS.with(|c| c.get())
630}
631
632/// Current value of [`EDGE_FILTER_MI_FIX_HITS`].
633#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
634pub(crate) fn edge_filter_mi_fix_hits() -> usize {
635 EDGE_FILTER_MI_FIX_HITS.with(|c| c.get())
636}
637
638// lane-realworld r4: this frame's `delta.q_present` (spec 5.9.17) and its
639// actual step (`1 << delta.q_res`, already the real multiplier, not the raw
640// 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a
641// true no-op, matching every existing gate stream's `delta_q_present == 0`
642// behaviour exactly, the same corner-cut [`CDEF_BITS`] takes above.
643// The running quantizer index (spec `CurrentQIndex`, libaom
644// `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the
645// top of every tile (spec `decode_tile`), carried across superblocks within
646// that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the
647// dequantization call sites instead of the frame-constant `base_q_idx`.
648// This frame's own per-plane DC/AC quantizer-index deltas (lane-sbpart r11,
649// spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- frame-constant (not
650// per-superblock like [`CURRENT_Q_IDX`]), set once per frame decode and read
651// back at every dequantization call site keyed on which plane it is doing.
652// How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has
653// read, across every call on the current thread -- the gate's proof that a
654// `delta_q_present` stream actually reached the new reader.
655thread_local! {
656 static DELTA_Q_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
657}
658
659/// Current value of [`DELTA_Q_HITS`].
660#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
661pub(crate) fn delta_q_hits() -> usize {
662 DELTA_Q_HITS.with(|c| c.get())
663}
664
665/// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 =
666/// Y, 1 = U, 2 = V) -- luma has no coded `ac` delta (spec 5.9.12 never reads
667/// one), so it is always `0` here.
668fn plane_q_delta(plane_idx: usize, fctx: &crate::decode::FrameCtx) -> (i32, i32) {
669 let d = fctx.quant_deltas.with(|c| c.get());
670 match plane_idx {
671 0 => (d.y_dc, 0),
672 1 => (d.u_dc, d.u_ac),
673 _ => (d.v_dc, d.v_ac),
674 }
675}
676
677/// `read_delta_qindex`/`read_delta_q_params` (spec 5.11.10, libaom
678/// `decodemv.c:85-146,735-770`), called right after [`maybe_read_cdef_idx`]
679/// at every block-decode call site (spec order `skip -> cdef -> delta_q`).
680/// A no-op when `delta_q_present` is unset, or when this block is not at the
681/// superblock's own top-left MI position (`b_row == 0 && b_col == 0` in
682/// libaom, collapsed here to a position check since a partition tree's
683/// top-left leaf is the only block that can ever land there), or when that
684/// leaf both *is* the whole superblock and is `skip` (the one case libaom
685/// itself skips the read, state carrying over unchanged).
686fn 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) {
687 if !fctx.delta_q_present.with(|c| c.get()) {
688 return;
689 }
690 let sb_mi = sb_mi_cur(fctx) as usize;
691 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
692 return;
693 }
694 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
695 // computed against the sequence's own superblock size (lane-sb128b r1:
696 // it used to be hardcoded against 64 and disabled under `sb128`, which a
697 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
698 // wrong).
699 if is_whole_sb && skip {
700 return;
701 }
702 let mut abs = dec.symbol(&mut cdfs.delta_q) as i32;
703 const DELTA_Q_SMALL: i32 = 3;
704 if abs >= DELTA_Q_SMALL {
705 let rem_bits = dec.literal(3) + 1;
706 let thr = (1i32 << rem_bits) + 1;
707 abs = dec.literal(rem_bits) as i32 + thr;
708 }
709 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
710 let reduced = if sign_negative { -abs } else { abs };
711 hit!(DELTA_Q_HITS);
712 let res = fctx.delta_q_res.with(|c| c.get());
713 fctx.current_q_idx.with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));
714}
715
716// lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi`
717// (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`.
718// The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`,
719// `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile,
720// mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever
721// updates index 0 and every reader treats that as the value for all 4
722// indices (spec `read_delta_lf_params`'s own single-cdf branch).
723// How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has
724// read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`].
725thread_local! {
726 static DELTA_LF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
727}
728
729/// Current value of [`DELTA_LF_HITS`].
730#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
731pub(crate) fn delta_lf_hits() -> usize {
732 DELTA_LF_HITS.with(|c| c.get())
733}
734
735/// `read_delta_lflevel`/`read_delta_lf_params` (spec 5.11.11, libaom
736/// `decodemv.c:99-146,735-770`) -- same shape and same call-site gating as
737/// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over
738/// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or
739/// read once into index 0 otherwise.
740fn 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) {
741 if !fctx.delta_lf_present.with(|c| c.get()) {
742 return;
743 }
744 let sb_mi = sb_mi_cur(fctx) as usize;
745 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
746 return;
747 }
748 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
749 // computed against the sequence's own superblock size (lane-sb128b r1:
750 // it used to be hardcoded against 64 and disabled under `sb128`, which a
751 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
752 // wrong).
753 if is_whole_sb && skip {
754 return;
755 }
756 let multi = fctx.delta_lf_multi.with(|c| c.get());
757 let res = fctx.delta_lf_res.with(|c| c.get());
758 let count = if multi { 4 } else { 1 };
759 let mut cur = fctx.current_delta_lf.with(|c| c.get());
760 for i in 0..count {
761 let mut abs = if multi {
762 dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32
763 } else {
764 dec.symbol(&mut cdfs.delta_lf) as i32
765 };
766 const DELTA_LF_SMALL: i32 = 3;
767 if abs >= DELTA_LF_SMALL {
768 let rem_bits = dec.literal(3) + 1;
769 let thr = (1i32 << rem_bits) + 1;
770 abs = dec.literal(rem_bits) as i32 + thr;
771 }
772 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
773 let reduced = if sign_negative { -abs } else { abs };
774 cur[i] = (cur[i] + reduced * res).clamp(-63, 63);
775 hit!(DELTA_LF_HITS);
776 }
777 fctx.current_delta_lf.with(|c| c.set(cur));
778}
779
780/// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
781/// after `skip` is known at every block-decode call site. A no-op at
782/// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and
783/// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
784/// `allow_intrabc`, so neither needs a separate check here. Reads once per
785/// superblock, at the first non-skip block.
786fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: bool, fctx: &crate::decode::FrameCtx) {
787 let bits = fctx.cdef_bits.with(|c| c.get());
788 if bits == 0 || skip || fctx.cdef_transmitted.with(|c| c.get()) {
789 return;
790 }
791 let idx = dec.literal(u32::from(bits)) as u8;
792 fctx.cdef_transmitted.with(|c| c.set(true));
793 hit!(CDEF_IDX_HITS);
794 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
795 let sb_cols = fctx.cdef_sb_cols.with(|c| c.get());
796 if sb_cols > 0 {
797 fctx.cdef_idx_grid.with(|g| {
798 let mut g = g.borrow_mut();
799 let i = sb_r * sb_cols + sb_c;
800 if i < g.len() {
801 g[i] = idx;
802 }
803 });
804 }
805}
806
807// ---------------------------------------------------------------------------
808// lane-seg: segmentation. Header (spec 5.9.14) is parsed by `ec-av1-syntax`;
809// this block is the per-block `segment_id` reader (spec 5.11.7-5.11.9) plus
810// the two consumers a real stream exercises: the per-segment quantizer index
811// (spec 7.12.2 `get_qindex`) and the per-segment loop-filter level
812// (spec 7.14.4). Shapes follow libaom `decodemv.c:read_segment_id`/
813// `read_intra_segment_id`/`read_inter_segment_id` and
814// `pred_common.h:av1_get_spatial_seg_pred` -- note libaom returns the SPATIAL
815// PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which
816// is what the oracle every gate here compares against actually does.
817thread_local! {
818 /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries
819 /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride).
820 /// `PrevSegmentIds`: the primary reference frame's saved map, empty when
821 /// this frame has no primary reference (spec `load_previous_segment_ids`).
822 /// `(mi_rows, mi_cols)` for both maps above.
823 /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi
824 /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which
825 /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead.
826 /// The block currently being decoded -- read back by [`block_q_idx`].
827 /// The tile's own top-left mi position, for `AvailU`/`AvailL`.
828 /// How many real `segment_id` symbols were read, and the set of segment
829 /// ids any block ended up with -- the gate's proof the feature fired.
830 static SEG_ID_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
831 static SEG_IDS_SEEN: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
832 /// How many `seg_id_predicted` symbols were read (temporal update).
833 static SEG_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
834}
835
836/// Installs this frame's segmentation parameters and allocates its map, with
837/// `prev` the primary reference frame's saved map (spec
838/// `load_previous_segment_ids`; `None` for `PRIMARY_REF_NONE` or an empty
839/// slot). Called once per frame, whether or not segmentation is enabled.
840pub(crate) fn set_segmentation(
841 seg: SegmentationParams,
842 mi_rows: usize,
843 mi_cols: usize,
844 prev: Option<&[u8]>, fctx: &crate::decode::FrameCtx,
845) {
846 fctx.seg.with(|s| *s.borrow_mut() = seg);
847 fctx.seg_mi_dims.with(|c| c.set((mi_rows, mi_cols)));
848 fctx.seg_ids.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]);
849 fctx.prev_seg_ids.with(|m| {
850 let mut m = m.borrow_mut();
851 m.clear();
852 if let Some(p) = prev {
853 if p.len() == mi_rows * mi_cols {
854 m.extend_from_slice(p);
855 }
856 }
857 });
858 fctx.above_seg_pred.with(|m| *m.borrow_mut() = vec![0u8; mi_cols]);
859 fctx.left_seg_pred.with(|m| *m.borrow_mut() = vec![0u8; mi_rows]);
860 fctx.cur_segment_id.with(|c| c.set(0));
861}
862
863/// This frame's decoded segment map, to be stored into whichever reference
864/// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`).
865pub(crate) fn take_segment_ids(fctx: &crate::decode::FrameCtx) -> Vec<u8> {
866 fctx.seg_ids.with(|m| m.borrow().clone())
867}
868
869/// How many `segment_id` symbols have been read (never reset per frame).
870#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
871pub(crate) fn segment_id_hits() -> usize {
872 SEG_ID_HITS.with(|c| c.get())
873}
874
875/// How many distinct segment ids any decoded block has carried.
876#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
877pub(crate) fn segment_ids_seen() -> usize {
878 SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize)
879}
880
881/// How many `seg_id_predicted` symbols have been read (temporal update).
882#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
883pub(crate) fn segment_pred_hits() -> usize {
884 SEG_PRED_HITS.with(|c| c.get())
885}
886
887/// Resets the segmentation hit counters (gate setup).
888#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
889pub(crate) fn reset_segment_hits() {
890 SEG_ID_HITS.with(|c| c.set(0));
891 SEG_IDS_SEEN.with(|c| c.set(0));
892 SEG_PRED_HITS.with(|c| c.set(0));
893}
894
895/// `seg_feature_active_idx(segment_id, feature)` for the frame currently
896/// being decoded, with its `FeatureData` value.
897fn seg_feature(segment_id: usize, feature: usize, fctx: &crate::decode::FrameCtx) -> Option<i32> {
898 fctx.seg.with(|s| {
899 let s = s.borrow();
900 s.feature_active(segment_id, feature)
901 .then(|| i32::from(s.feature_data[segment_id][feature]))
902 })
903}
904
905/// `get_qindex(ignoreDeltaQ = 0, segment_id)` (spec 7.12.2, libaom
906/// `av1_get_qindex`) for the block currently being decoded: the running
907/// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data.
908/// Every dequant call site reads the block's quantizer through here.
909fn block_q_idx(fctx: &crate::decode::FrameCtx) -> i32 {
910 let base = fctx.current_q_idx.with(|c| c.get());
911 let seg_id = fctx.cur_segment_id.with(|c| c.get()) as usize;
912 match seg_feature(seg_id, SEG_LVL_ALT_Q, fctx) {
913 Some(data) => (base + data).clamp(0, 255),
914 None => base,
915 }
916}
917
918/// The segment id recorded for one mi cell of the current frame's map.
919fn segment_id_at(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> u8 {
920 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
921 if mi_r >= mi_rows || mi_c >= mi_cols {
922 return 0;
923 }
924 fctx.seg_ids.with(|m| m.borrow()[mi_r * mi_cols + mi_c])
925}
926
927/// `set_segment_id`: stamps `id` over every mi cell this block covers.
928fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8, fctx: &crate::decode::FrameCtx) {
929 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
930 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
931 fctx.seg_ids.with(|m| {
932 let mut m = m.borrow_mut();
933 for y in 0..y_mis {
934 for x in 0..x_mis {
935 m[(mi_r + y) * mi_cols + mi_c + x] = id;
936 }
937 }
938 });
939 fctx.cur_segment_id.with(|c| c.set(id));
940 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
941}
942
943/// `get_predicted_segment_id` (libaom `dec_get_segment_id` over
944/// `last_frame_seg_map`): the minimum previous-frame segment id over the
945/// block's own mi footprint. `0` when there is no previous map.
946fn predicted_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, fctx: &crate::decode::FrameCtx) -> u8 {
947 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
948 fctx.prev_seg_ids.with(|m| {
949 let m = m.borrow();
950 if m.is_empty() {
951 return 0;
952 }
953 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
954 let mut id = u8::MAX;
955 for y in 0..y_mis {
956 for x in 0..x_mis {
957 id = id.min(m[(mi_r + y) * mi_cols + mi_c + x]);
958 }
959 }
960 if id == u8::MAX { 0 } else { id }
961 })
962}
963
964/// `av1_neg_deinterleave` (libaom `decodemv.c:258`).
965fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 {
966 if reference == 0 {
967 return diff;
968 }
969 if reference >= max - 1 {
970 return max - diff - 1;
971 }
972 let half = if 2 * reference < max {
973 diff <= 2 * reference
974 } else {
975 diff <= 2 * (max - reference - 1)
976 };
977 if half {
978 return if diff & 1 != 0 {
979 reference + ((diff + 1) >> 1)
980 } else {
981 reference - (diff >> 1)
982 };
983 }
984 if 2 * reference < max { diff } else { max - (diff + 1) }
985}
986
987/// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current
988/// frame's already-decoded above/left/above-left neighbours.
989fn spatial_seg_pred(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> (i32, usize) {
990 let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
991 let (avail_u, avail_l) = (mi_r > row0, mi_c > col0);
992 let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1, fctx)));
993 let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c, fctx)));
994 let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1, fctx)));
995 let ctx = match prev_ul {
996 None => 0,
997 Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2,
998 Some(ul) if Some(ul) == prev_u || Some(ul) == prev_l || prev_u == prev_l => 1,
999 Some(_) => 0,
1000 };
1001 let pred = match (prev_u, prev_l) {
1002 (None, l) => l.unwrap_or(0),
1003 (Some(u), None) => u,
1004 (Some(u), Some(l)) => {
1005 if prev_ul == Some(u) {
1006 u
1007 } else {
1008 l
1009 }
1010 }
1011 };
1012 (pred, ctx)
1013}
1014
1015/// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id
1016/// when `skip`, otherwise one `segment_id` symbol de-interleaved against
1017/// that prediction. Does NOT write the map -- callers do.
1018fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, skip: bool, fctx: &crate::decode::FrameCtx) -> u8 {
1019 let (pred, ctx) = spatial_seg_pred(mi_r, mi_c, fctx);
1020 if skip {
1021 return pred as u8;
1022 }
1023 let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32;
1024 hit!(SEG_ID_HITS);
1025 let last_active = fctx.seg.with(|s| i32::from(s.borrow().last_active_seg_id));
1026 neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active) as u8
1027}
1028
1029/// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block
1030/// -- once before `skip` when `SegIdPreSkip`, once after it otherwise (the
1031/// caller decides which by passing `pre_skip`).
1032fn intra_segment_id(
1033 dec: &mut SymbolDecoder,
1034 cdfs: &mut Cdfs,
1035 mi_r: usize,
1036 mi_c: usize,
1037 w_mi: usize,
1038 h_mi: usize,
1039 skip: bool, fctx: &crate::decode::FrameCtx,
1040) {
1041 if !fctx.seg.with(|s| s.borrow().enabled) {
1042 return;
1043 }
1044 let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip, fctx);
1045 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1046}
1047
1048/// Whether this frame's intra blocks read their `segment_id` before `skip`
1049/// (`SegIdPreSkip`); `false` also when segmentation is off.
1050fn seg_id_pre_skip(fctx: &crate::decode::FrameCtx) -> bool {
1051 fctx.seg.with(|s| {
1052 let s = s.borrow();
1053 s.enabled && s.seg_id_pre_skip
1054 })
1055}
1056
1057/// `read_inter_segment_id(preskip)` (spec 5.11.9, libaom `decodemv.c:352`).
1058/// Called at both spec positions of an inter frame's block: `pre_skip = true`
1059/// before `skip_mode`/`skip`, and `pre_skip = false` after them.
1060fn inter_segment_id(
1061 dec: &mut SymbolDecoder,
1062 cdfs: &mut Cdfs,
1063 mi_r: usize,
1064 mi_c: usize,
1065 w_mi: usize,
1066 h_mi: usize,
1067 skip: bool,
1068 pre_skip: bool, fctx: &crate::decode::FrameCtx,
1069) {
1070 let (enabled, update_map, temporal_update, pre_skip_frame) = fctx.seg.with(|s| {
1071 let s = s.borrow();
1072 (s.enabled, s.update_map, s.temporal_update, s.seg_id_pre_skip)
1073 });
1074 if !enabled {
1075 return;
1076 }
1077 if !update_map {
1078 // The map is inherited wholesale from the previous frame.
1079 let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx);
1080 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1081 return;
1082 }
1083 if pre_skip && !pre_skip_frame {
1084 return;
1085 }
1086 if !pre_skip && skip {
1087 // libaom: a skipped block never codes `seg_id_predicted`, and its
1088 // segment id is the spatial prediction.
1089 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0, fctx);
1090 let id = read_segment_id(dec, cdfs, mi_r, mi_c, true, fctx);
1091 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1092 return;
1093 }
1094 let id = if temporal_update {
1095 let ctx = seg_pred_ctx(mi_r, mi_c, fctx);
1096 let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0;
1097 hit!(SEG_PRED_HITS);
1098 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted), fctx);
1099 if predicted {
1100 predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx)
1101 } else {
1102 read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
1103 }
1104 } else {
1105 read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
1106 };
1107 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1108}
1109
1110/// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags.
1111fn seg_pred_ctx(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> usize {
1112 // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and
1113 // so contribute 0) outside the tile -- the availability check here is
1114 // what keeps a previous tile's stamps out of this tile's context.
1115 let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
1116 let above = if mi_r > row0 {
1117 fctx.above_seg_pred.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))
1118 } else {
1119 0
1120 };
1121 let left = if mi_c > col0 {
1122 fctx.left_seg_pred.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))
1123 } else {
1124 0
1125 };
1126 usize::from(above + left)
1127}
1128
1129/// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update.
1130fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8, fctx: &crate::decode::FrameCtx) {
1131 fctx.above_seg_pred.with(|m| {
1132 let mut m = m.borrow_mut();
1133 for i in 0..w_mi {
1134 if let Some(cell) = m.get_mut(mi_c + i) {
1135 *cell = value;
1136 }
1137 }
1138 });
1139 fctx.left_seg_pred.with(|m| {
1140 let mut m = m.borrow_mut();
1141 for i in 0..h_mi {
1142 if let Some(cell) = m.get_mut(mi_r + i) {
1143 *cell = value;
1144 }
1145 }
1146 });
1147}
1148
1149// How many key-frame luma blocks resolved `smooth_neighbor` (spec
1150// `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after
1151// counter, proving a stream actually put a directional block next to a
1152// smooth-predicted neighbour rather than every block reading the (previously
1153// hardcoded `false`) edge-filter strength bucket unchanged.
1154thread_local! {
1155 static SMOOTH_LUMA_HITS: std::cell::Cell<usize> =
1156 const { std::cell::Cell::new(0) };
1157}
1158
1159/// Current value of [`SMOOTH_LUMA_HITS`].
1160#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1161pub(crate) fn smooth_luma_hits() -> usize {
1162 SMOOTH_LUMA_HITS.with(|c| c.get())
1163}
1164
1165thread_local! {
1166 /// lane-band46 r1: how many split-transform units answered their intra
1167 /// reach DIFFERENTLY under libaom's per-unit rules ([`Reach::of_tu`], the
1168 /// palette2 r12 fix) than the standalone-block lookup this decoder used to
1169 /// apply to them (class reach-is-per-transform-unit). Every hit is a
1170 /// transform unit whose above-right / below-left reference samples would
1171 /// be wrong without that fix.
1172 static SPLIT_TU_REACH_FIX_HITS: std::cell::Cell<usize> =
1173 const { std::cell::Cell::new(0) };
1174}
1175
1176/// Current value of [`SPLIT_TU_REACH_FIX_HITS`].
1177#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1178pub(crate) fn split_tu_reach_fix_hits() -> usize {
1179 SPLIT_TU_REACH_FIX_HITS.with(|c| c.get())
1180}
1181
1182/// [`Reach::of_tu`] for one transform unit, counting how often that per-unit
1183/// answer differs from the standalone-block answer the call sites used before
1184/// lane-palette2 r12 -- the counter a gate asserts on to prove a stream really
1185/// exercised the fix. `col_off`/`row_off` are in SAMPLES from the parent
1186/// block's top-left `(px, py)`.
1187#[allow(clippy::too_many_arguments)]
1188fn tu_reach(
1189 bw: usize,
1190 bh: usize,
1191 col_off: usize,
1192 row_off: usize,
1193 tx: usize,
1194 block: Reach,
1195 px: usize,
1196 py: usize,
1197 width: usize,
1198 height: usize, fctx: &crate::decode::FrameCtx,
1199) -> Reach {
1200 let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block);
1201 let standalone = Reach::of(tx, px + col_off, py + row_off, width, height, fctx);
1202 if fixed != standalone {
1203 hit!(SPLIT_TU_REACH_FIX_HITS);
1204 }
1205 fixed
1206}
1207
1208// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12),
1209// across every call on the current thread -- lane-chroma r3's own before/after
1210// counter, proving a stream actually exercised chroma's smooth/paeth
1211// predictor (the previously-refused round-2 gap) rather than every block
1212// landing on DC/CFL/directional.
1213thread_local! {
1214 static SMOOTH_UV_HITS: std::cell::Cell<usize> =
1215 const { std::cell::Cell::new(0) };
1216}
1217
1218/// Current value of [`SMOOTH_UV_HITS`].
1219#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1220pub(crate) fn smooth_uv_hits() -> usize {
1221 SMOOTH_UV_HITS.with(|c| c.get())
1222}
1223
1224// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a
1225// full superblock walk over, across every call on the current thread --
1226// lane-tiles r2's own gate-blind-to-feature guard: a gate over a
1227// multi-tile stream must prove more than one tile actually fired, not just
1228// that the stream carried tile_info.cols > 1.
1229thread_local! {
1230 static TILE_HITS: std::cell::Cell<usize> =
1231 const { std::cell::Cell::new(0) };
1232}
1233/// Current value of [`TILE_HITS`].
1234#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1235pub(crate) fn tile_hits() -> usize {
1236 TILE_HITS.with(|c| c.get())
1237}
1238
1239// How many 4-pixel deblocking edge groups [`edge_params`] has actually
1240// selected for filtering, across every call on the current thread -- the same
1241// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1242// exercised `apply_deblock` rather than every edge landing on level 0.
1243thread_local! {
1244 static DEBLOCK_HITS: std::cell::Cell<usize> =
1245 const { std::cell::Cell::new(0) };
1246}
1247/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
1248/// mirroring stream.rs's `pictures_decoded` so the two dumps index
1249/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
1250static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize =
1251 std::sync::atomic::AtomicUsize::new(0);
1252
1253/// Current value of [`DEBLOCK_HITS`].
1254#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1255pub(crate) fn deblock_hits() -> usize {
1256 DEBLOCK_HITS.with(|c| c.get())
1257}
1258
1259// lane-defon r1: how many COMPOUND_REFERENCE blocks read a
1260// `UNIDIR_COMP_REFERENCE` pair (both references on the same temporal side,
1261// spec 5.11.25 `comp_reference_type == 0`) -- the gate's proof that a
1262// stream built with `--enable-onesided-comp=1` really exercised the
1263// `uni_comp_ref` alphabet rather than only bidirectional pairs.
1264thread_local! {
1265 static UNI_COMP_HITS: std::cell::Cell<usize> =
1266 const { std::cell::Cell::new(0) };
1267}
1268
1269/// Current value of [`UNI_COMP_HITS`].
1270#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1271pub(crate) fn uni_comp_hits() -> usize {
1272 UNI_COMP_HITS.with(|c| c.get())
1273}
1274
1275// lane-defon r1: how many blocks blended through a `COMPOUND_DIFFWTD` mask
1276// (`mc::diffwtd_mask`) -- the narrower half of `MASKED_COMPOUND_HITS`, the
1277// gate's proof that `--enable-diff-wtd-comp=1` reached the difference-weighted
1278// blend and not only the wedge arm.
1279thread_local! {
1280 static DIFFWTD_HITS: std::cell::Cell<usize> =
1281 const { std::cell::Cell::new(0) };
1282}
1283
1284/// Current value of [`DIFFWTD_HITS`].
1285#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1286pub(crate) fn diffwtd_hits() -> usize {
1287 DIFFWTD_HITS.with(|c| c.get())
1288}
1289
1290// lane-mcomp64 r1: how many blocks took the INFERRED `COMPOUND_DIFFWTD` arm --
1291// a block size where `av1_is_wedge_used` is false (64x64 is the only such size
1292// this decoder's square inter path reaches), so no `compound_type` symbol is
1293// coded at all. Strictly narrower than `DIFFWTD_HITS`, which also counts the
1294// coded-symbol DIFFWTD blocks at 8x8/16x16/32x32.
1295thread_local! {
1296 static DIFFWTD_INFERRED_HITS: std::cell::Cell<usize> =
1297 const { std::cell::Cell::new(0) };
1298}
1299
1300/// Current value of [`DIFFWTD_INFERRED_HITS`].
1301#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1302pub(crate) fn diffwtd_inferred_hits() -> usize {
1303 DIFFWTD_INFERRED_HITS.with(|c| c.get())
1304}
1305
1306// lane-defon r1: how many FORWARD KEYFRAMES were decoded -- a KEY frame coded
1307// with `show_frame == 0`, output later by a `show_existing_frame` header
1308// (aomenc `--enable-fwd-kf=1 --fwd-kf-dist=N`). Counted from
1309// `stream::decode_stream`, which is where the frame header is consumed; the
1310// gate's proof that the on-value really reached the bitstream rather than
1311// being dropped by the rate control.
1312thread_local! {
1313 static FWD_KF_HITS: std::cell::Cell<usize> =
1314 const { std::cell::Cell::new(0) };
1315}
1316
1317/// Current value of [`FWD_KF_HITS`].
1318#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1319pub(crate) fn fwd_kf_hits() -> usize {
1320 FWD_KF_HITS.with(|c| c.get())
1321}
1322
1323/// Records one decoded forward keyframe (see [`FWD_KF_HITS`]).
1324pub(crate) fn note_fwd_kf() {
1325 hit!(FWD_KF_HITS);
1326}
1327
1328// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
1329// the block's own side, across every call on the current thread -- the same
1330// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1331// actually exercised a *split* transform under `TxMode::Select` rather than
1332// every block coincidentally resolving `depth=0` (indistinguishable from
1333// `TxMode::Largest` pixel-wise).
1334thread_local! {
1335 static TX_DEPTH_HITS: std::cell::Cell<usize> =
1336 const { std::cell::Cell::new(0) };
1337}
1338
1339// How many plain SQUARE intra blocks (lane-sqchroma r1) resolved a luma
1340// transform smaller than their own side (`tx_depth != 0`) while coding a
1341// chroma prediction other than `DC_PRED` -- the pair the square path's chroma
1342// only exercises with aomenc's tx-size search left ON (its default), which
1343// every older recipe in this file pins off. Counted at the block, so a stream
1344// where RD happened to give every split-transform block a DC chroma mode
1345// reads as zero rather than silently passing for free.
1346thread_local! {
1347 static SQ_CHROMA_TX_HITS: std::cell::Cell<usize> =
1348 const { std::cell::Cell::new(0) };
1349}
1350
1351/// Current value of [`SQ_CHROMA_TX_HITS`].
1352#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1353pub(crate) fn sq_chroma_tx_hits() -> usize {
1354 SQ_CHROMA_TX_HITS.with(|c| c.get())
1355}
1356
1357/// Current value of [`TX_DEPTH_HITS`].
1358#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1359pub(crate) fn tx_depth_hits() -> usize {
1360 TX_DEPTH_HITS.with(|c| c.get())
1361}
1362
1363// lane-txselect: how many `txfm_split` symbols an inter frame's var-tx tree
1364// read, and how many of those actually took the split, on the current thread
1365// -- the same before/after counter pattern as [`TX_DEPTH_HITS`], proving a
1366// stream exercised spec 5.11.17's `read_var_tx_size` rather than every block
1367// coincidentally coding one whole-block transform.
1368thread_local! {
1369 static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1370 static TXFM_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1371 // lane-inter4 r2: rectangular INTER residual coding -- how many rect
1372 // strips coded one whole-block rect transform unit, and how many split
1373 // their rect max transform into square sub-transforms.
1374 static RECT_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1375 static RECT_INTER_TXSPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1376 // lane-r14 r2: luma transform units of an inter strip with a 64-px axis
1377 // (64x32/32x64/64x16/16x64), whose coefficients are coded as the
1378 // truncated low-32 corner.
1379 static RECT64_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1380 // lane-rectres r1: whole-block luma transform units of a 32x32-level 1:4
1381 // inter strip, `[32x8, 8x32]`.
1382 static RECT32X8_INTER_TU_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1383 // lane-r14 r3: rectangular var-tx LEAVES, [32x16, 16x32].
1384 static VARTX_RECT_LEAF_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1385 // lane-inter16ab r4: rectangular var-tx leaves with a 4-px axis, [8x4, 4x8]
1386 // -- the `sub_tx_size_map[TX_16X4]` split leaves of a 16x16-level 1:4 strip.
1387 static VARTX_RECT_LEAF4_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1388 // lane-inter4 r3: 16x16-level PARTITION_HORZ / PARTITION_VERT on an inter
1389 // frame -- 16x8 and 8x16 inter leaves.
1390 static INTER_LEAF16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1391 static INTER_LEAF16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1392 // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits,
1393 // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] --
1394 // `decode_inter_block` already carries forty parameters and both are
1395 // frame-constant.
1396 // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit,
1397 // frame-constant like the two above and stashed the same way -- an intra
1398 // block inside an inter frame reads `use_filter_intra` under it.
1399}
1400
1401/// Current value of [`TXFM_SPLIT_READS`].
1402#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1403pub(crate) fn txfm_split_reads() -> usize {
1404 TXFM_SPLIT_READS.with(|c| c.get())
1405}
1406
1407/// Current value of [`TXFM_SPLIT_HITS`].
1408#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1409pub(crate) fn txfm_split_hits() -> usize {
1410 TXFM_SPLIT_HITS.with(|c| c.get())
1411}
1412
1413/// Current value of [`INTER_LEAF16_HORZ_HITS`] (lane-inter4 r3).
1414#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1415pub(crate) fn inter_leaf16_horz_hits() -> usize {
1416 INTER_LEAF16_HORZ_HITS.with(|c| c.get())
1417}
1418
1419/// Current value of [`INTER_LEAF16_VERT_HITS`] (lane-inter4 r3).
1420#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1421pub(crate) fn inter_leaf16_vert_hits() -> usize {
1422 INTER_LEAF16_VERT_HITS.with(|c| c.get())
1423}
1424
1425/// Current value of [`RECT_INTER_TU_HITS`] (lane-inter4 r2).
1426pub(crate) fn rect_inter_tu_hits() -> usize {
1427 RECT_INTER_TU_HITS.with(|c| c.get())
1428}
1429
1430/// Current value of [`RECT_INTER_TXSPLIT_HITS`] (lane-inter4 r2).
1431pub(crate) fn rect_inter_txsplit_hits() -> usize {
1432 RECT_INTER_TXSPLIT_HITS.with(|c| c.get())
1433}
1434
1435/// Current value of [`RECT64_INTER_TU_HITS`] (lane-r14 r2).
1436pub(crate) fn rect64_inter_tu_hits() -> usize {
1437 RECT64_INTER_TU_HITS.with(|c| c.get())
1438}
1439
1440/// Current value of [`RECT32X8_INTER_TU_HITS`] (lane-rectres r1): `[32x8, 8x32]`
1441/// whole-block luma units of a 32x32-level 1:4 inter strip.
1442pub(crate) fn rect32x8_inter_tu_hits() -> [usize; 2] {
1443 RECT32X8_INTER_TU_HITS.with(|c| c.get())
1444}
1445
1446/// Current value of [`VARTX_RECT_LEAF_HITS`] (lane-r14 r3): how many
1447/// rectangular var-tx leaf transform units were coded, `[32x16, 16x32]`.
1448pub(crate) fn vartx_rect_leaf_hits() -> [usize; 2] {
1449 VARTX_RECT_LEAF_HITS.with(|c| c.get())
1450}
1451
1452/// Current value of [`VARTX_RECT_LEAF4_HITS`] (lane-inter16ab r4): 8x4/4x8
1453/// split leaves of a 16x4/4x16 strip, `[8x4, 4x8]`.
1454pub(crate) fn vartx_rect_leaf4_hits() -> [usize; 2] {
1455 VARTX_RECT_LEAF4_HITS.with(|c| c.get())
1456}
1457
1458/// Records one rectangular var-tx leaf.
1459fn vartx_rect_leaf_hit(tw: usize, th: usize) {
1460 if crate::envflags::env_flag!("EC_VARTXLEAF") {
1461 eprintln!("EC_VARTXLEAF tw={tw} th={th}");
1462 }
1463 let cell = if tw.min(th) == 4 { &VARTX_RECT_LEAF4_HITS } else { &VARTX_RECT_LEAF_HITS };
1464 cell.with(|c| {
1465 let mut h = c.get();
1466 h[usize::from(th > tw)] += 1;
1467 c.set(h);
1468 });
1469}
1470
1471/// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/
1472/// [`ENABLE_FILTER_INTRA_INTER`].
1473pub(crate) fn set_inter_tx_mode(
1474 tx_select: bool,
1475 reduced_tx_set: bool,
1476 enable_filter_intra: bool, fctx: &crate::decode::FrameCtx,
1477) {
1478 fctx.tx_select_inter.with(|c| c.set(tx_select));
1479 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
1480 fctx.enable_filter_intra_inter.with(|c| c.set(enable_filter_intra));
1481}
1482
1483// How many `partition_w16` reads (a 16x16 block's own partition symbol, key
1484// intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a
1485// plain default-settings aomenc run over lavfi mandelbrot hits this arm on
1486// frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not
1487// the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real
1488// `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`,
1489// chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8
1490// path above).
1491thread_local! {
1492 static VERT_B_INTRA_HITS: std::cell::Cell<usize> =
1493 const { std::cell::Cell::new(0) };
1494}
1495
1496/// Current value of [`VERT_B_INTRA_HITS`].
1497#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1498pub(crate) fn vert_b_intra_hits() -> usize {
1499 VERT_B_INTRA_HITS.with(|c| c.get())
1500}
1501
1502// lane-ab16 r1: how many 16x16-level AB partitions fired, per arm, in
1503// `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order. Each arm is two
1504// 8x8 squares (`decode_leaf8`) plus one 16x8/8x16 strip (`decode_leaf_rect`,
1505// the non-skip coefficient path lane-rectx proved); the gate hard-asserts
1506// every arm separately so a run where aomenc's RD only picked one cannot
1507// pass as proof of four.
1508thread_local! {
1509 static AB16_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
1510}
1511
1512// [`AB16_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16).
1513thread_local! {
1514 /// 4x4 transform units decoded inside an 8x8 square of a
1515 /// `PARTITION_VERT_A`/`_B` -- the exact call that panicked before
1516 /// [`crate::encode::Reach::of_tu`] (lane-ab16 r2), so the gate can prove
1517 /// a real `--enable-tx-size-search=1` stream reaches it.
1518 static VERT_AB_TX4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1519}
1520
1521#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1522pub(crate) fn vert_ab_tx4_hits() -> usize {
1523 VERT_AB_TX4_HITS.with(std::cell::Cell::get)
1524}
1525
1526#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1527pub(crate) fn ab16_hits_by_arm() -> [usize; 4] {
1528 AB16_HITS.with(std::cell::Cell::get)
1529}
1530
1531fn bump_ab16(arm: usize) {
1532 hit_do! {
1533 AB16_HITS.with(|c| {
1534 let mut v = c.get();
1535 v[arm] += 1;
1536 c.set(v);
1537 });
1538 }
1539}
1540
1541// How many `partition_w16` reads resolved to a plain `PARTITION_HORZ`/
1542// `PARTITION_VERT` (lane-rect16 r2): re-measuring after the VERT_B fix above
1543// showed mandelbrot's real first-hit blocker is this plain arm at mi=(0,7),
1544// not VERT_B (`refusal-names-a-correlate`; the VERT_B write-up's "frame 0's
1545// very first non-NONE/SPLIT symbol" claim was about decode ORDER within one
1546// superblock's z-order recursion, not raster mi position).
1547thread_local! {
1548 static HORZ_VERT_INTRA_HITS: std::cell::Cell<usize> =
1549 const { std::cell::Cell::new(0) };
1550}
1551
1552/// Current value of [`HORZ_VERT_INTRA_HITS`].
1553#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1554pub(crate) fn horz_vert_intra_hits() -> usize {
1555 HORZ_VERT_INTRA_HITS.with(|c| c.get())
1556}
1557
1558// How many blocks were decoded as a frame-edge rect strip -- the single
1559// coded half of a `PARTITION_HORZ`/`PARTITION_VERT` at the true frame edge
1560// (lane-oddh r1), i.e. a block living inside the 8px band of a frame whose
1561// height or width is 8 mod 16 (the user's 3840x1608 film). Intra and inter
1562// paths share the counter.
1563thread_local! {
1564 static EDGE_RECT_STRIP_HITS: std::cell::Cell<usize> =
1565 const { std::cell::Cell::new(0) };
1566}
1567
1568/// Current value of [`EDGE_RECT_STRIP_HITS`].
1569#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
1570pub(crate) fn edge_rect_strip_hits() -> usize {
1571 EDGE_RECT_STRIP_HITS.with(|c| c.get())
1572}
1573
1574// lane-interedge r1: frame-edge half strips on the INTER path, per partition
1575// level (64/32/16) x axis (HORZ at a bottom edge, VERT at a right edge). The
1576// index is `level_idx * 2 + axis` with `level_idx` 0=64, 1=32, 2=16 and
1577// `axis` 0=HORZ (`!has_rows`), 1=VERT (`!has_cols`). Both of the user's films
1578// are height mod 16 == 8, so every inter frame crosses these nodes.
1579thread_local! {
1580 static INTER_EDGE_STRIP_HITS: std::cell::Cell<[usize; 6]> =
1581 const { std::cell::Cell::new([0; 6]) };
1582}
1583
1584/// Bumps one bucket of [`INTER_EDGE_STRIP_HITS`].
1585pub(crate) fn bump_inter_edge_strip(idx: usize) {
1586 hit_do! {
1587 INTER_EDGE_STRIP_HITS.with(|c| {
1588 let mut v = c.get();
1589 v[idx] += 1;
1590 c.set(v);
1591 });
1592 }
1593}
1594
1595// lane-edgeboth r1: how many partition nodes were coded as the BOTH-AXES-CUT
1596// forced split -- libaom `decode_partition` (decodeframe.c):
1597// `else if (!has_rows && !has_cols) partition = PARTITION_SPLIT;`, the one
1598// straddle case that reads NO symbol at all. Indexed by level:
1599// 0 = 16x16, 1 = 32x32, 2 = 64x64, 3 = 128x128; intra and inter share it.
1600thread_local! {
1601 static EDGE_BOTH_CUT_HITS: std::cell::Cell<[usize; 4]> =
1602 const { std::cell::Cell::new([0; 4]) };
1603}
1604
1605fn bump_edge_both_cut(level: usize) {
1606 hit_do! {
1607 EDGE_BOTH_CUT_HITS.with(|c| {
1608 let mut v = c.get();
1609 v[level] += 1;
1610 c.set(v);
1611 });
1612 }
1613}
1614
1615/// Current value of [`INTER_EDGE_STRIP_HITS`] (`[h64, v64, h32, v32, h16, v16]`).
1616pub fn inter_edge_strip_hits() -> [usize; 6] {
1617 INTER_EDGE_STRIP_HITS.with(|c| c.get())
1618}
1619
1620/// Resets [`INTER_EDGE_STRIP_HITS`] -- a refused attempt must not carry hits
1621/// into the next one (class `counter-from-refused-stream`).
1622pub fn reset_inter_edge_strip_hits() {
1623 INTER_EDGE_STRIP_HITS.with(|c| c.set([0; 6]));
1624}
1625
1626/// Current value of [`EDGE_BOTH_CUT_HITS`] (`[16, 32, 64, 128]` levels).
1627#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1628pub(crate) fn edge_both_cut_hits() -> [usize; 4] {
1629 EDGE_BOTH_CUT_HITS.with(|c| c.get())
1630}
1631
1632/// Zeroes [`EDGE_BOTH_CUT_HITS`] so a gate can measure a per-attempt delta.
1633#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1634pub(crate) fn reset_edge_both_cut_hits() {
1635 EDGE_BOTH_CUT_HITS.with(|c| c.set([0; 4]));
1636}
1637
1638// How many HORZ/VERT intra strips resolved a SPLIT luma transform
1639// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) --
1640// the case every rect path here refused by name before, and the first
1641// refusal the user's ReelB extract (600s in) stops at.
1642thread_local! {
1643 static RECT_SPLIT_TX_HITS: std::cell::Cell<usize> =
1644 const { std::cell::Cell::new(0) };
1645}
1646
1647/// Current value of [`RECT_SPLIT_TX_HITS`].
1648#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1649pub(crate) fn rect_split_tx_hits() -> usize {
1650 RECT_SPLIT_TX_HITS.with(|c| c.get())
1651}
1652
1653// The subset of [`RECT_SPLIT_TX_HITS`] that is BOTH superblock-level (one
1654// side 64) AND split past the first depth, i.e. tiled more than one unit in
1655// each axis -- the only shape with a transform unit that has neighbours on
1656// two sides inside its own strip (`row_off > 0 && col_off > 0`), and the one
1657// no gate fired before lane-rectsplit r2 (the shared counter above also
1658// counts 32x32-level and depth-1 strips, so it cannot prove this case).
1659thread_local! {
1660 static RECT_SPLIT_SB_INTERIOR_TU_HITS: std::cell::Cell<usize> =
1661 const { std::cell::Cell::new(0) };
1662}
1663
1664/// Current value of [`RECT_SPLIT_SB_INTERIOR_TU_HITS`].
1665#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1666pub(crate) fn rect_split_sb_interior_tu_hits() -> usize {
1667 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.get())
1668}
1669
1670// Per-shape hit counts for the rect chroma transforms lane-rectchroma r1
1671// wired into [`decode_rect_split`] -- the shapes a split-transform strip's
1672// chroma half takes that had no coefficient tables before (index order:
1673// 32x8, 8x32, 8x4, 4x8). One counter per shape because a gate that only
1674// proves the pair it happens to hit cannot catch a transposed scan/context
1675// table (class scan-weights-cross-axis).
1676thread_local! {
1677 static RECT_SPLIT_CHROMA_SHAPE_HITS: std::cell::Cell<[usize; 4]> =
1678 const { std::cell::Cell::new([0; 4]) };
1679}
1680
1681/// Current value of [`RECT_SPLIT_CHROMA_SHAPE_HITS`] (32x8, 8x32, 8x4, 4x8).
1682#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1683pub(crate) fn rect_split_chroma_shape_hits() -> [usize; 4] {
1684 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| c.get())
1685}
1686
1687// How many HORZ/VERT intra strips actually predicted with filter intra
1688// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name
1689// ("this decoder predicts square-only") until `predict_filter_intra` took
1690// `bw`x`bh`.
1691thread_local! {
1692 static FILTER_INTRA_RECT_HITS: std::cell::Cell<usize> =
1693 const { std::cell::Cell::new(0) };
1694}
1695
1696/// Current value of [`FILTER_INTRA_RECT_HITS`].
1697#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1698pub(crate) fn filter_intra_rect_hits() -> usize {
1699 FILTER_INTRA_RECT_HITS.with(|c| c.get())
1700}
1701
1702// As [`FILTER_INTRA_RECT_HITS`], counting only the 32x32-level 1:4 strips
1703// (32x8/8x32, lane-fi32x8 r1) -- the shapes whose `use_filter_intra` symbol
1704// was never read at all before that round, so a gate needs to prove the flag
1705// fired at THAT shape and not at a 16x8 one somewhere else in the frame.
1706// Split by ORIENTATION: rows 8 (32x8) and 9 (8x32) of `cdf::FILTER_INTRA`
1707// carry different probabilities (18101 vs 20229), so a transposed pair is
1708// only caught by a gate that sees the flag fire on BOTH shapes (class
1709// scan-weights-cross-axis).
1710thread_local! {
1711 static FILTER_INTRA_RECT4_HORZ_HITS: std::cell::Cell<usize> =
1712 const { std::cell::Cell::new(0) };
1713 static FILTER_INTRA_RECT4_VERT_HITS: std::cell::Cell<usize> =
1714 const { std::cell::Cell::new(0) };
1715}
1716
1717/// Current value of [`FILTER_INTRA_RECT4_HORZ_HITS`] (32x8 strips).
1718#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1719pub(crate) fn filter_intra_rect4_horz_hits() -> usize {
1720 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.get())
1721}
1722
1723/// Current value of [`FILTER_INTRA_RECT4_VERT_HITS`] (8x32 strips).
1724#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1725pub(crate) fn filter_intra_rect4_vert_hits() -> usize {
1726 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.get())
1727}
1728
1729// How many rectangular transform units actually coded coefficients through
1730// [`read_coeffs_rect`] (`all_zero == 0`) -- lane-rect1d's measure that a gate
1731// exercised the rect coefficient reader at all rather than passing on
1732// all-skip blocks.
1733thread_local! {
1734 static RECT_COEFF_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1735 static RECT_CLASS1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1736}
1737
1738/// Current value of [`RECT_COEFF_TU_HITS`].
1739#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1740pub(crate) fn rect_coeff_tu_hits() -> usize {
1741 RECT_COEFF_TU_HITS.with(|c| c.get())
1742}
1743
1744/// Rectangular transform units whose resolved `tx_type` is a 1D class
1745/// (`V_DCT`/`H_DCT`) -- [`TX_CLASS1_HITS`]'s rect-only half, so a gate can
1746/// pin that the 1D-class-on-a-RECT-transform path fired rather than settling
1747/// for the square reader's own 1D types.
1748#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1749pub(crate) fn rect_class1_hits() -> usize {
1750 RECT_CLASS1_HITS.with(|c| c.get())
1751}
1752
1753// As [`FILTER_INTRA_RECT_HITS`], counting only the strips BELOW 16x16
1754// (8x16/16x8 leaves of a 16x16 HORZ/VERT partition, lane-fistrip r1) -- the
1755// shapes whose `use_filter_intra` symbol had no CDF class before this round.
1756// A gate asserting the wider counter would be satisfied by a 32x16 strip and
1757// prove nothing about the new shapes.
1758thread_local! {
1759 static FILTER_INTRA_RECT_SUB16_HITS: std::cell::Cell<usize> =
1760 const { std::cell::Cell::new(0) };
1761}
1762
1763/// Current value of [`FILTER_INTRA_RECT_SUB16_HITS`].
1764#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1765pub(crate) fn filter_intra_rect_sub16_hits() -> usize {
1766 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.get())
1767}
1768
1769// As [`FILTER_INTRA_RECT_SUB16_HITS`], one partition level further down:
1770// 4x8/8x4 leaves of an 8x8 HORZ/VERT (lane-fi8 r1). A gate on the sub16
1771// counter would be satisfied by a 16x8 strip and prove nothing here.
1772thread_local! {
1773 static FILTER_INTRA_RECT_SUB8_HITS: std::cell::Cell<usize> =
1774 const { std::cell::Cell::new(0) };
1775}
1776
1777/// Current value of [`FILTER_INTRA_RECT_SUB8_HITS`].
1778#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1779pub(crate) fn filter_intra_rect_sub8_hits() -> usize {
1780 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.get())
1781}
1782
1783// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
1784// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
1785// call on the current thread -- the same before/after counter pattern as
1786// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
1787// `eob_pt`/1D-neighbour context path rather than every block coincidentally
1788// landing on `DCT_DCT`.
1789thread_local! {
1790 static TX_CLASS1_HITS: std::cell::Cell<usize> =
1791 const { std::cell::Cell::new(0) };
1792}
1793
1794// How many `uv_mode` reads resolved to a directional chroma mode (neither
1795// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
1796// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1797// actually exercised chroma's own directional predictor.
1798thread_local! {
1799 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
1800 const { std::cell::Cell::new(0) };
1801}
1802
1803/// Current value of [`DIRECTIONAL_UV_HITS`].
1804#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1805pub(crate) fn directional_uv_hits() -> usize {
1806 DIRECTIONAL_UV_HITS.with(|c| c.get())
1807}
1808
1809// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
1810// something other than [`ANGLE_DELTA_ZERO`], across every call in the
1811// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
1812// proving a stream actually exercised a nonzero angle delta.
1813thread_local! {
1814 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
1815 const { std::cell::Cell::new(0) };
1816}
1817
1818// How many [`read_single_ref`] reads resolved to a reference other than
1819// `LAST_FRAME`, across every call on the current thread -- the same before/after
1820// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1821// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
1822// only other supported one so far) rather than every block coincidentally
1823// resolving `LAST_FRAME`.
1824thread_local! {
1825 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
1826 const { std::cell::Cell::new(0) };
1827}
1828
1829/// Current value of [`NON_LAST_REF_HITS`].
1830#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1831pub(crate) fn non_last_ref_hits() -> usize {
1832 NON_LAST_REF_HITS.with(|c| c.get())
1833}
1834
1835// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
1836// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
1837// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
1838// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
1839// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
1840// `GOLDEN_FRAME` draw it did not ask for.
1841thread_local! {
1842 static LAST2_HITS: std::cell::Cell<usize> =
1843 const { std::cell::Cell::new(0) };
1844}
1845thread_local! {
1846 static LAST3_HITS: std::cell::Cell<usize> =
1847 const { std::cell::Cell::new(0) };
1848}
1849thread_local! {
1850 static GOLDEN_HITS: std::cell::Cell<usize> =
1851 const { std::cell::Cell::new(0) };
1852}
1853thread_local! {
1854 static BWDREF_HITS: std::cell::Cell<usize> =
1855 const { std::cell::Cell::new(0) };
1856}
1857thread_local! {
1858 static ALTREF2_HITS: std::cell::Cell<usize> =
1859 const { std::cell::Cell::new(0) };
1860}
1861thread_local! {
1862 static ALTREF_HITS: std::cell::Cell<usize> =
1863 const { std::cell::Cell::new(0) };
1864}
1865
1866// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
1867// -- proves a `reference_select` stream actually reached a block that picked
1868// compound, not just that the header bit was set. Every such block is
1869// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
1870// so this only ever counts attempted reads, never a completed decode.
1871thread_local! {
1872 static COMP_MODE_HITS: std::cell::Cell<usize> =
1873 const { std::cell::Cell::new(0) };
1874}
1875
1876/// Current value of [`COMP_MODE_HITS`].
1877#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1878pub(crate) fn comp_mode_hits() -> usize {
1879 COMP_MODE_HITS.with(|c| c.get())
1880}
1881
1882// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
1883// use for, across every call on the current thread -- the same before/after
1884// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1885// exercised palette reconstruction rather than only reading and refusing the
1886// `palette_y_mode` symbol.
1887thread_local! {
1888 static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1889}
1890
1891/// Current value of [`PALETTE_HITS`].
1892#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1893pub(crate) fn palette_hits() -> usize {
1894 PALETTE_HITS.with(|c| c.get())
1895}
1896
1897// lane-tiles r12: of those, how many sat at their own TILE's left column --
1898// exactly the blocks whose palette cache/ctx must NOT see the previous tile's
1899// colours (`av1_get_palette_cache`'s `xd->left_mbmi == NULL`). A multi-tile
1900// palette gate that never hits one proves nothing about the tile guard.
1901thread_local! {
1902 static PALETTE_TILE_LEFT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1903}
1904
1905/// Current value of [`PALETTE_TILE_LEFT_HITS`].
1906#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1907pub(crate) fn palette_tile_left_hits() -> usize {
1908 PALETTE_TILE_LEFT_HITS.with(|c| c.get())
1909}
1910
1911// lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma
1912// palette use -- proves a stream actually reconstructed UV palette pixels,
1913// not just read and refused the `palette_uv_mode` symbol.
1914thread_local! {
1915 static PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1916}
1917
1918/// Current value of [`PALETTE_UV_HITS`].
1919#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1920pub(crate) fn palette_uv_hits() -> usize {
1921 PALETTE_UV_HITS.with(|c| c.get())
1922}
1923
1924// lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`])
1925// decoded a real palette-Y use -- proves the rect strip's own palette syntax
1926// (not just the square path's) actually fired.
1927thread_local! {
1928 static PALETTE_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1929}
1930
1931/// Current value of [`PALETTE_RECT_HITS`].
1932#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1933pub(crate) fn palette_rect_hits() -> usize {
1934 PALETTE_RECT_HITS.with(|c| c.get())
1935}
1936
1937// lane-palette2 r6: how many HORZ/VERT rect intra strips ran the
1938// [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] --
1939// i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in
1940// range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per
1941// RD, almost always refused-on-use because the block doesn't end up USING a
1942// palette -- see r5's report). This is the site the removed refusal
1943// ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it
1944// fired here whether or not the block picked a palette, so this is the
1945// counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost
1946// never observes.
1947thread_local! {
1948 static RECT_SCREEN_CONTENT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1949}
1950
1951/// Current value of [`RECT_SCREEN_CONTENT_HITS`].
1952#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1953pub(crate) fn rect_screen_content_hits() -> usize {
1954 RECT_SCREEN_CONTENT_HITS.with(|c| c.get())
1955}
1956
1957// lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a
1958// split luma transform (`logical_tx != side`) -- proves the per-TU index-map
1959// windowing actually ran, not just that the whole-block path stayed exact.
1960// Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16);
1961// first actually incremented in r7, when the refusal it guarded was lifted.
1962thread_local! {
1963 static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1964}
1965
1966thread_local! {
1967 /// lane-kf900 r4: rect intra strips that ACTUALLY use a palette -- the
1968 /// 1:4 shapes (32x8/8x32, 16x4/4x16) and the sub-16x16 2:1 leaves
1969 /// (16x8/8x16), the two shapes the lifted refusals named.
1970 static RECT4_PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1971}
1972
1973/// Current value of [`RECT4_PALETTE_HITS`].
1974#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1975pub(crate) fn rect4_palette_hits() -> usize {
1976 RECT4_PALETTE_HITS.with(|c| c.get())
1977}
1978
1979/// Current value of [`PALETTE_SPLIT_TX_HITS`].
1980#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1981pub(crate) fn palette_split_tx_hits() -> usize {
1982 PALETTE_SPLIT_TX_HITS.with(|c| c.get())
1983}
1984
1985thread_local! {
1986 /// lane-pal8 r1: square 8x8 LEAVES ([`decode_leaf8`]) that actually use a
1987 /// palette (Y or UV) -- the shape every 8-bit `--tune-content=screen`
1988 /// stream stopped on, since aomenc palettes square blocks at 8 bit and
1989 /// `--min-partition-size=8` puts them on this leaf path.
1990 static PALETTE_LEAF8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1991}
1992
1993/// Current value of [`PALETTE_LEAF8_HITS`].
1994#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1995pub(crate) fn palette_leaf8_hits() -> usize {
1996 PALETTE_LEAF8_HITS.with(|c| c.get())
1997}
1998
1999/// Zeroes [`PALETTE_LEAF8_HITS`] (per-attempt gate counting).
2000#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2001pub(crate) fn reset_palette_leaf8_hits() {
2002 PALETTE_LEAF8_HITS.with(|c| c.set(0));
2003}
2004
2005thread_local! {
2006 /// lane-pal8 r1: NON-SKIP palette blocks on a superblock-level (64-level)
2007 /// HORZ/VERT or 1:4 strip ([`decode_block_rect64`]) -- i.e. a palette
2008 /// block that also carries a real, corner-cropped luma transform.
2009 static PALETTE_SB_STRIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2010}
2011
2012/// Current value of [`PALETTE_SB_STRIP_HITS`].
2013#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2014pub(crate) fn palette_sb_strip_hits() -> usize {
2015 PALETTE_SB_STRIP_HITS.with(|c| c.get())
2016}
2017
2018/// Zeroes [`PALETTE_SB_STRIP_HITS`] (per-attempt gate counting).
2019#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2020pub(crate) fn reset_palette_sb_strip_hits() {
2021 PALETTE_SB_STRIP_HITS.with(|c| c.set(0));
2022}
2023
2024// lane-t900 r22: palette blocks reconstructed inside an INTER frame (the
2025// intra-in-inter path, `decode_inter_block`/`decode_inter_block8`) -- counted
2026// apart from [`PALETTE_HITS`] so a witness gate can prove the INTER-frame
2027// capability rather than the key frame's, which every screen stream also
2028// carries.
2029thread_local! {
2030 static INTRA_IN_INTER_PALETTE_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2031 static INTRA_IN_INTER_PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2032}
2033
2034// lane-t900 r23: as [`INTRA_IN_INTER_PALETTE_Y_HITS`], narrowed to the 8x8
2035// LEAF site ([`decode_inter_block8`]'s intra arm) -- the >=16 site fires the
2036// shared counter too, so only this one proves a gate really reached the leaf
2037// where the refusal used to sit.
2038thread_local! {
2039 static INTER8_PALETTE_HITS: std::cell::Cell<(usize, usize)> =
2040 const { std::cell::Cell::new((0, 0)) };
2041}
2042
2043/// Current values of the 8x8-leaf intra-in-inter palette counters, `(y, uv)`.
2044pub(crate) fn inter8_palette_hits() -> (usize, usize) {
2045 INTER8_PALETTE_HITS.with(std::cell::Cell::get)
2046}
2047
2048/// Current values of the two intra-in-inter palette counters, `(y, uv)`.
2049pub(crate) fn intra_in_inter_palette_hits() -> (usize, usize) {
2050 (
2051 INTRA_IN_INTER_PALETTE_Y_HITS.with(|c| c.get()),
2052 INTRA_IN_INTER_PALETTE_UV_HITS.with(|c| c.get()),
2053 )
2054}
2055
2056// lane-hgkf r2: SKIPPED intra blocks whose `tx_depth` split the luma transform
2057// and which are therefore predicted one transform unit at a time (a skipped
2058// block codes no coefficients, so nothing else in the stream witnesses this
2059// path -- only the pixels do).
2060thread_local! {
2061 static SKIP_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2062}
2063
2064/// Current value of [`SKIP_SPLIT_TX_HITS`] (blocks, not units).
2065pub fn skip_split_tx_hits() -> usize {
2066 SKIP_SPLIT_TX_HITS.with(|c| c.get())
2067}
2068
2069/// Zeroes [`SKIP_SPLIT_TX_HITS`] before a gate's own decode attempt.
2070pub fn reset_skip_split_tx_hits() {
2071 SKIP_SPLIT_TX_HITS.with(|c| c.set(0));
2072}
2073
2074// lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth`
2075// symbol split their luma transform, bucketed by block side (8, 16, 32, 64) --
2076// the gate's proof that the lifted path actually ran, per size.
2077thread_local! {
2078 static INTRA_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 4]> =
2079 const { std::cell::Cell::new([0; 4]) };
2080}
2081
2082/// Current value of [`INTRA_IN_INTER_SPLIT_TX_HITS`], indexed 8/16/32/64.
2083#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2084pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] {
2085 INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
2086}
2087
2088 /// A just-decoded palette-Y block's own predicted pixels
2089 /// (`side*side`, row-major, `colors[map[i]]`), consumed by
2090 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
2091 /// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
2092 /// per-block override through `read_plane`'s two dozen call sites is the
2093 /// alternative this avoids). Always empty again once that call consumes
2094 /// it (`.take()`), so a non-palette block's own `reconstruct` call never
2095 /// sees stale state.
2096
2097
2098/// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
2099/// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a
2100/// site whose reconstruct never runs would be picked up by the NEXT block's
2101/// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
2102/// lane-lossless2: one transform unit's window on a block-sized palette
2103/// prediction buffer. A unit reads its prediction at ITS OWN stride, so
2104/// handing it the whole-block buffer makes every unit reconstruct the block's
2105/// top-left corner (the luma split-transform paths already window; the chroma
2106/// ones did not, which is invisible until a lossless frame codes a palette
2107/// block as 4x4 chroma units).
2108fn palette_window(buf: &[u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize) -> Vec<u16> {
2109 (0..h)
2110 .flat_map(|r| buf[(oy + r) * stride + ox..][..w].iter().copied())
2111 .collect()
2112}
2113
2114/// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
2115#[track_caller]
2116fn set_palette_pred(buf: Vec<u16>, fctx: &crate::decode::FrameCtx) {
2117 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
2118 let stale = fctx.palette_pred.with(|c| c.borrow().is_some());
2119 eprintln!(
2120 "PALSET len={} stale={stale} at {}",
2121 buf.len(),
2122 std::panic::Location::caller()
2123 );
2124 }
2125 fctx.palette_pred.with(|c| *c.borrow_mut() = Some(buf));
2126}
2127
2128#[track_caller]
2129fn take_palette_pred(fctx: &crate::decode::FrameCtx) -> Option<Vec<u16>> {
2130 let got = fctx.palette_pred.with(|c| c.borrow_mut().take());
2131 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
2132 eprintln!(
2133 "PALTAKE len={:?} at {}",
2134 got.as_ref().map(Vec::len),
2135 std::panic::Location::caller()
2136 );
2137 }
2138 got
2139}
2140
2141/// The luma window a `UV_CFL_PRED` chroma block averages its AC signal over
2142/// (lane-wave1 step (i)). Parse records the window; [`flush_recon`] reads the
2143/// pixels, because at parse time this block's own luma is still queued.
2144#[derive(Clone, Copy, Debug)]
2145pub(crate) struct CflSrc {
2146 px: usize,
2147 py: usize,
2148 bw: usize,
2149 bh: usize,
2150 /// Which averager the parse site asked for -- [`cfl_ac_q3_rect`] and
2151 /// [`cfl_ac_q3`] are not the same function at `bw == bh`.
2152 rect: bool,
2153}
2154
2155fn cfl_src(px: usize, py: usize, side: usize) -> CflSrc {
2156 CflSrc { px, py, bw: side, bh: side, rect: false }
2157}
2158
2159fn cfl_src_rect(px: usize, py: usize, bw: usize, bh: usize) -> CflSrc {
2160 CflSrc { px, py, bw, bh, rect: true }
2161}
2162
2163/// lane-wave1 step (i): the pixel-writing half of block decoding, recorded
2164/// instead of executed. Each variant is the resolved argument tuple of the
2165/// `PlaneBuf::reconstruct*` call it replaces, so replaying the queue in push
2166/// order performs exactly the same writes in exactly the same order --
2167/// entropy parsing no longer touches the frame's own planes (except the two
2168/// sites named in [`flush_recon`]'s doc), which is what lets step (ii) run
2169/// the replay on a superblock-row wavefront worker.
2170/// The dequantization + inverse transform of one transform unit, kept as its
2171/// INPUTS so that a recorded write carries the work instead of its result
2172/// (lane-wave3): at `EC_AV1_RECON_THREADS > 1` the transform then runs on the
2173/// recon worker, not on the parsing thread. `stride == 0` means the dense
2174/// `w x h` residual; otherwise it is re-laid into the `stride x stride` grid
2175/// `reconstruct_mc_rect` reads both of its buffers at.
2176#[derive(Clone, Copy)]
2177pub(crate) struct TxParams {
2178 pub(crate) w: usize,
2179 pub(crate) h: usize,
2180 pub(crate) bit_depth: u8,
2181 pub(crate) q_idx: i32,
2182 pub(crate) dc_delta: i32,
2183 pub(crate) ac_delta: i32,
2184 pub(crate) tx_type: TxType,
2185 pub(crate) stride: usize,
2186 /// lane-lossless: this transform unit belongs to a lossless frame, so the
2187 /// residual comes off the 4x4 Walsh-Hadamard
2188 /// ([`crate::transform::dequant_and_inverse_wht4x4`]) instead of the
2189 /// DCT/ADST network (libaom `inv_txfm_add`, `av1/common/idct.c`).
2190 pub(crate) lossless: bool,
2191}
2192
2193impl TxParams {
2194 /// The one copy of the produce-the-residual code: the inline path calls it
2195 /// on the parse thread, the wavefront worker calls it on its own, so both
2196 /// are the same function on the same inputs and byte-identical.
2197 fn run(self, grid: &[i32]) -> Vec<i32> {
2198 let residual = if self.lossless {
2199 debug_assert_eq!((self.w, self.h), (4, 4));
2200 debug_assert_eq!(self.tx_type, TxType::DctDct);
2201 crate::transform::dequant_and_inverse_wht4x4(
2202 grid, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta,
2203 )
2204 } else {
2205 dequant_and_inverse_typed_wh(
2206 grid, self.w, self.h, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta,
2207 self.tx_type,
2208 )
2209 };
2210 // An all-zero grid transforms to the empty marker, and a strided copy
2211 // of zeros is still zeros: the marker passes straight through.
2212 if residual.is_empty() {
2213 return residual;
2214 }
2215 if self.stride == 0 {
2216 return residual;
2217 }
2218 let mut strided = vec![0i32; self.stride * self.stride];
2219 for row in 0..self.h {
2220 strided[row * self.stride..][..self.w]
2221 .copy_from_slice(&residual[row * self.w..][..self.w]);
2222 }
2223 strided
2224 }
2225}
2226
2227/// A recorded write's residual: already transformed, or the coefficients and
2228/// [`TxParams`] the worker transforms itself.
2229pub(crate) enum Residual {
2230 /// An already-transformed residual in the arena, `(offset, len)`; a zero
2231 /// `len` is the all-zero marker [`dense_residual`] expands.
2232 Done(u32, u32),
2233 /// The coefficients live in the pushing tile's arena
2234 /// ([`crate::decode::FrameCtx::coeff_arena`]); this is their `(offset,
2235 /// len)` in it.
2236 Coeffs(TxParams, u32, u32),
2237}
2238
2239impl Residual {
2240 /// The record for a transform unit whose coefficient grid is all zero:
2241 /// the empty marker, so neither the grid nor the residual is cloned and
2242 /// the worker never runs the transform (60% of the 4K segment's units).
2243 fn coeffs(tx: TxParams, grid: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
2244 if is_zero_grid(grid) {
2245 return Self::Done(0, 0);
2246 }
2247 Self::Coeffs(tx, push_coeffs(grid, fctx), grid.len() as u32)
2248 }
2249
2250 /// A residual the parse thread already transformed, kept in the arena
2251 /// instead of its own `Vec`.
2252 fn done(residual: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
2253 // lane-blockmem: a skipped block hands over [`ZERO_RESIDUAL`] itself,
2254 // which is exactly the all-zero marker -- one pointer compare instead
2255 // of copying up to 64 KB of zeros into the arena per block.
2256 if std::ptr::eq(residual.as_ptr(), ZERO_RESIDUAL.as_ptr()) {
2257 return Self::Done(0, 0);
2258 }
2259 Self::Done(push_coeffs(residual, fctx), residual.len() as u32)
2260 }
2261
2262 /// The residual to reconstruct with; `scratch` is where a transform run
2263 /// on this thread lands, so the caller owns that buffer.
2264 fn resolve<'a>(self, arena: &'a [i32], scratch: &'a mut Vec<i32>) -> &'a [i32] {
2265 match self {
2266 Self::Done(off, len) => &arena[off as usize..][..len as usize],
2267 Self::Coeffs(p, off, len) => {
2268 *scratch = p.run(&arena[off as usize..][..len as usize]);
2269 scratch
2270 }
2271 }
2272 }
2273}
2274
2275/// Appends to the tile's coefficient arena, returning the offset the record
2276/// carries; see [`crate::decode::FrameCtx::coeff_arena`].
2277fn push_coeffs(v: &[i32], fctx: &crate::decode::FrameCtx) -> u32 {
2278 fctx.coeff_arena.with(|a| {
2279 let mut a = a.borrow_mut();
2280 let off = a.len();
2281 a.extend_from_slice(v);
2282 off as u32
2283 })
2284}
2285
2286/// [`push_coeffs`] for a recorded prediction.
2287fn push_pred_samples(v: &[u16], fctx: &crate::decode::FrameCtx) -> u32 {
2288 fctx.pred_arena.with(|a| {
2289 let mut a = a.borrow_mut();
2290 let off = a.len();
2291 a.extend_from_slice(v);
2292 off as u32
2293 })
2294}
2295
2296/// An all-zero residual, for the transform units that code no coefficient:
2297/// [`crate::transform::dequant_and_inverse_typed_wh`] returns those EMPTY,
2298/// and the reconstruction loops below read this instead of a per-unit
2299/// `vec![0; w * h]`. Sized for the largest stride a recorded unit can carry
2300/// (a 128-wide inter block's prediction stride).
2301pub(crate) static ZERO_RESIDUAL: [i32; 128 * 128] = [0; 128 * 128];
2302
2303/// lane-blockscratch: one plane's coefficient levels as the block-tail
2304/// neighbour writes want them. A plane that coded nothing (a skipped block, a
2305/// strip with no chroma, luma under a var-tx split whose units already wrote
2306/// themselves) names the shared [`ZERO_RESIDUAL`] instead of allocating and
2307/// zeroing up to 64 KB of its own per block.
2308#[derive(Clone)]
2309enum Grid {
2310 Zero(usize),
2311 Own(Vec<i32>),
2312}
2313
2314/// lane-blockscratch: the mu-chunk chroma collector, allocated by the first
2315/// unit that writes into it. Only a block wider or taller than 64 px codes its
2316/// chroma per 64x64 chunk; every smaller block used to allocate and zero both
2317/// collectors per block and then drop them untouched.
2318fn mu_units(v: &mut Vec<i32>, n: usize) -> &mut Vec<i32> {
2319 if v.is_empty() {
2320 *v = vec![0i32; n];
2321 }
2322 v
2323}
2324
2325impl std::ops::Deref for Grid {
2326 type Target = [i32];
2327 fn deref(&self) -> &[i32] {
2328 match self {
2329 Grid::Zero(n) => &ZERO_RESIDUAL[..*n],
2330 Grid::Own(v) => v,
2331 }
2332 }
2333}
2334
2335/// Whether a coefficient grid codes nothing: a [`Grid::Zero`] unit IS the
2336/// shared [`ZERO_RESIDUAL`], so one pointer compare answers the 60% of
2337/// transform units that code no coefficient without the scan (lane-coefgrid).
2338pub(crate) fn is_zero_grid(grid: &[i32]) -> bool {
2339 std::ptr::eq(grid.as_ptr(), ZERO_RESIDUAL.as_ptr()) || grid.iter().all(|&c| c == 0)
2340}
2341
2342/// `residual`, or `n` zeros when it is the empty all-zero marker.
2343fn dense_residual(residual: &[i32], n: usize) -> &[i32] {
2344 if residual.is_empty() { &ZERO_RESIDUAL[..n] } else { residual }
2345}
2346
2347/// Where a recorded motion-compensated write reads its prediction from.
2348///
2349/// lane-wave4: a block's whole-block prediction (mc + warp + interintra) is
2350/// the parse thread's single biggest reconstruction cost, so at
2351/// `EC_AV1_RECON_THREADS > 1` it is not built at parse at all: the block
2352/// pushes a [`ReconOp::Pred`] carrying the build as a closure, the worker
2353/// runs it into its own three-plane slot, and every transform unit of that
2354/// block then reads its window out of that slot ([`Pred::Cur`]).
2355#[derive(Clone, Copy)]
2356pub(crate) enum Pred<'a> {
2357 /// A prediction the parse thread already built, at its own stride
2358 /// (`stride == 0` means "the reader's own `stride` argument").
2359 Inline(&'a [u16], usize),
2360 /// The current block's deferred prediction: plane, its stride, and this
2361 /// unit's offset into it.
2362 Cur { plane: usize, stride: usize, off: usize },
2363}
2364
2365impl<'a> Pred<'a> {
2366 /// The same prediction read at an explicit stride.
2367 fn view(self, stride: usize) -> Self {
2368 match self {
2369 Self::Inline(b, _) => Self::Inline(b, stride),
2370 Self::Cur { plane, off, .. } => Self::Cur { plane, stride, off },
2371 }
2372 }
2373 /// The materialised buffer and the stride to read it at (`stride` is the
2374 /// reader's own when this prediction was built dense); `None` for a
2375 /// deferred prediction, which only a recorded op can carry.
2376 fn inline(self, stride: usize) -> Option<(&'a [u16], usize)> {
2377 match self {
2378 Self::Inline(b, s) => Some((b, if s == 0 { stride } else { s })),
2379 Self::Cur { .. } => None,
2380 }
2381 }
2382 /// This prediction's window starting `n` samples in.
2383 fn offset(self, n: usize) -> Self {
2384 match self {
2385 Self::Inline(b, s) => Self::Inline(&b[n..], s),
2386 Self::Cur { plane, stride, off } => Self::Cur { plane, stride, off: off + n },
2387 }
2388 }
2389}
2390
2391/// [`Pred`], resolved into what a recorded op carries.
2392pub(crate) enum PredSrc {
2393 /// A prediction window in the tile's prediction arena, `(offset, len)`.
2394 Owned(u32, u32),
2395 /// A window of the block prediction: its plane, its offset, and the
2396 /// stride it is read at -- which is the block's, not necessarily the
2397 /// op's (a transform unit's residual stays dense, so the worker takes
2398 /// its window out of the block prediction itself).
2399 Cur { plane: usize, off: usize, src: usize },
2400}
2401
2402/// One block's whole-block prediction build, deferred to a recon worker.
2403///
2404/// The closure borrows the tile's reference pictures and its own frame-level
2405/// tables; [`WaveGuard`] joins every worker before the tile decoder returns,
2406/// so those borrows outlive it -- the [`ReconPlanes`] trade-off, stated once
2407/// here for the closure's `'static`/`Send` laundering in [`push_pred`].
2408pub(crate) struct PredBuild(
2409 Box<
2410 dyn FnOnce(
2411 &mut PlaneBuf<'static>,
2412 &mut PlaneBuf<'static>,
2413 &mut PlaneBuf<'static>,
2414 &crate::decode::FrameCtx,
2415 // lane-blockmem: the previous block's three prediction buffers,
2416 // refilled in place -- the build used to return three fresh
2417 // `Vec`s per block and drop these.
2418 &mut [Vec<u16>; 3],
2419 ),
2420 >,
2421);
2422
2423// SAFETY: see [`PredBuild`] -- the captured borrows are read-only reference
2424// pictures and frame tables, and the closure runs on exactly one worker.
2425#[allow(unsafe_code)]
2426unsafe impl Send for PredBuild {}
2427
2428/// `true` when this tile's writes are recorded for the wavefront instead of
2429/// performed at the push site, i.e. when a prediction may be deferred.
2430fn recon_deferred(fctx: &crate::decode::FrameCtx) -> bool {
2431 fctx.recon_planes.with(std::cell::Cell::get).is_none()
2432}
2433
2434/// The previous block's prediction buffer, cleared and zero-filled to `n`
2435/// (lane-blockmem): the same bytes the `vec![0u16; n]` it replaces produced,
2436/// without the per-block allocation and free.
2437fn refill(mut v: Vec<u16>, n: usize) -> Vec<u16> {
2438 // A buffer that has to grow anyway is cheaper allocated zeroed (`calloc`)
2439 // than resized element by element -- which is every block on the inline
2440 // path, where there is no previous buffer to reuse.
2441 if v.capacity() < n {
2442 return vec![0u16; n];
2443 }
2444 v.clear();
2445 v.resize(n, 0);
2446 v
2447}
2448
2449/// Records one block's prediction build for the worker that reconstructs it.
2450#[allow(unsafe_code)]
2451fn push_pred<'a>(
2452 fctx: &crate::decode::FrameCtx,
2453 f: impl FnOnce(
2454 &mut PlaneBuf<'static>,
2455 &mut PlaneBuf<'static>,
2456 &mut PlaneBuf<'static>,
2457 &crate::decode::FrameCtx,
2458 &mut [Vec<u16>; 3],
2459 ) + 'a,
2460) {
2461 type Dyn<'x> = dyn FnOnce(
2462 &mut PlaneBuf<'static>,
2463 &mut PlaneBuf<'static>,
2464 &mut PlaneBuf<'static>,
2465 &crate::decode::FrameCtx,
2466 &mut [Vec<u16>; 3],
2467 ) + 'x;
2468 let boxed: Box<Dyn<'a>> = Box::new(f);
2469 // SAFETY: see [`PredBuild`] -- every worker is joined by [`WaveGuard`]
2470 // before the borrows the closure holds go out of scope.
2471 let boxed: Box<Dyn<'static>> = unsafe { std::mem::transmute(boxed) };
2472 push_op(fctx, ReconOp::Pred(PredBuild(boxed)));
2473}
2474
2475/// One superblock's recorded writes plus the two arenas they index -- the
2476/// unit a wavefront worker takes off the queue (lane-recoparse).
2477pub(crate) struct ReconJob {
2478 ops: Vec<ReconOp>,
2479 coeffs: Vec<i32>,
2480 preds: Vec<u16>,
2481}
2482
2483pub(crate) enum ReconOp {
2484 /// lane-wave4: build this block's prediction into the worker's slot.
2485 Pred(PredBuild),
2486 Intra {
2487 plane: usize,
2488 x: usize,
2489 y: usize,
2490 bw: usize,
2491 bh: usize,
2492 /// `true` when the parse site called `reconstruct_rect` (whose
2493 /// `edges_rect` differs from `edges` even at `bw == bh`).
2494 rect: bool,
2495 mode: usize,
2496 angle_delta: i32,
2497 reach: Reach,
2498 residual: Residual,
2499 cfl: Option<(i32, CflSrc)>,
2500 filter_intra: Option<usize>,
2501 smooth_neighbor: bool,
2502 /// The palette/intrabc prediction override, taken off
2503 /// [`FrameCtx::palette_pred`] at PUSH time (parse order), never read
2504 /// from that slot by the replay.
2505 pred: Option<Vec<u16>>,
2506 },
2507 Mc {
2508 plane: usize,
2509 x: usize,
2510 y: usize,
2511 stride: usize,
2512 w: usize,
2513 h: usize,
2514 prediction: PredSrc,
2515 residual: Residual,
2516 },
2517}
2518
2519/// The three planes of the tile currently being decoded, as raw pointers.
2520///
2521/// corner-cut: at one reconstruction thread a recorded write must cost
2522/// nothing -- deferring it to the end of the superblock is +1.2%
2523/// instructions and +4.5% wall on 4K, because the residual is written at
2524/// parse and read back cache-cold at replay. So the recorded op is performed
2525/// at the push site instead, through the pointers the tile decoder registers
2526/// once ([`ReconInline`]), which is the same thread, the same order and the
2527/// same writes as before lane-wave1 -- but the `&mut PlaneBuf` the parse
2528/// stack still holds aliases them, exactly the [`crate::par::Shared`]
2529/// trade-off (Miri's stacked borrows would flag both). The upgrade path is
2530/// threading the three planes down every `read_plane`/`read_inter_plane`
2531/// call site (~40) so the push site owns the borrow it writes through.
2532#[derive(Clone, Copy)]
2533pub(crate) struct ReconPlanes(
2534 *mut PlaneBuf<'static>,
2535 *mut PlaneBuf<'static>,
2536 *mut PlaneBuf<'static>,
2537);
2538
2539// SAFETY: a `FrameCtx` sent to another thread (a frame worker, or
2540// [`filter_ctx_copy`]) is always one whose guard is not installed, so the
2541// value travelling is `None`; the pointers never leave the tile decoder's
2542// own thread.
2543#[allow(unsafe_code)]
2544unsafe impl Send for ReconPlanes {}
2545// SAFETY: the wavefront's workers share one `ReconPlanes` and write provably
2546// disjoint superblocks of it (see [`WaveState`]) -- the [`crate::par::Shared`]
2547// contract, one superblock per band instead of one row band.
2548#[allow(unsafe_code)]
2549unsafe impl Sync for ReconPlanes {}
2550
2551/// Registers the tile's planes for inline reconstruction and unregisters them
2552/// on every exit from the tile decoder, including the `?` ones -- a stale
2553/// pointer here would outlive the planes, since [`FrameCtx`] outlives the
2554/// tile.
2555pub(crate) struct ReconInline<'a>(&'a crate::decode::FrameCtx);
2556
2557#[allow(unsafe_code)]
2558impl<'a> ReconInline<'a> {
2559 /// Installs the guard for this tile when reconstruction is inline
2560 /// (`EC_AV1_RECON_THREADS == 1`, the default); `None` hands every write
2561 /// to the queue instead, for the wavefront workers to replay.
2562 fn install(
2563 fctx: &'a crate::decode::FrameCtx,
2564 y: &mut PlaneBuf<'static>,
2565 u: &mut PlaneBuf<'static>,
2566 v: &mut PlaneBuf<'static>,
2567 ) -> Option<Self> {
2568 if crate::par::recon_threads() != 1 {
2569 return None;
2570 }
2571 // SAFETY: the planes are locals of the tile decoder and outlive the
2572 // guard, which is dropped on every exit from it (including `?`); see
2573 // [`ReconPlanes`] for the aliasing trade-off.
2574 let planes = ReconPlanes(
2575 std::ptr::from_mut(y),
2576 std::ptr::from_mut(u),
2577 std::ptr::from_mut(v),
2578 );
2579 fctx.recon_planes.with(|c| c.set(Some(planes)));
2580 Some(Self(fctx))
2581 }
2582}
2583
2584impl Drop for ReconInline<'_> {
2585 fn drop(&mut self) {
2586 self.0.recon_planes.with(|c| c.set(None));
2587 }
2588}
2589
2590#[allow(unsafe_code)]
2591fn push_op(fctx: &crate::decode::FrameCtx, op: ReconOp) {
2592 if let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) {
2593 // SAFETY: see [`ReconPlanes`] -- one thread, and the write is the one
2594 // the parse site would have performed itself before lane-wave1.
2595 // The inline path never records coefficients (the transform runs at
2596 // the push site), so the arena is not read here.
2597 unsafe {
2598 exec_op(op, &mut *y, &mut *u, &mut *v, &mut Default::default(), &[], &[], fctx)
2599 };
2600 return;
2601 }
2602 fctx.recon_ops.with(|c| c.borrow_mut().push(op));
2603}
2604
2605/// lane-wave1 step (ii): the superblock-row wavefront a tile's recorded
2606/// writes are reconstructed on when `EC_AV1_RECON_THREADS > 1`.
2607///
2608/// The parser keeps parsing and never touches the planes; each superblock's
2609/// drained `Vec<ReconOp>` becomes one job, keyed by the superblock's own
2610/// `(row, column)` inside the tile (128x128 superblocks are one job for all
2611/// four of their 64x64 visits, since a 128 block writes across quadrants).
2612/// A worker may start job `(r, c)` once `(r - 1, min(c + 1, last_col))` and
2613/// `(r, c - 1)` are complete -- the classic wavefront rule, which covers
2614/// every pixel an intra predictor can read (its edges reach one block right
2615/// along the row above and one block down the column to the left, both
2616/// inside those two neighbours) and every CfL AC read (this block's own
2617/// luma, written by this same job). Jobs are handed out in raster order, so
2618/// the oldest outstanding one always has its dependencies met: no deadlock.
2619///
2620/// Gate counters incremented inside `reconstruct*`/`intra`/`mc` are
2621/// `thread_local!` and miss every worker, which is why the default is 1.
2622pub(crate) struct WaveState {
2623 q: std::sync::Mutex<WaveQueue>,
2624 cv: std::sync::Condvar,
2625 planes: ReconPlanes,
2626 /// The two [`FrameCtx`] fields reconstruction reads (`sample_max` is
2627 /// `bit_depth`'s; everything else a `reconstruct*` needs is in the op).
2628 bit_depth: u8,
2629 enable_edge_filter: bool,
2630 last_col: usize,
2631}
2632
2633struct WaveQueue {
2634 /// Queued jobs per superblock ROW, in column order (lane-wave5). Only a
2635 /// row's front job can ever be runnable -- a job waits on its own left
2636 /// neighbour -- so a worker takes the lowest row whose front job's
2637 /// dependencies are met. Popping the raster-oldest job instead (what
2638 /// this replaced) put every worker on the SAME row, where the wavefront
2639 /// rule serialises them, which is why 4 workers ran the tile at 1.2x.
2640 rows: Vec<std::collections::VecDeque<(usize, ReconJob)>>,
2641 /// Jobs sitting in `rows`, so a worker knows the queue is empty without
2642 /// walking it.
2643 queued: usize,
2644 /// Per superblock row, the last column reconstructed (-1 = none yet).
2645 done: Vec<isize>,
2646 /// Per superblock row, the last column PARSED (submitted, whether or not
2647 /// it recorded any write) and the last column actually pushed as a job
2648 /// (-1 = none). A row is fully reconstructed once it has been parsed to
2649 /// `last_col` and `done` has caught up with `last_push` -- lane-pipefilt
2650 /// reads that to release the row's filters (see [`wave_rows_complete`]).
2651 last_sub: Vec<isize>,
2652 last_push: Vec<isize>,
2653 /// Jobs popped but not finished -- what [`wave_barrier`] waits out.
2654 active: usize,
2655 closed: bool,
2656 /// lane-sballoc: the three per-superblock buffers a finished job hands
2657 /// back, so [`wave_submit`] takes a warm allocation (capacity kept, no
2658 /// first-touch page faults) instead of the `Vec::with_capacity` it used
2659 /// to make per superblock -- 3 allocations and 3 frees per superblock,
2660 /// 4680 per 4K frame. Bounded at `recon_threads + 2` sets, and it lives
2661 /// inside the queue's own mutex, which both sides already take.
2662 free: Vec<JobBufs>,
2663 free_cap: usize,
2664}
2665
2666/// One recycled set of [`ReconJob`] buffers (lane-sballoc).
2667type JobBufs = (Vec<ReconOp>, Vec<i32>, Vec<u16>);
2668
2669impl WaveQueue {
2670 /// The lowest-row queued job whose wavefront dependencies are satisfied,
2671 /// or `None` (with the blocking condition counted when instrumented).
2672 fn take_runnable(
2673 &mut self,
2674 last_col: usize,
2675 stats: bool,
2676 ) -> Option<(usize, usize, ReconJob)> {
2677 let mut blocked: Option<bool> = None;
2678 for r in 0..self.rows.len() {
2679 let Some(front) = self.rows[r].front() else {
2680 continue;
2681 };
2682 let c = front.0;
2683 let above = r == 0 || self.done[r - 1] >= (c + 1).min(last_col) as isize;
2684 let left = c == 0 || self.done[r] >= c as isize - 1;
2685 if above && left {
2686 let (c, job) = self.rows[r].pop_front().expect("front checked above");
2687 self.queued -= 1;
2688 return Some((r, c, job));
2689 }
2690 if blocked.is_none() {
2691 blocked = Some(above);
2692 }
2693 }
2694 if stats {
2695 match blocked {
2696 Some(true) => WS_BLOCK_LEFT.fetch_add(1, Relaxed),
2697 Some(false) => WS_BLOCK_ABOVE.fetch_add(1, Relaxed),
2698 None => 0,
2699 };
2700 }
2701 None
2702 }
2703}
2704
2705/// lane-wave5 instrumentation, on `EC_AV1_WAVE_STATS=1`: where a recon
2706/// worker's time goes (busy replaying, waiting for a dependency, idle on an
2707/// empty queue), how far ahead the parse thread is, and how often the two
2708/// parse-time pixel reads barrier the wavefront. Cumulative for the process,
2709/// dumped by every [`WaveGuard`] drop, so the LAST line of a decode is the
2710/// whole run.
2711const WS_SLOTS: usize = 16;
2712use std::sync::atomic::AtomicU64;
2713use std::sync::atomic::Ordering::Relaxed;
2714static WS_JOBS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2715static WS_OPS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2716static WS_BUSY: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2717static WS_WAIT: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2718static WS_BLOCK_ABOVE: AtomicU64 = AtomicU64::new(0);
2719static WS_BLOCK_LEFT: AtomicU64 = AtomicU64::new(0);
2720/// Parse-thread time between two submits, i.e. everything parse still does
2721/// itself (symbol decode plus the predictions not deferred).
2722static WS_PARSE: AtomicU64 = AtomicU64::new(0);
2723/// Parse-thread time spent waiting for the wavefront: at [`wave_barrier`]
2724/// (the intrabc/interintra reads) and at the tile's end.
2725static WS_BARRIER: AtomicU64 = AtomicU64::new(0);
2726static WS_BARRIERS: AtomicU64 = AtomicU64::new(0);
2727static WS_DRAIN: AtomicU64 = AtomicU64::new(0);
2728static WS_TILES: AtomicU64 = AtomicU64::new(0);
2729
2730fn wave_stats() -> bool {
2731 static ON: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
2732 match ON.load(Relaxed) {
2733 0 => {
2734 let on = crate::envflags::var("EC_AV1_WAVE_STATS")
2735 .map(|v| v.trim() == "1")
2736 .unwrap_or(false);
2737 ON.store(1 + u8::from(on), Relaxed);
2738 on
2739 }
2740 n => n == 2,
2741 }
2742}
2743
2744fn wave_stats_dump() {
2745 let ms = |n: u64| n as f64 / 1e6;
2746 let mut s = format!("wave_stats tiles={}", WS_TILES.load(Relaxed));
2747 for i in 0..WS_SLOTS {
2748 let jobs = WS_JOBS[i].load(Relaxed);
2749 if jobs == 0 {
2750 continue;
2751 }
2752 s += &format!(
2753 " | w{i} jobs={jobs} ops/job={:.1} busy={:.0}ms wait={:.0}ms wait/job={:.0}us",
2754 WS_OPS[i].load(Relaxed) as f64 / jobs as f64,
2755 ms(WS_BUSY[i].load(Relaxed)),
2756 ms(WS_WAIT[i].load(Relaxed)),
2757 WS_WAIT[i].load(Relaxed) as f64 / jobs as f64 / 1e3,
2758 );
2759 }
2760 s += &format!(
2761 " | pipe={}/{}",
2762 PIPE_FRAMES.load(Relaxed),
2763 PIPE_FRAMES.load(Relaxed) + PIPE_WHOLE.load(Relaxed),
2764 );
2765 s += &format!(
2766 " | parse={:.0}ms barrier={:.0}ms/{} drain={:.0}ms block_above={} block_left={}",
2767 ms(WS_PARSE.load(Relaxed)),
2768 ms(WS_BARRIER.load(Relaxed)),
2769 WS_BARRIERS.load(Relaxed),
2770 ms(WS_DRAIN.load(Relaxed)),
2771 WS_BLOCK_ABOVE.load(Relaxed),
2772 WS_BLOCK_LEFT.load(Relaxed),
2773 );
2774 eprintln!("{s}");
2775}
2776
2777#[allow(unsafe_code)]
2778fn wave_worker(st: &WaveState, idx: usize) {
2779 let fctx = FrameCtx::new();
2780 fctx.bit_depth.set(st.bit_depth);
2781 fctx.enable_edge_filter.set(st.enable_edge_filter);
2782 let stats = wave_stats();
2783 let slot = idx.min(WS_SLOTS - 1);
2784 loop {
2785 let t0 = std::time::Instant::now();
2786 let mut q = st.q.lock().unwrap();
2787 let (r, c, job) = loop {
2788 if let Some(job) = q.take_runnable(st.last_col, stats) {
2789 break job;
2790 }
2791 if q.closed && q.queued == 0 {
2792 return;
2793 }
2794 q = st.cv.wait(q).unwrap();
2795 };
2796 q.active += 1;
2797 drop(q);
2798 if stats {
2799 WS_WAIT[slot].fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
2800 WS_JOBS[slot].fetch_add(1, Relaxed);
2801 WS_OPS[slot].fetch_add(job.ops.len() as u64, Relaxed);
2802 }
2803 let t1 = std::time::Instant::now();
2804 let ReconPlanes(y, u, v) = st.planes;
2805 // SAFETY: this job writes only superblock (r, c)'s own pixels, and
2806 // every superblock that could have written or be reading them is
2807 // complete by the wavefront rule above.
2808 let mut cur: [Vec<u16>; 3] = Default::default();
2809 let ReconJob { mut ops, mut coeffs, mut preds } = job;
2810 unsafe {
2811 for op in ops.drain(..) {
2812 exec_op(op, &mut *y, &mut *u, &mut *v, &mut cur, &coeffs, &preds, &fctx);
2813 }
2814 }
2815 if stats {
2816 WS_BUSY[slot].fetch_add(t1.elapsed().as_nanos() as u64, Relaxed);
2817 }
2818 coeffs.clear();
2819 preds.clear();
2820 let mut q = st.q.lock().unwrap();
2821 // lane-sballoc: hand the three buffers back for the next submit.
2822 if q.free.len() < q.free_cap {
2823 q.free.push((ops, coeffs, preds));
2824 }
2825 q.done[r] = c as isize;
2826 q.active -= 1;
2827 st.cv.notify_all();
2828 }
2829}
2830
2831/// Installs the wavefront for one tile and joins its workers on every exit
2832/// from the tile decoder, including the `?` ones -- the jobs hold raw
2833/// pointers into the tile's planes, so no worker may outlive them.
2834/// (lane-pool1: the workers come from this thread's persistent pool, so a
2835/// tile costs a batch submit rather than `EC_AV1_RECON_THREADS` fresh threads
2836/// with fresh scratch.)
2837pub(crate) struct WaveGuard<'a>(
2838 &'a crate::decode::FrameCtx,
2839 Option<crate::par::Batch<'static>>,
2840);
2841
2842#[allow(unsafe_code)]
2843impl<'a> WaveGuard<'a> {
2844 fn install(
2845 fctx: &'a crate::decode::FrameCtx,
2846 y: &mut PlaneBuf<'static>,
2847 u: &mut PlaneBuf<'static>,
2848 v: &mut PlaneBuf<'static>,
2849 rows: usize,
2850 cols: usize,
2851 ) -> Option<Self> {
2852 let threads = crate::par::recon_threads();
2853 if threads == 1 || rows == 0 || cols == 0 {
2854 return None;
2855 }
2856 let st = std::sync::Arc::new(WaveState {
2857 q: std::sync::Mutex::new(WaveQueue {
2858 rows: (0..rows).map(|_| std::collections::VecDeque::new()).collect(),
2859 queued: 0,
2860 done: vec![-1; rows],
2861 last_sub: vec![-1; rows],
2862 last_push: vec![-1; rows],
2863 active: 0,
2864 closed: false,
2865 free: Vec::new(),
2866 free_cap: threads + 2,
2867 }),
2868 cv: std::sync::Condvar::new(),
2869 // SAFETY: the planes are locals of the tile decoder and outlive
2870 // this guard, which joins every worker in `drop`.
2871 planes: ReconPlanes(
2872 std::ptr::from_mut(y),
2873 std::ptr::from_mut(u),
2874 std::ptr::from_mut(v),
2875 ),
2876 bit_depth: fctx.bit_depth.with(std::cell::Cell::get),
2877 enable_edge_filter: fctx.enable_edge_filter.with(std::cell::Cell::get),
2878 last_col: cols - 1,
2879 });
2880 let batch = crate::par::Batch::new("ec-av1-recon");
2881 for idx in 0..threads {
2882 let st = std::sync::Arc::clone(&st);
2883 batch.submit(move || wave_worker(&st, idx));
2884 }
2885 fctx.wave.with(|w| *w.borrow_mut() = Some(st));
2886 fctx.wave_mark.with(|c| c.set(Some(std::time::Instant::now())));
2887 Some(Self(fctx, Some(batch)))
2888 }
2889}
2890
2891impl Drop for WaveGuard<'_> {
2892 fn drop(&mut self) {
2893 let st = self.0.wave.with(|w| w.borrow_mut().take());
2894 if let Some(st) = st {
2895 st.q.lock().unwrap().closed = true;
2896 st.cv.notify_all();
2897 }
2898 let t0 = std::time::Instant::now();
2899 // Dropping the batch waits every worker out, as the joins did.
2900 drop(self.1.take());
2901 if wave_stats() {
2902 WS_DRAIN.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
2903 WS_TILES.fetch_add(1, Relaxed);
2904 wave_stats_dump();
2905 }
2906 }
2907}
2908
2909/// An empty buffer for the next superblock: the recycled one when it is at
2910/// least as big as the superblock just parsed, else a fresh sized one
2911/// (lane-sballoc; `v` is always empty).
2912fn reuse<T>(mut v: Vec<T>, cap: usize) -> Vec<T> {
2913 if v.capacity() < cap {
2914 v.reserve_exact(cap - v.len());
2915 }
2916 v
2917}
2918
2919/// Hands superblock `(r, c)`'s recorded writes to the wavefront. `false`
2920/// when there is no wavefront (one reconstruction thread), in which case the
2921/// caller replays them itself.
2922fn wave_submit(fctx: &crate::decode::FrameCtx, r: usize, c: usize) -> bool {
2923 let st = fctx.wave.with(|w| w.borrow().clone());
2924 let Some(st) = st else { return false };
2925 // lane-blockmem: the op list is replaced sized for the next superblock,
2926 // exactly as the two arenas below are -- taking it left a zero-capacity
2927 // `Vec` that regrew (and memmoved every recorded op) from nothing on
2928 // every superblock.
2929 // lane-sballoc: the replacement comes from the finished jobs' free list
2930 // when there is one (warm capacity, already faulted in); only the first
2931 // superblocks of a tile allocate.
2932 let mut q = st.q.lock().unwrap();
2933 let (sops, scoeffs, spreds) = q.free.pop().unwrap_or_default();
2934 let ops = fctx.recon_ops.with(|c| {
2935 let mut c = c.borrow_mut();
2936 let cap = c.len();
2937 std::mem::replace(&mut *c, reuse(sops, cap))
2938 });
2939 // The job owns its coefficients: the arena is replaced by an empty one
2940 // sized for the next superblock, so parse never regrows from nothing and
2941 // the worker frees this buffer once, instead of once per unit.
2942 let coeffs = fctx.coeff_arena.with(|c| {
2943 let mut c = c.borrow_mut();
2944 let cap = c.len();
2945 std::mem::replace(&mut *c, reuse(scoeffs, cap))
2946 });
2947 let preds = fctx.pred_arena.with(|c| {
2948 let mut c = c.borrow_mut();
2949 let cap = c.len();
2950 std::mem::replace(&mut *c, reuse(spreds, cap))
2951 });
2952 {
2953 if (c as isize) > q.last_sub[r] {
2954 q.last_sub[r] = c as isize;
2955 }
2956 if !ops.is_empty() {
2957 q.rows[r].push_back((c, ReconJob { ops, coeffs, preds }));
2958 q.queued += 1;
2959 q.last_push[r] = c as isize;
2960 }
2961 drop(q);
2962 st.cv.notify_all();
2963 }
2964 if wave_stats() {
2965 let now = std::time::Instant::now();
2966 if let Some(t) = fctx.wave_mark.with(|c| c.replace(Some(now))) {
2967 WS_PARSE.fetch_add((now - t).as_nanos() as u64, Relaxed);
2968 }
2969 }
2970 true
2971}
2972
2973/// Waits until every submitted job is reconstructed, so the parser may read
2974/// the planes itself (the intrabc source fetch and the interintra intra
2975/// predictor -- see [`flush_recon`]).
2976fn wave_barrier(fctx: &crate::decode::FrameCtx) {
2977 let st = fctx.wave.with(|w| w.borrow().clone());
2978 let Some(st) = st else { return };
2979 let stats = wave_stats();
2980 let t0 = std::time::Instant::now();
2981 let mut q = st.q.lock().unwrap();
2982 while q.queued > 0 || q.active > 0 {
2983 q = st.cv.wait(q).unwrap();
2984 }
2985 drop(q);
2986 if stats {
2987 WS_BARRIER.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
2988 WS_BARRIERS.fetch_add(1, Relaxed);
2989 }
2990}
2991
2992/// Performs an intra write at its push site when the tile registered its
2993/// planes for inline reconstruction ([`ReconPlanes`]); `false` when the
2994/// caller must record it for the wavefront workers instead.
2995#[allow(unsafe_code)]
2996#[allow(clippy::too_many_arguments)]
2997fn inline_intra(
2998 plane: usize,
2999 x: usize,
3000 oy: usize,
3001 bw: usize,
3002 bh: usize,
3003 rect: bool,
3004 mode: usize,
3005 angle_delta: i32,
3006 reach: Reach,
3007 residual: &[i32],
3008 cfl: Option<(i32, CflSrc)>,
3009 filter_intra: Option<usize>,
3010 smooth_neighbor: bool,
3011 fctx: &crate::decode::FrameCtx,
3012) -> bool {
3013 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
3014 return false;
3015 };
3016 let pred = take_palette_pred(fctx);
3017 // SAFETY: see [`ReconPlanes`].
3018 unsafe {
3019 exec_intra(
3020 &mut *y, &mut *u, &mut *v, plane, x, oy, bw, bh, rect, mode, angle_delta, reach,
3021 residual, cfl, filter_intra, smooth_neighbor, pred, fctx,
3022 );
3023 }
3024 true
3025}
3026
3027/// [`inline_intra`] for a motion-compensated write.
3028#[allow(unsafe_code)]
3029#[allow(clippy::too_many_arguments)]
3030fn inline_mc(
3031 plane: usize,
3032 x: usize,
3033 oy: usize,
3034 stride: usize,
3035 w: usize,
3036 h: usize,
3037 prediction: &[u16],
3038 residual: &[i32],
3039 fctx: &crate::decode::FrameCtx,
3040) -> bool {
3041 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
3042 return false;
3043 };
3044 // SAFETY: see [`ReconPlanes`].
3045 unsafe {
3046 exec_mc(&mut *y, &mut *u, &mut *v, plane, x, oy, stride, w, h, prediction, residual, fctx);
3047 }
3048 true
3049}
3050
3051/// [`PlaneBuf::reconstruct`], recorded (lane-wave1 step (i)).
3052#[allow(clippy::too_many_arguments)]
3053fn push_intra(
3054 plane: usize,
3055 x: usize,
3056 y: usize,
3057 side: usize,
3058 mode: usize,
3059 angle_delta: i32,
3060 reach: Reach,
3061 residual: &[i32],
3062 cfl: Option<(i32, CflSrc)>,
3063 filter_intra: Option<usize>,
3064 smooth_neighbor: bool, fctx: &crate::decode::FrameCtx,
3065) {
3066 if inline_intra(
3067 plane, x, y, side, side, false, mode, angle_delta, reach, residual, cfl, filter_intra,
3068 smooth_neighbor, fctx,
3069 ) {
3070 return;
3071 }
3072 let pred = take_palette_pred(fctx);
3073 push_op(fctx, ReconOp::Intra {
3074 plane, x, y, bw: side, bh: side, rect: false, mode, angle_delta, reach,
3075 residual: Residual::done(residual, fctx), cfl, filter_intra, smooth_neighbor, pred,
3076 });
3077}
3078
3079/// [`PlaneBuf::reconstruct_rect`], recorded (lane-wave1 step (i)).
3080#[allow(clippy::too_many_arguments)]
3081fn push_intra_rect(
3082 plane: usize,
3083 x: usize,
3084 y: usize,
3085 bw: usize,
3086 bh: usize,
3087 mode: usize,
3088 angle_delta: i32,
3089 reach: Reach,
3090 residual: &[i32],
3091 cfl: Option<(i32, CflSrc)>,
3092 filter_intra: Option<usize>,
3093 smooth_neighbor: bool, fctx: &crate::decode::FrameCtx,
3094) {
3095 if inline_intra(
3096 plane, x, y, bw, bh, true, mode, angle_delta, reach, residual, cfl, filter_intra,
3097 smooth_neighbor, fctx,
3098 ) {
3099 return;
3100 }
3101 let pred = take_palette_pred(fctx);
3102 push_op(fctx, ReconOp::Intra {
3103 plane, x, y, bw, bh, rect: true, mode, angle_delta, reach,
3104 residual: Residual::done(residual, fctx), cfl, filter_intra, smooth_neighbor, pred,
3105 });
3106}
3107
3108/// [`PlaneBuf::reconstruct_mc_rect`] at `stride == w == h == side`, recorded.
3109fn push_mc(
3110 plane: usize,
3111 x: usize,
3112 y: usize,
3113 side: usize,
3114 prediction: Pred<'_>,
3115 residual: &[i32], fctx: &crate::decode::FrameCtx,
3116) {
3117 push_mc_rect(plane, x, y, side, side, side, prediction, residual, fctx);
3118}
3119
3120/// [`PlaneBuf::reconstruct_mc_rect`], recorded (lane-wave1 step (i)).
3121#[allow(clippy::too_many_arguments)]
3122fn push_mc_rect(
3123 plane: usize,
3124 x: usize,
3125 y: usize,
3126 stride: usize,
3127 w: usize,
3128 h: usize,
3129 prediction: Pred<'_>,
3130 residual: &[i32], fctx: &crate::decode::FrameCtx,
3131) {
3132 let (src, stride) = match prediction.inline(stride) {
3133 Some(v) => v,
3134 None => {
3135 let Pred::Cur { plane: sp, stride: ss, off } = prediction else { unreachable!() };
3136 push_op(fctx, ReconOp::Mc {
3137 plane, x, y, stride: ss, w, h,
3138 prediction: PredSrc::Cur { plane: sp, off, src: ss },
3139 residual: Residual::done(residual, fctx),
3140 });
3141 return;
3142 }
3143 };
3144 if inline_mc(plane, x, y, stride, w, h, src, residual, fctx) {
3145 return;
3146 }
3147 push_op(fctx, ReconOp::Mc {
3148 plane, x, y, stride, w, h,
3149 // The whole window `reconstruct_mc_rect` reads at `stride`, not
3150 // `w * h`: the record keeps exactly what `src.to_vec()` carried.
3151 prediction: PredSrc::Owned(push_pred_samples(src, fctx), src.len() as u32),
3152 residual: Residual::done(residual, fctx),
3153 });
3154}
3155
3156/// [`push_intra_rect`] carrying the transform's INPUTS: at one reconstruction
3157/// thread the transform runs here, exactly as before; on the wavefront it
3158/// travels with the op and runs on the worker (lane-wave3).
3159#[allow(clippy::too_many_arguments)]
3160fn push_intra_tx(
3161 plane: usize,
3162 x: usize,
3163 y: usize,
3164 bw: usize,
3165 bh: usize,
3166 rect: bool,
3167 mode: usize,
3168 angle_delta: i32,
3169 reach: Reach,
3170 tx: TxParams,
3171 grid: &[i32],
3172 cfl: Option<(i32, CflSrc)>,
3173 filter_intra: Option<usize>,
3174 smooth_neighbor: bool,
3175 fctx: &crate::decode::FrameCtx,
3176) {
3177 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
3178 inline_intra(
3179 plane, x, y, bw, bh, rect, mode, angle_delta, reach, &tx.run(grid), cfl, filter_intra,
3180 smooth_neighbor, fctx,
3181 );
3182 return;
3183 }
3184 let pred = take_palette_pred(fctx);
3185 push_op(fctx, ReconOp::Intra {
3186 plane, x, y, bw, bh, rect, mode, angle_delta, reach,
3187 residual: Residual::coeffs(tx, grid, fctx), cfl, filter_intra, smooth_neighbor, pred,
3188 });
3189}
3190
3191/// [`push_mc_rect`] carrying the transform's inputs -- see [`push_intra_tx`].
3192#[allow(clippy::too_many_arguments)]
3193fn push_mc_rect_tx(
3194 plane: usize,
3195 x: usize,
3196 y: usize,
3197 stride: usize,
3198 w: usize,
3199 h: usize,
3200 prediction: Pred<'_>,
3201 tx: TxParams,
3202 grid: &[i32],
3203 fctx: &crate::decode::FrameCtx,
3204) {
3205 // lane-wave4: a deferred prediction is not there to be windowed -- the
3206 // op carries its offset into the block's prediction instead, and the
3207 // residual is laid out at that same stride (`reconstruct_mc_rect` reads
3208 // both buffers at one stride).
3209 let (prediction, stride) = match prediction.inline(stride) {
3210 Some(v) => v,
3211 None => {
3212 let Pred::Cur { plane: sp, stride: ss, off } = prediction else { unreachable!() };
3213 let mut tx = tx;
3214 tx.stride = 0;
3215 push_op(fctx, ReconOp::Mc {
3216 plane, x, y, stride: w, w, h,
3217 prediction: PredSrc::Cur { plane: sp, off, src: ss },
3218 residual: Residual::coeffs(tx, grid, fctx),
3219 });
3220 return;
3221 }
3222 };
3223 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
3224 // `reconstruct_mc_rect` reads the prediction and the residual at ONE
3225 // stride, so a prediction handed over at the block's stride (a var-tx
3226 // unit's window, lane-wave4) has to be densified for a dense residual
3227 // -- which is exactly what the recorded path below does.
3228 let residual = tx.run(grid);
3229 let res_stride = if tx.stride == 0 { w } else { tx.stride };
3230 let window;
3231 let prediction = if stride == res_stride {
3232 prediction
3233 } else {
3234 debug_assert_eq!(res_stride, w);
3235 let mut win = Vec::with_capacity(w * h);
3236 for row in 0..h {
3237 win.extend_from_slice(&prediction[row * stride..][..w]);
3238 }
3239 window = win;
3240 &window[..]
3241 };
3242 inline_mc(plane, x, y, res_stride, w, h, prediction, &residual, fctx);
3243 return;
3244 }
3245 // `reconstruct_mc_rect` reads exactly rows `0..h`, columns `0..w` of the
3246 // two buffers at `stride`, so the record carries that window densely
3247 // rather than the whole block's prediction: a 4x4 unit of a 64x64 block
3248 // copied 64*64 samples on the PARSING thread before. The residual is then
3249 // produced dense too (`TxParams::stride = 0`), which is the same numbers
3250 // in the same places at stride `w`.
3251 let off = fctx.pred_arena.with(|a| {
3252 let mut a = a.borrow_mut();
3253 let off = a.len();
3254 for row in 0..h {
3255 a.extend_from_slice(&prediction[row * stride..][..w]);
3256 }
3257 off as u32
3258 });
3259 let mut tx = tx;
3260 tx.stride = 0;
3261 push_op(fctx, ReconOp::Mc {
3262 plane, x, y, stride: w, w, h, prediction: PredSrc::Owned(off, (w * h) as u32),
3263 residual: Residual::coeffs(tx, grid, fctx),
3264 });
3265}
3266
3267/// Replays every recorded [`ReconOp`] into the frame's planes, in push order,
3268/// and empties the queue (lane-wave1 step (i)).
3269///
3270/// Called at the top of each superblock visit and at the end of each tile, so
3271/// a whole superblock's parsing runs with no plane access at all; the two
3272/// parse-time pixel READS that survive -- the intrabc source fetch and the
3273/// interintra intra predictor -- flush ahead of themselves instead, which
3274/// keeps them byte-exact and names exactly what step (ii) still has to move.
3275fn flush_recon(
3276 fctx: &crate::decode::FrameCtx,
3277 y: &mut PlaneBuf<'static>,
3278 u: &mut PlaneBuf<'static>,
3279 v: &mut PlaneBuf<'static>,
3280) {
3281 // lane-wave1 step (ii): a parse-time pixel READ needs every worker's
3282 // writes in place, not just this superblock's queue.
3283 wave_barrier(fctx);
3284 let mut ops = fctx.recon_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));
3285 fctx.recon_ops.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut ops));
3286 let mut coeffs = fctx.coeff_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));
3287 fctx.coeff_arena.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut coeffs));
3288 let mut preds = fctx.pred_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));
3289 fctx.pred_arena.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut preds));
3290 let mut cur: [Vec<u16>; 3] = Default::default();
3291 for op in ops.drain(..) {
3292 exec_op(op, y, u, v, &mut cur, &coeffs, &preds, fctx);
3293 }
3294 coeffs.clear();
3295 preds.clear();
3296 fctx.recon_spare.with(|c| *c.borrow_mut() = ops);
3297 fctx.coeff_spare.with(|c| *c.borrow_mut() = coeffs);
3298 fctx.pred_spare.with(|c| *c.borrow_mut() = preds);
3299}
3300
3301/// Performs one recorded write: the body [`flush_recon`] replays, and the
3302/// body [`push_op`] runs immediately when reconstruction is inline.
3303fn exec_op(
3304 op: ReconOp,
3305 y: &mut PlaneBuf<'static>,
3306 u: &mut PlaneBuf<'static>,
3307 v: &mut PlaneBuf<'static>,
3308 cur: &mut [Vec<u16>; 3],
3309 coeffs: &[i32],
3310 preds: &[u16],
3311 fctx: &crate::decode::FrameCtx,
3312) {
3313 // lane-nbpub instrument: `EC_AV1_NORECON=1` drops every recorded pixel
3314 // write, leaving the entropy parse and the per-mi neighbour bookkeeping
3315 // alone. It makes the encoder's own streams garbage, so it is a
3316 // MEASUREMENT rung only -- what it measures is how much of the encoder's
3317 // first decode of its own tiles (`par::S_FIRST`) is reconstruction and
3318 // how much is parse. Answer at 3840x1608 (4 frames, 4x2 tiles, 8 tile
3319 // threads): 150 ms -> 141 ms, i.e. the reconstruction is 6% of that
3320 // stage and the parse plus the neighbour grids are the other 94%. That
3321 // is why handing the decoder the encoder's own reconstruction cannot
3322 // shrink the stage: only publishing the per-mi neighbour state the
3323 // filters read (and so never parsing at all) can.
3324 if crate::envflags::env_flag!("EC_AV1_NORECON") {
3325 return;
3326 }
3327 let mut scratch = Vec::new();
3328 match op {
3329 ReconOp::Pred(b) => (b.0)(y, u, v, fctx, cur),
3330 ReconOp::Intra {
3331 plane, x, y: oy, bw, bh, rect, mode, angle_delta, reach, residual, cfl,
3332 filter_intra, smooth_neighbor, pred,
3333 } => exec_intra(
3334 y, u, v, plane, x, oy, bw, bh, rect, mode, angle_delta, reach,
3335 residual.resolve(coeffs, &mut scratch),
3336 cfl, filter_intra, smooth_neighbor, pred, fctx,
3337 ),
3338 ReconOp::Mc { plane, x, y: oy, stride, w, h, prediction, residual } => {
3339 let residual = residual.resolve(coeffs, &mut scratch);
3340 match prediction {
3341 PredSrc::Owned(off, len) => {
3342 let p = &preds[off as usize..][..len as usize];
3343 exec_mc(y, u, v, plane, x, oy, stride, w, h, p, residual, fctx);
3344 }
3345 PredSrc::Cur { plane: sp, off, src } => {
3346 let block = std::mem::take(&mut cur[sp]);
3347 if src == stride {
3348 exec_mc(y, u, v, plane, x, oy, stride, w, h, &block[off..], residual, fctx);
3349 } else {
3350 // A transform unit's residual is dense, so its window
3351 // of the block prediction is taken out dense too --
3352 // the copy the parsing thread used to make, made here.
3353 let mut window = Vec::with_capacity(w * h);
3354 for row in 0..h {
3355 window.extend_from_slice(&block[off + row * src..][..w]);
3356 }
3357 exec_mc(y, u, v, plane, x, oy, stride, w, h, &window, residual, fctx);
3358 }
3359 cur[sp] = block;
3360 }
3361 }
3362 }
3363 }
3364}
3365
3366/// [`ReconOp::Intra`] performed. Its arguments are borrowed, so the inline
3367/// path ([`push_op`]'s registered planes) reaches it without ever building
3368/// the record -- which is what keeps one reconstruction thread at the cost of
3369/// the pre-lane-wave1 decoder.
3370#[allow(clippy::too_many_arguments)]
3371fn exec_intra(
3372 y: &mut PlaneBuf<'static>,
3373 u: &mut PlaneBuf<'static>,
3374 v: &mut PlaneBuf<'static>,
3375 plane: usize,
3376 x: usize,
3377 oy: usize,
3378 bw: usize,
3379 bh: usize,
3380 rect: bool,
3381 mode: usize,
3382 angle_delta: i32,
3383 reach: Reach,
3384 residual: &[i32],
3385 cfl: Option<(i32, CflSrc)>,
3386 filter_intra: Option<usize>,
3387 smooth_neighbor: bool,
3388 pred: Option<Vec<u16>>,
3389 fctx: &crate::decode::FrameCtx,
3390) {
3391 // The CfL AC signal is read HERE, off the luma that has already been
3392 // written for this block -- at parse time it would have been the previous
3393 // frame's samples.
3394 let ac = cfl.map(|(alpha, src)| {
3395 let sig = if src.rect {
3396 cfl_ac_q3_rect(&*y, src.px, src.py, src.bw, src.bh)
3397 } else {
3398 cfl_ac_q3(&*y, src.px, src.py, src.bw)
3399 };
3400 (alpha, sig)
3401 });
3402 let cfl = ac.as_ref().map(|(a, sig)| (*a, sig.as_slice()));
3403 let target: &mut PlaneBuf<'static> = match plane { 0 => &mut *y, 1 => &mut *u, _ => &mut *v };
3404 if rect {
3405 target.reconstruct_rect(
3406 x, oy, bw, bh, mode, angle_delta, reach, residual, cfl, filter_intra,
3407 smooth_neighbor, pred, fctx,
3408 );
3409 } else {
3410 target.reconstruct(
3411 x, oy, bw, mode, angle_delta, reach, residual, cfl, filter_intra,
3412 smooth_neighbor, pred, fctx,
3413 );
3414 }
3415}
3416
3417/// [`ReconOp::Mc`] performed -- see [`exec_intra`].
3418#[allow(clippy::too_many_arguments)]
3419fn exec_mc(
3420 y: &mut PlaneBuf<'static>,
3421 u: &mut PlaneBuf<'static>,
3422 v: &mut PlaneBuf<'static>,
3423 plane: usize,
3424 x: usize,
3425 oy: usize,
3426 stride: usize,
3427 w: usize,
3428 h: usize,
3429 prediction: &[u16],
3430 residual: &[i32],
3431 fctx: &crate::decode::FrameCtx,
3432) {
3433 let target: &mut PlaneBuf<'static> = match plane { 0 => &mut *y, 1 => &mut *u, _ => &mut *v };
3434 target.reconstruct_mc_rect(x, oy, stride, w, h, prediction, residual, fctx);
3435}
3436
3437thread_local! {
3438 /// The current frame's `mi` grid, kept only while a frame header set
3439 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
3440 /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
3441 /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
3442 /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
3443 /// does not allow intrabc (so nothing is paid for it).
3444 ///
3445 /// corner-cut: only [`decode_block`] (the square path) records into it,
3446 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
3447 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
3448 /// be wrong there; upgrade = record from the rect/leaf paths too.
3449 /// The block vector [`read_intra_mode`] just decoded, handed to
3450 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
3451 /// which the alternative -- a tenth tuple member through every caller --
3452 /// already avoids). Always `.take()`n by the block that reads it.
3453 /// How many blocks decoded `use_intrabc == 1` -- the gate's hit counter.
3454 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3455}
3456 // The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so
3457 // an intrabc block's chroma reads can inherit it (see
3458 // [`INTRABC_CHROMA_TX`]). Written on every luma read; only ever read
3459 // through that one arming site.
3460 // libaom `av1_get_tx_type` (`blockd.h:1350`): for `PLANE_TYPE_UV` it
3461 // branches on `is_inter_block(mbmi)` -- which `is_intrabc_block` also
3462 // satisfies (`blockd.h:373`) -- and takes the *colocated luma
3463 // transform's coded* `tx_type` (`mbmi->txk_type[...]`), never
3464 // `intra_mode_to_tx_type` of the chroma mode. `Some` only across an
3465 // intrabc block's two chroma [`read_plane`] calls; the type decides the
3466 // `TX_CLASS`, hence the scan order, `eob_multi_ctx` and every nz context
3467 // -- getting it wrong desyncs the chroma coefficients, it is not a
3468 // reconstruction-only detail.
3469
3470/// Whether this frame's header set `allow_intrabc` -- [`INTRABC_MI_GRID`] is
3471/// `Some` exactly then (set once per frame in `decode_frame`), so the flag
3472/// needs no separate plumbing to reach the rect-strip mode reader.
3473fn allow_intrabc_frame(fctx: &crate::decode::FrameCtx) -> bool {
3474 fctx.intrabc_mi_grid.with(|g| g.borrow().is_some())
3475}
3476
3477thread_local! {
3478 /// How many rect intra strips READ the `use_intrabc` symbol (i.e. how many
3479 /// times the fix below was exercised) -- the rect-strip gate's hit counter,
3480 /// distinct from [`INTRABC_HITS`] which counts blocks that USE intrabc.
3481 static RECT_INTRABC_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3482}
3483
3484/// Current value of [`RECT_INTRABC_READS`].
3485pub(crate) fn rect_intrabc_reads() -> usize {
3486 RECT_INTRABC_READS.with(|c| c.get())
3487}
3488
3489/// Zeroes [`RECT_INTRABC_READS`] (gate tests call this before a decode).
3490#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3491pub(crate) fn reset_rect_intrabc_reads() {
3492 RECT_INTRABC_READS.with(|c| c.set(0));
3493}
3494
3495thread_local! {
3496 /// Blocks that USED intrabc at an 8x8 LEAF (`decode_leaf8`) specifically
3497 /// -- the shape lane-kf900 r7 fixed; [`INTRABC_HITS`] counts every shape.
3498 static LEAF8_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3499}
3500
3501/// Current value of [`LEAF8_INTRABC_HITS`].
3502pub(crate) fn leaf8_intrabc_hits() -> usize {
3503 LEAF8_INTRABC_HITS.with(|c| c.get())
3504}
3505
3506/// Zeroes [`LEAF8_INTRABC_HITS`] (gate tests call this before a decode).
3507#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3508pub(crate) fn reset_leaf8_intrabc_hits() {
3509 LEAF8_INTRABC_HITS.with(|c| c.set(0));
3510}
3511
3512/// Current value of [`INTRABC_HITS`].
3513#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3514pub(crate) fn intrabc_hits() -> usize {
3515 INTRABC_HITS.with(|c| c.get())
3516}
3517
3518/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
3519#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3520pub(crate) fn reset_intrabc_hits() {
3521 INTRABC_HITS.with(|c| c.set(0));
3522}
3523
3524thread_local! {
3525 /// lane-t900 r32: intrabc blocks whose transform size came off the INTER
3526 /// var-tx partition tree (unskipped, `TX_MODE_SELECT`) -- the capability
3527 /// that replaced the refusal "an intrabc block under TxMode::Select".
3528 static INTRABC_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3529}
3530
3531/// Current value of [`INTRABC_VARTX_HITS`].
3532#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3533pub(crate) fn intrabc_vartx_hits() -> usize {
3534 INTRABC_VARTX_HITS.with(|c| c.get())
3535}
3536
3537/// Zeroes [`INTRABC_VARTX_HITS`] (gate tests call this before a decode).
3538#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3539pub(crate) fn reset_intrabc_vartx_hits() {
3540 INTRABC_VARTX_HITS.with(|c| c.set(0));
3541}
3542
3543/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
3544/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
3545/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
3546/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
3547fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>, fctx: &crate::decode::FrameCtx) {
3548 fctx.intrabc_mi_grid.with(|g| {
3549 let mut g = g.borrow_mut();
3550 let Some((grid, _, _)) = g.as_mut() else {
3551 return;
3552 };
3553 let info = crate::mvstack::MiInfo {
3554 is_inter: dv.is_some(),
3555 ref_frame: 0,
3556 ref_frame1: NO_REF1,
3557 mv: mv16(dv.unwrap_or((0, 0))),
3558 mv1: (0, 0),
3559 is_new_mv: dv.is_some(),
3560 is_global_mv0: false,
3561 is_global_mv1: false,
3562 size: n4 as u8,
3563 size_h: n4 as u8,
3564 };
3565 for r in mi_r..mi_r + n4 {
3566 for c in mi_c..mi_c + n4 {
3567 grid.set(r, c, info);
3568 }
3569 }
3570 });
3571}
3572
3573// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
3574// proves a real `skip_mode_present` stream actually reached a block that
3575// picked it, not just that the frame header bit was set.
3576thread_local! {
3577 static SKIP_MODE_HITS: std::cell::Cell<usize> =
3578 const { std::cell::Cell::new(0) };
3579}
3580
3581/// Current value of [`SKIP_MODE_HITS`].
3582#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3583pub(crate) fn skip_mode_hits() -> usize {
3584 SKIP_MODE_HITS.with(|c| c.get())
3585}
3586
3587// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
3588// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
3589// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
3590// reached [`obmc_blend`], not just the header bit.
3591thread_local! {
3592 static OBMC_HITS: std::cell::Cell<usize> =
3593 const { std::cell::Cell::new(0) };
3594}
3595
3596// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the
3597// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled
3598// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while
3599// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have
3600// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this
3601// decoder used to read with the wrong alphabet, so a gate that asserts this
3602// counter advanced proves the fixed path fired (class
3603// `gate-blind-to-feature`).
3604thread_local! {
3605 static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3606}
3607
3608/// Current value of [`FIMV_ALPHABET_HITS`].
3609pub fn fimv_alphabet_hits() -> usize {
3610 FIMV_ALPHABET_HITS.with(|c| c.get())
3611}
3612
3613// lane-fimv r1: how many frame headers this decoder has decoded with
3614// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate
3615// prove the encoder really produced the header state under test rather than
3616// assume it.
3617thread_local! {
3618 static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3619}
3620
3621/// Current value of [`FIMV_FRAME_HITS`].
3622pub fn fimv_frame_hits() -> usize {
3623 FIMV_FRAME_HITS.with(|c| c.get())
3624}
3625
3626/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
3627/// `force_integer_mv` bit is set.
3628pub fn note_force_integer_mv_frame() {
3629 hit!(FIMV_FRAME_HITS);
3630}
3631
3632/// Current value of [`OBMC_HITS`].
3633#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3634pub(crate) fn obmc_hits() -> usize {
3635 OBMC_HITS.with(|c| c.get())
3636}
3637
3638// lane-t900 r27: OBMC blends that actually READ a recorded switchable filter
3639// off the neighbour band -- the positive half of the proof for "an OBMC
3640// neighbour whose switchable interp filter was never recorded". A
3641// fixed-filter frame returns before this point (its neighbours legitimately
3642// carry the `[3, 3]` sentinel), so every bump is a neighbour whose own
3643// `interp_filter` symbols were published by `record_inter_rect_mi`.
3644thread_local! {
3645 static OBMC_FILTER_BAND_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3646}
3647
3648/// Current value of [`OBMC_FILTER_BAND_READS`].
3649#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3650pub(crate) fn obmc_filter_band_reads() -> usize {
3651 OBMC_FILTER_BAND_READS.with(|c| c.get())
3652}
3653
3654// lane-scaledref r1: per-case firing counts for the scaled-reference gate
3655// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED
3656// reference would pass just as well and prove nothing, so the gate
3657// hard-asserts each combination this round lifts actually occurred:
3658// a compound block with a scaled tap, a warp block whose warp libaom
3659// suppresses because the reference is scaled, an OBMC block, an interintra
3660// block, and an 8x8 leaf.
3661thread_local! {
3662 static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3663 static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3664 static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3665 static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3666 static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3667 static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3668 static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3669}
3670
3671/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one
3672/// scaled and one unscaled tap.
3673#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3674pub(crate) fn mixed_scale_compound_hits() -> usize {
3675 MIXED_SCALE_COMPOUND_HITS.with(|c| c.get())
3676}
3677
3678/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have
3679/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf`
3680/// instead because their reference is scaled (libaom `motion_mode_allowed`,
3681/// `blockd.h:1484`).
3682#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3683pub(crate) fn scaled_warp_suppressed_hits() -> usize {
3684 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get())
3685}
3686
3687/// Current value of [`SCALED_COMPOUND_HITS`].
3688#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3689pub(crate) fn scaled_compound_hits() -> usize {
3690 SCALED_COMPOUND_HITS.with(|c| c.get())
3691}
3692
3693/// Current value of [`SCALED_WARP_FALLBACK_HITS`].
3694pub fn scaled_warp_fallback_hits() -> usize {
3695 SCALED_WARP_FALLBACK_HITS.with(|c| c.get())
3696}
3697
3698/// Current value of [`SCALED_OBMC_HITS`].
3699#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3700pub(crate) fn scaled_obmc_hits() -> usize {
3701 SCALED_OBMC_HITS.with(|c| c.get())
3702}
3703
3704/// Current value of [`SCALED_INTERINTRA_HITS`].
3705#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3706pub(crate) fn scaled_interintra_hits() -> usize {
3707 SCALED_INTERINTRA_HITS.with(|c| c.get())
3708}
3709
3710/// Current value of [`SCALED_BLOCK8_HITS`].
3711#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3712pub(crate) fn scaled_block8_hits() -> usize {
3713 SCALED_BLOCK8_HITS.with(|c| c.get())
3714}
3715
3716// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
3717// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
3718// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
3719// 8x8-leaf OBMC block apart from a 16x16+ one.
3720thread_local! {
3721 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3722}
3723
3724// lane-interp3 r1: how many inter blocks read a SWITCHABLE `interp_filter`
3725// pair whose two directions differ (`enable_dual_filter` only -- with dual
3726// filter off both directions take the single symbol, so this can never fire).
3727// A gate asserting it proves the stream really carries dual-filter blocks.
3728thread_local! {
3729 static DUAL_FILTER_DIFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3730}
3731
3732// lane-interp3 r1: how many COMPOUND 8x8 leaves read their own
3733// `read_mb_interp_filter` symbol(s) -- the read this round added (the leaf
3734// used to skip it entirely, losing a symbol and stamping the `[3, 3]`
3735// no-filter sentinel that made a neighbouring OBMC block panic).
3736thread_local! {
3737 static COMPOUND8_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3738}
3739
3740/// Current value of [`DUAL_FILTER_DIFF_HITS`].
3741#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3742pub(crate) fn dual_filter_diff_hits() -> usize {
3743 DUAL_FILTER_DIFF_HITS.with(|c| c.get())
3744}
3745
3746/// Current value of [`COMPOUND8_FILTER_HITS`].
3747#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3748pub(crate) fn compound8_filter_hits() -> usize {
3749 COMPOUND8_FILTER_HITS.with(|c| c.get())
3750}
3751
3752// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
3753// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
3754// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
3755// -- the gate's proof that a fixture really exercises the alphabet this
3756// round changed, even though the block itself still refuses (warp
3757// estimation/filter not ported).
3758thread_local! {
3759 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
3760 const { std::cell::Cell::new(0) };
3761}
3762
3763/// Current value of [`WARP_SELECTED_HITS`].
3764#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3765pub(crate) fn warp_selected_hits() -> usize {
3766 WARP_SELECTED_HITS.with(|c| c.get())
3767}
3768
3769// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one
3770// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane`
3771// into the compound intermediate) rather than translationally -- the
3772// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model
3773// really reached [`crate::warp::warp_affine_compound`].
3774thread_local! {
3775 static COMPOUND_WARP_HITS: std::cell::Cell<usize> =
3776 const { std::cell::Cell::new(0) };
3777}
3778
3779/// Current value of [`COMPOUND_WARP_HITS`].
3780#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3781pub(crate) fn compound_warp_hits() -> usize {
3782 COMPOUND_WARP_HITS.with(|c| c.get())
3783}
3784
3785// lane-interp3 r3: the same proof narrowed to the 8x8 LEAF's own compound
3786// arm ([`decode_inter_block8`]) -- that arm predicted both taps
3787// translationally until r3, so a gate needs to tell a warped 8x8 compound
3788// leaf apart from a warped 16x16+ one (both bump [`COMPOUND_WARP_HITS`]).
3789thread_local! {
3790 static COMPOUND_WARP_HITS_8: std::cell::Cell<usize> =
3791 const { std::cell::Cell::new(0) };
3792}
3793
3794/// Current value of [`COMPOUND_WARP_HITS_8`].
3795#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3796pub(crate) fn compound_warp_hits_8() -> usize {
3797 COMPOUND_WARP_HITS_8.with(|c| c.get())
3798}
3799
3800// lane-gmaffine r1: how many blocks built their prediction from a
3801// SIX-parameter (`AFFINE`) global-motion model through
3802// `crate::warp::global_warp_params` -- the gate's proof that a stream really
3803// carried an AFFINE `global_motion_params` AND that a block was predicted
3804// with it, not merely that the header parsed one.
3805thread_local! {
3806 static AFFINE_GM_HITS: std::cell::Cell<usize> =
3807 const { std::cell::Cell::new(0) };
3808}
3809
3810/// Current value of [`AFFINE_GM_HITS`].
3811#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3812pub(crate) fn affine_gm_hits() -> usize {
3813 AFFINE_GM_HITS.with(|c| c.get())
3814}
3815
3816// lane-t900 r9: rect blocks whose warp-sample top-right probe answers
3817// differently at the block's WIDTH than at libaom's
3818// `AOMMAX(xd->width, xd->height)` -- each one is a `num_proj_ref` that could
3819// pick the wrong motion_mode alphabet.
3820thread_local! {
3821 static TR_REACH_LONGER_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3822}
3823
3824/// Current value of [`TR_REACH_LONGER_SIDE_HITS`].
3825pub fn tr_reach_longer_side_hits() -> usize {
3826 TR_REACH_LONGER_SIDE_HITS.with(std::cell::Cell::get)
3827}
3828
3829// lane-t900 r9: libaom `is_nontrans_global_motion` (mvref_common.h) returns 0
3830// for `AOMMIN(mi_size_wide[bsize], mi_size_high[bsize]) < 2`, i.e. any block
3831// with a 4-px side is NEVER "non-translational global" and therefore ALWAYS
3832// reads its interp-filter symbol. Counts the blocks where that guard flips
3833// our answer -- a GLOBALMV/GLOBAL_GLOBALMV block with a non-TRANSLATION model
3834// and a 4-px side, which we used to suppress the interp read on (a pre-mode
3835// entropy desync one symbol wide).
3836thread_local! {
3837 static GM_NONTRANS_SMALL_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3838}
3839
3840/// Current value of [`GM_NONTRANS_SMALL_SIDE_HITS`].
3841pub fn gm_nontrans_small_side_hits() -> usize {
3842 GM_NONTRANS_SMALL_SIDE_HITS.with(std::cell::Cell::get)
3843}
3844
3845// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves
3846// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real
3847// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented
3848// only once `find_projection` returned a usable model, unlike
3849// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates'
3850// proof that the leaf path itself fired, not the 16x16+ one.
3851thread_local! {
3852 static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3853 static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3854}
3855
3856/// Current value of [`GLOBALMV_HITS_8`].
3857#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3858pub(crate) fn globalmv_hits_8() -> usize {
3859 GLOBALMV_HITS_8.with(|c| c.get())
3860}
3861
3862/// Current value of [`WARP_HITS_8`].
3863#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3864pub(crate) fn warp_hits_8() -> usize {
3865 WARP_HITS_8.with(|c| c.get())
3866}
3867
3868// How many blocks decoded `interintra == 1` with the non-wedge blended
3869// prediction applied (lane-interintra r1) -- the gate's proof that a
3870// stream actually exercised interintra.
3871thread_local! {
3872 static INTERINTRA_HITS: std::cell::Cell<usize> =
3873 const { std::cell::Cell::new(0) };
3874}
3875
3876/// Current value of [`INTERINTRA_HITS`].
3877#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3878pub(crate) fn interintra_hits() -> usize {
3879 INTERINTRA_HITS.with(|c| c.get())
3880}
3881
3882// lane-midcut r1: of those, how many were RECTANGULAR (`write_w != write_h`)
3883// -- the shape `interintra_blend` used to build a square `side x side` intra
3884// predictor for, with `ii_size_scales`/`edges` taken at the square. Every
3885// pre-existing interintra gate passed with that bug, so the rect arm needs
3886// its own counter to stop being vacuous.
3887thread_local! {
3888 static INTERINTRA_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3889}
3890
3891/// Current value of [`INTERINTRA_RECT_HITS`].
3892pub fn interintra_rect_hits() -> usize {
3893 INTERINTRA_RECT_HITS.with(|c| c.get())
3894}
3895
3896// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
3897// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
3898// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
3899// gate fixture actually exercises this alphabet, even though the block
3900// still refuses (the mask blend itself is unported).
3901thread_local! {
3902 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
3903 const { std::cell::Cell::new(0) };
3904}
3905
3906/// Current value of [`MASKED_COMPOUND_HITS`].
3907#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3908pub(crate) fn masked_compound_hits() -> usize {
3909 MASKED_COMPOUND_HITS.with(|c| c.get())
3910}
3911
3912// lane-intersub8 r4/r5: the NON-SQUARE half of `MASKED_COMPOUND_HITS` -- a
3913// masked-compound block whose true footprint is rectangular, i.e. the case
3914// whose `compound_type`/`wedge_idx` CDF row r4 fixed (it used to read the
3915// square envelope's `BLOCK_SIZES_ALL` index). Square blocks cannot show that
3916// defect, so a gate asserting `masked_compound_hits` alone stays vacuous for it.
3917thread_local! {
3918 static RECT_MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
3919 const { std::cell::Cell::new(0) };
3920}
3921
3922/// Current value of [`RECT_MASKED_COMPOUND_HITS`].
3923#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3924pub(crate) fn rect_masked_compound_hits() -> usize {
3925 RECT_MASKED_COMPOUND_HITS.with(|c| c.get())
3926}
3927
3928// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
3929// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
3930// actually exercised the wedge blend, not just the DIFFWTD half of
3931// `MASKED_COMPOUND_HITS`.
3932thread_local! {
3933 static WEDGE_HITS: std::cell::Cell<usize> =
3934 const { std::cell::Cell::new(0) };
3935}
3936
3937/// Current value of [`WEDGE_HITS`].
3938#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3939pub(crate) fn wedge_hits() -> usize {
3940 WEDGE_HITS.with(|c| c.get())
3941}
3942
3943// How many blocks decoded a real wedge-INTERINTRA block
3944// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
3945// a gate fixture exercised the wedge blend (fixed sign 0), not just the
3946// smooth arm counted by `INTERINTRA_HITS`.
3947thread_local! {
3948 static WII_HITS: std::cell::Cell<usize> =
3949 const { std::cell::Cell::new(0) };
3950}
3951
3952/// Current value of [`WII_HITS`].
3953#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3954pub(crate) fn wii_hits() -> usize {
3955 WII_HITS.with(|c| c.get())
3956}
3957
3958// lane-sbrect10 r1: how many INTRA blocks read `uv_mode` off the 13-symbol
3959// NO-CFL alphabet *because their size excludes CFL* (libaom `is_cfl_allowed`:
3960// wide <= 32 && high <= 32). The witness that a gate stream really carries a
3961// 64-axis intra block -- the shape whose 14-symbol read desynced every inter
3962// frame carrying one.
3963thread_local! {
3964 static NOCFL_UV_MODE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3965}
3966
3967/// Current value of [`NOCFL_UV_MODE_HITS`].
3968#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3969pub(crate) fn nocfl_uv_mode_hits() -> usize {
3970 NOCFL_UV_MODE_HITS.with(|c| c.get())
3971}
3972
3973/// lane-inter16ab r5: the six RECTANGULAR wedge shapes, in this order --
3974/// the counter slots of [`RECT_WEDGE_HITS`]/[`RECT_WII_HITS`].
3975pub(crate) const RECT_WEDGE_SHAPES: [(usize, usize); 6] =
3976 [(8, 16), (16, 8), (16, 32), (32, 16), (8, 32), (32, 8)];
3977
3978fn rect_wedge_slot(bw: usize, bh: usize) -> Option<usize> {
3979 RECT_WEDGE_SHAPES.iter().position(|&s| s == (bw, bh))
3980}
3981
3982// lane-inter16ab r5: how many COMPOUND_WEDGE / wedge-INTERINTRA blocks used a
3983// RECTANGULAR codebook row (hgtw/hltw), per shape -- the gate's proof that
3984// the rect wedge masks lifted this round actually fired, not just the square
3985// ones already counted by `WEDGE_HITS`/`WII_HITS`.
3986thread_local! {
3987 static RECT_WEDGE_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
3988 static RECT_WII_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
3989}
3990
3991/// Current value of [`RECT_WEDGE_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
3992pub(crate) fn rect_wedge_hits() -> [usize; 6] {
3993 RECT_WEDGE_HITS.with(|c| c.get())
3994}
3995
3996/// Current value of [`RECT_WII_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
3997pub(crate) fn rect_wii_hits() -> [usize; 6] {
3998 RECT_WII_HITS.with(|c| c.get())
3999}
4000
4001// lane-inter4 r4: how many 16x8/8x16 INTER LEAVES actually ran the OBMC
4002// blend -- the gate's proof that `--enable-obmc=1` reached this shape (the
4003// r3 refusal's replacement: prefilt frames are bit-exact vs an instrumented
4004// aomdec, neighbour list included).
4005thread_local! {
4006 static OBMC_RECT_LEAF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4007}
4008
4009/// Current value of [`OBMC_RECT_LEAF_HITS`].
4010pub(crate) fn obmc_rect_leaf_hits() -> usize {
4011 OBMC_RECT_LEAF_HITS.with(|c| c.get())
4012}
4013
4014// lane-obmcrec r1: how many OBMC neighbours were taken from the SECOND half of
4015// a 4-wide/4-tall (1:4 strip) chroma pair -- the case whose interp filter used
4016// to be read from the pair's FIRST mi, which is a different block and, when
4017// that half is intra, carries the `[3, 3]` "no filter" sentinel (the three
4018// 1080p 10-bit film cuts refused there). The gate's proof the shape fired.
4019thread_local! {
4020 static OBMC_PAIR_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4021}
4022
4023/// Current value of [`OBMC_PAIR_FILTER_HITS`].
4024pub(crate) fn obmc_pair_filter_hits() -> usize {
4025 OBMC_PAIR_FILTER_HITS.with(|c| c.get())
4026}
4027
4028// lane-t900 r14: how many OBMC neighbour predictions run PAST the frame edge
4029// -- libaom's `op_mi_size` is `AOMMIN(xd->width|height, mi_step)`, the block's
4030// own side, so a block overhanging the bottom/right still predicts the full
4031// neighbour strip (the destination write is what clips). We used to shrink the
4032// prediction to the visible part, which at 4 chroma rows/cols also swaps the
4033// vertical/horizontal kernel to the 4-tap one. The gate's proof the shape fired.
4034thread_local! {
4035 static OBMC_EDGE_SPAN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4036}
4037
4038/// Current value of [`OBMC_EDGE_SPAN_HITS`].
4039#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4040pub(crate) fn obmc_edge_span_hits() -> usize {
4041 OBMC_EDGE_SPAN_HITS.with(|c| c.get())
4042}
4043
4044/// Current value of [`OBMC_HITS_8`].
4045#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4046pub(crate) fn obmc_hits_8() -> usize {
4047 OBMC_HITS_8.with(|c| c.get())
4048}
4049
4050// lane-rectgate r1: how many 32x32 quadrants actually decoded a
4051// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
4052// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
4053// `VERT_B` all still fall into the generic "a partition type this encoder
4054// never writes" refusal below) -- the gate's proof that a free-partition
4055// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
4056// coincidentally never selecting one.
4057thread_local! {
4058 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
4059 const { std::cell::Cell::new(0) };
4060}
4061
4062/// Current value of [`EXTENDED_PARTITION_HITS`].
4063#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4064pub(crate) fn extended_partition_hits() -> usize {
4065 EXTENDED_PARTITION_HITS.with(|c| c.get())
4066}
4067
4068// lane-partitions r1: how many 32x32 quadrants decoded a real
4069// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
4070// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
4071// gate's proof this round's arms actually fired.
4072thread_local! {
4073 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
4074 const { std::cell::Cell::new(0) };
4075}
4076
4077/// Current value of [`RECT_PARTITION_HITS`].
4078#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4079pub(crate) fn rect_partition_hits() -> usize {
4080 RECT_PARTITION_HITS.with(|c| c.get())
4081}
4082
4083// lane-inter8 r1: how many superblocks an inter tile coded as a single
4084// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for
4085// static content, previously a named refusal).
4086thread_local! {
4087 /// lane-sb128c r1: how many 128x128 `PARTITION_NONE` roots this INTER tile
4088 /// path decoded as one whole block (its gate's own witness).
4089 pub(crate) static INTER_SB128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4090 /// 128x64 / 64x128 INTER blocks decoded at the 128 root (lane-sb128c r7).
4091 pub(crate) static INTER_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4092 pub(crate) static INTER_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4093}
4094
4095/// Current value of [`INTER_SB128_HORZ_HITS`], for a gate's before/after delta.
4096pub(crate) fn inter_sb128_horz_hits() -> usize {
4097 INTER_SB128_HORZ_HITS.with(std::cell::Cell::get)
4098}
4099
4100/// Current value of [`INTER_SB128_VERT_HITS`], for a gate's before/after delta.
4101pub(crate) fn inter_sb128_vert_hits() -> usize {
4102 INTER_SB128_VERT_HITS.with(std::cell::Cell::get)
4103}
4104
4105/// Current value of [`INTER_SB128_NONE_HITS`], for a gate's before/after delta.
4106pub fn inter_sb128_none_hits() -> usize {
4107 INTER_SB128_NONE_HITS.with(std::cell::Cell::get)
4108}
4109
4110thread_local! {
4111 /// lane-sb128c r3: how many INTRA-coded 128x128 blocks inside an INTER
4112 /// frame this decoder reconstructed (mu-chunk chroma, four TX_64X64 luma
4113 /// units) -- the gate's witness that the lifted refusal's case fired.
4114 pub(crate) static INTRA_128_IN_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4115}
4116
4117/// Current value of [`INTRA_128_IN_INTER_HITS`], for a gate's before/after delta.
4118pub fn intra_128_in_inter_hits() -> usize {
4119 INTRA_128_IN_INTER_HITS.with(std::cell::Cell::get)
4120}
4121
4122thread_local! {
4123 static INTER_SB_NONE_HITS: std::cell::Cell<usize> =
4124 const { std::cell::Cell::new(0) };
4125}
4126
4127/// Current value of [`INTER_SB_NONE_HITS`].
4128#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4129pub(crate) fn inter_sb_none_hits() -> usize {
4130 INTER_SB_NONE_HITS.with(|c| c.get())
4131}
4132
4133// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter
4134// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle
4135// path has always run that loop, so only this counter proves the newly-lifted
4136// alphabet value fired.
4137thread_local! {
4138 static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> =
4139 const { std::cell::Cell::new(0) };
4140}
4141
4142/// Current value of [`INTER_SUB16_SPLIT_HITS`].
4143#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4144pub(crate) fn inter_sub16_split_hits() -> usize {
4145 INTER_SUB16_SPLIT_HITS.with(|c| c.get())
4146}
4147
4148// lane-t900 r28: how many 16x16 inter splits reached their four 8x8 leaves
4149// while at least one reference picture was SCALED (superres) -- the counter
4150// behind the lifted "8x8 partition leaf under a scaled reference" refusal.
4151thread_local! {
4152 static SCALED_LEAF8_HITS: std::cell::Cell<usize> =
4153 const { std::cell::Cell::new(0) };
4154}
4155
4156/// Current value of [`SCALED_LEAF8_HITS`].
4157pub fn scaled_leaf8_hits() -> usize {
4158 SCALED_LEAF8_HITS.with(|c| c.get())
4159}
4160
4161// lane-t900 r28: how many sub-8x8 inter blocks (the 4x4 split and the 8x4/4x8
4162// rect pair) were predicted from a SCALED reference -- the counter behind the
4163// lifted "sub-8x8 inter block under a scaled reference" refusal.
4164thread_local! {
4165 static SCALED_SUB8_HITS: std::cell::Cell<usize> =
4166 const { std::cell::Cell::new(0) };
4167}
4168
4169/// Current value of [`SCALED_SUB8_HITS`].
4170pub fn scaled_sub8_hits() -> usize {
4171 SCALED_SUB8_HITS.with(|c| c.get())
4172}
4173
4174// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
4175// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
4176// rect coefficient reader itself fired, not just the strip-level partition
4177// symbol [`RECT_PARTITION_HITS`] already counts.
4178thread_local! {
4179 static RECT_COEFF_HITS: std::cell::Cell<usize> =
4180 const { std::cell::Cell::new(0) };
4181}
4182
4183/// Current value of [`RECT_COEFF_HITS`].
4184#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4185pub(crate) fn rect_coeff_hits() -> usize {
4186 RECT_COEFF_HITS.with(|c| c.get())
4187}
4188
4189// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`])
4190// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the
4191// charter's real-aomenc gate hard-asserts.
4192thread_local! {
4193 static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> =
4194 const { std::cell::Cell::new(0) };
4195}
4196
4197/// Current value of [`RECT_LEAF_COEFF_HITS`].
4198#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4199pub(crate) fn rect_leaf_coeff_hits() -> usize {
4200 RECT_LEAF_COEFF_HITS.with(|c| c.get())
4201}
4202
4203// lane-intrarect r1: how many intra-coded HORZ/VERT strips decoded on the
4204// INTER block path ([`decode_intra_rect_in_inter`]), per shape class --
4205// [0] the superblock-level 64x32/32x64, [1] 32x16/16x32, [2] 16x8/8x16.
4206// Every one of them was the named refusal "an intra-coded HORZ/VERT strip
4207// needs rectangular intra prediction" before this round.
4208thread_local! {
4209 static INTRA_RECT_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
4210 const { std::cell::Cell::new([0; 3]) };
4211}
4212
4213/// Current value of [`INTRA_RECT_IN_INTER_HITS`] for one shape class
4214/// (0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16).
4215#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4216pub(crate) fn intra_rect_strip_in_inter_hits(class: usize) -> usize {
4217 INTRA_RECT_IN_INTER_HITS.with(|c| c.get()[class])
4218}
4219
4220// lane-rect64port r1 (ported by hand from lane-intra64split 5ffbaf3): coded
4221// (non-skip) 64-level HORZ/VERT intra strips whose luma transform is the
4222// un-split TX_64X32/TX_32X64 -- the corner-cropped 32x32 coefficient read of
4223// [`decode_rect_split`], the shape both 10-bit 3840x1608 film cuts stop on.
4224// Split by ORIENTATION (index 0 = 64x32 wide / HORZ, 1 = 32x64 tall / VERT):
4225// a single counter cannot tell an axis swap from a working arm
4226// (class [[scan-weights-cross-axis]]), so the gate asserts both cells.
4227thread_local! {
4228 static RECT64_CORNER_TU_HITS: std::cell::Cell<[usize; 2]> =
4229 const { std::cell::Cell::new([0; 2]) };
4230}
4231
4232/// Current value of [`RECT64_CORNER_TU_HITS`] for one orientation
4233/// (0 = 64x32, 1 = 32x64).
4234pub(crate) fn rect64_corner_tu_hits(orient: usize) -> usize {
4235 RECT64_CORNER_TU_HITS.with(|c| c.get()[orient])
4236}
4237
4238// lane-intrasplit r1: intra HORZ/VERT strips inside an INTER frame whose luma
4239// transform is SPLIT, bucketed by the read `tx_depth` (index 1 and 2; index 0
4240// is never incremented) -- the gate's proof that the lifted path ran per depth.
4241thread_local! {
4242 static INTRA_RECT_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 3]> =
4243 const { std::cell::Cell::new([0; 3]) };
4244}
4245
4246// lane-t900 r21: rect intra strips inside an inter frame that read the
4247// screen-content palette syntax (`allow_screen_content_tools` set and the
4248// strip's own shape admitted by `palette_bsize_ctx_wh`) -- the site a blanket
4249// refusal used to guard, so this counter is what keeps its witness gate
4250// non-vacuous.
4251thread_local! {
4252 static INTRA_RECT_IN_INTER_SCREEN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4253}
4254
4255/// Current value of [`INTRA_RECT_IN_INTER_SCREEN_HITS`].
4256#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4257pub(crate) fn intra_rect_in_inter_screen_hits() -> usize {
4258 INTRA_RECT_IN_INTER_SCREEN_HITS.with(std::cell::Cell::get)
4259}
4260
4261/// Resets [`INTRA_RECT_IN_INTER_SCREEN_HITS`] before a decode.
4262#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4263pub(crate) fn reset_intra_rect_in_inter_screen_hits() {
4264 INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(0));
4265}
4266
4267/// Current value of [`INTRA_RECT_IN_INTER_SPLIT_TX_HITS`], indexed by tx depth.
4268#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4269pub(crate) fn intra_rect_in_inter_split_tx_hits() -> [usize; 3] {
4270 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
4271}
4272
4273// lane-midcut r2: rect intra blocks inside an inter frame whose `tx_depth` CDF
4274// ROW moved when libaom's inter-neighbour override was applied -- i.e. exactly
4275// the blocks the key frame's deblock-grid approximation used to mis-read.
4276thread_local! {
4277 static INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS: std::cell::Cell<usize> =
4278 const { std::cell::Cell::new(0) };
4279}
4280
4281/// Current value of [`INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS`].
4282#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
4283pub(crate) fn intra_rect_in_inter_txctx_override_hits() -> usize {
4284 INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS.with(std::cell::Cell::get)
4285}
4286
4287// lane-intra14 r1: how many intra-coded 1:4 strips decoded on the INTER
4288// block path, per shape -- [0] 64x16, [1] 16x64, [2] 32x8, [3] 8x32. Every
4289// one of them was the named refusal "an intra-coded 1:4 (or other non-2:1)
4290// rect strip on the inter block path" before this round.
4291thread_local! {
4292 static INTRA_RECT4_IN_INTER_HITS: std::cell::Cell<[usize; 4]> =
4293 const { std::cell::Cell::new([0; 4]) };
4294}
4295
4296/// Current value of [`INTRA_RECT4_IN_INTER_HITS`] for one shape
4297/// (0 = 64x16, 1 = 16x64, 2 = 32x8, 3 = 8x32).
4298pub(crate) fn intra_rect4_strip_in_inter_hits(shape: usize) -> usize {
4299 INTRA_RECT4_IN_INTER_HITS.with(|c| c.get()[shape])
4300}
4301
4302// lane-intra14 r1: set while an INTRA block of an INTER frame is decoded
4303// through one of the key-frame rect readers ([`decode_block_rect4`],
4304// [`decode_block_rect64`]). `Some((size_group, skip))` tells
4305// [`read_intra_mode_rect`] that (a) `skip`/segment id/cdef/delta-q were
4306// already read by [`decode_inter_block`] and (b) the luma mode comes off
4307// `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`,
4308// decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair.
4309
4310// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
4311// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
4312// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16
4313// slot -- i.e. how often the r5 defect would have picked the wrong CDF row.
4314thread_local! {
4315 static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
4316 const { std::cell::Cell::new(0) };
4317}
4318
4319/// Current value of [`MODE_MI_OVERRIDE_HITS`].
4320#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4321pub(crate) fn mode_mi_override_hits() -> usize {
4322 MODE_MI_OVERRIDE_HITS.with(|c| c.get())
4323}
4324
4325// lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a
4326// TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a
4327// mode from the previous tile, where libaom's `up_available`/`left_available`
4328// make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams:
4329// `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode`
4330// per superblock row in `start_row`, so the luma fallback cannot leak the way
4331// lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is
4332// the invariant that makes the coarse fallback safe.
4333thread_local! {
4334 static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell<usize> =
4335 const { std::cell::Cell::new(0) };
4336}
4337
4338/// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`].
4339#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4340pub(crate) fn mode_tile_edge_coarse_leaks() -> usize {
4341 MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get())
4342}
4343
4344// lane-cfl r1: how many times a chroma intra-edge filter-type read
4345// (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the
4346// mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the
4347// r1 defect would have filtered a chroma edge with the wrong strength.
4348thread_local! {
4349 static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
4350 const { std::cell::Cell::new(0) };
4351}
4352
4353/// Current value of [`UV_MODE_MI_OVERRIDE_HITS`].
4354#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4355pub(crate) fn uv_mode_mi_override_hits() -> usize {
4356 UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get())
4357}
4358
4359// lane-t900 r12: how many chroma edge-filter-type reads took their above/left
4360// `uv_mode` from the mi GRID where the one-slot-per-column map would have
4361// answered differently -- the sub-8x8 pair case where the pair's own first
4362// half had already overwritten the column slot the chroma-ref half reads.
4363thread_local! {
4364 static UV_MODE_GRID_OVERRIDE_HITS: std::cell::Cell<usize> =
4365 const { std::cell::Cell::new(0) };
4366}
4367
4368/// Current value of [`UV_MODE_GRID_OVERRIDE_HITS`].
4369pub fn uv_mode_grid_override_hits() -> usize {
4370 UV_MODE_GRID_OVERRIDE_HITS.with(|c| c.get())
4371}
4372
4373// lane-t900 r8: how many intra edge-filter-type reads (luma + chroma) the
4374// INTER neighbour stamp saved: the coarse SUB band still held a SMOOTH mode
4375// from an earlier block in that pixel row/column while the mi-exact map --
4376// which an inter block only started writing this round -- correctly says the
4377// neighbour is not smooth (libaom `is_smooth`: an inter neighbour's `mode` is
4378// an INTER mode, and its `uv_mode` "is not set for inter blocks").
4379thread_local! {
4380 static INTER_NEIGHBOUR_NOT_SMOOTH_HITS: std::cell::Cell<usize> =
4381 const { std::cell::Cell::new(0) };
4382}
4383
4384/// Current value of [`INTER_NEIGHBOUR_NOT_SMOOTH_HITS`].
4385#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4386pub(crate) fn inter_neighbour_not_smooth_hits() -> usize {
4387 INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|c| c.get())
4388}
4389
4390// lane-mtfix r1: how many times a chroma intra-edge filter-type read was
4391// suppressed at a TILE edge that is not a frame edge -- the above/left
4392// `uv_mode` neighbour of a block on a tile's first mi row/column lives in
4393// another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The
4394// coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per
4395// tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile
4396// above would decide this tile's chroma edge filter strength.
4397thread_local! {
4398 static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell<usize> =
4399 const { std::cell::Cell::new(0) };
4400}
4401
4402/// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`].
4403#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4404pub(crate) fn uv_tile_edge_suppressed_hits() -> usize {
4405 UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get())
4406}
4407
4408// lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs`
4409// read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block
4410// shapes the r1 chroma defect showed up on.
4411thread_local! {
4412 static CFL_BLOCK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4413 static UV_ANGLE_DELTA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4414}
4415
4416/// Current value of [`CFL_BLOCK_HITS`].
4417#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4418pub(crate) fn cfl_block_hits() -> usize {
4419 CFL_BLOCK_HITS.with(|c| c.get())
4420}
4421
4422/// Current value of [`UV_ANGLE_DELTA_HITS`].
4423#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4424pub(crate) fn uv_angle_delta_hits() -> usize {
4425 UV_ANGLE_DELTA_HITS.with(|c| c.get())
4426}
4427
4428// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
4429// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
4430// gate's proof this round's arms actually reached a real block, not just
4431// that `partition_w64` read one of those two symbol values.
4432thread_local! {
4433 static SB_RECT_HITS: std::cell::Cell<usize> =
4434 const { std::cell::Cell::new(0) };
4435}
4436
4437// Current value of [`SB_RECT_HITS`].
4438// lane-hgkf r1: the frame-edge partition bit, one level each. Slot 0 = a
4439// 64-level gathered edge bit read as HORZ/VERT, 1 = the same bit read as
4440// SPLIT, 2/3 = the 32-level pair. A gate asserting slot 0 or 2 proves the
4441// non-SPLIT edge arm actually decoded (before this round the bit was read and
4442// thrown away, so that arm was unreachable).
4443thread_local! {
4444 static EDGE_PART_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
4445}
4446
4447/// Current value of [`EDGE_PART_HITS`].
4448#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4449pub(crate) fn edge_part_hits() -> [usize; 4] {
4450 EDGE_PART_HITS.with(|c| c.get())
4451}
4452
4453/// Reset [`EDGE_PART_HITS`] (a gate counts one stream at a time).
4454#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4455pub(crate) fn reset_edge_part_hits() {
4456 EDGE_PART_HITS.with(|c| c.set([0; 4]));
4457}
4458
4459fn bump_edge_part(slot: usize) {
4460 hit_do! {
4461 EDGE_PART_HITS.with(|c| {
4462 let mut h = c.get();
4463 h[slot] += 1;
4464 c.set(h);
4465 });
4466 }
4467}
4468
4469#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4470pub(crate) fn sb_rect_hits() -> usize {
4471 SB_RECT_HITS.with(|c| c.get())
4472}
4473
4474// lane-golomb r2: the 32x32-level FRAME-EDGE partition. Slot 0/1 = the
4475// gathered edge bit read as 0 (HORZ/VERT) / 1 (SPLIT); slot 2 = a 32-level
4476// PARTITION_HORZ decoded with `has_rows32 == false` (only the top 32x16 half
4477// is coded), slot 3 = a PARTITION_VERT with `has_cols32 == false`. Both tile
4478// paths (intra and inter) feed the same counter.
4479//
4480// lane-golomb r3: slots 4..7 are the same four facts one level up, at the
4481// SUPERBLOCK (64x64) edge -- 4/5 = the gathered 64-level bit read as
4482// HORZ/VERT / SPLIT, 6 = a 64x32 bottom-edge strip decoded with
4483// `has_rows == false`, 7 = a 32x64 right-edge strip. Real aomenc answers a
4484// bottom-edge superblock with the 64-level HORZ (measured: 192x80 flat-band,
4485// every SB of the last row), so the 32-level slots stay 0 on that content and
4486// only these prove the arm fired.
4487thread_local! {
4488 static EDGE32_HITS: std::cell::Cell<[usize; 8]> =
4489 const { std::cell::Cell::new([0; 8]) };
4490}
4491
4492/// Current value of [`EDGE32_HITS`].
4493#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4494pub(crate) fn edge32_hits() -> [usize; 8] {
4495 EDGE32_HITS.with(|c| c.get())
4496}
4497
4498/// [`bump_edge32`] of `base + bit`, returning the bit -- the gathered edge
4499/// reads are `if`-conditions, so the counter has to ride the expression.
4500fn bump_edge32_bit(base: usize, bit: usize) -> usize {
4501 bump_edge32(base + bit.min(1));
4502 bit
4503}
4504
4505fn bump_edge32(slot: usize) {
4506 hit_do! {
4507 EDGE32_HITS.with(|c| {
4508 let mut h = c.get();
4509 h[slot] += 1;
4510 c.set(h)
4511 });
4512 }
4513}
4514
4515// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/
4516// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64
4517// strip) fired. Real aomenc picks these at 64 even with
4518// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is
4519// the counter the gate hard-asserts.
4520thread_local! {
4521 static SB_AB_HITS: std::cell::Cell<[usize; 4]> =
4522 const { std::cell::Cell::new([0; 4]) };
4523}
4524
4525/// Current value of [`SB_AB_HITS`], summed over the four arms.
4526#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4527pub(crate) fn sb_ab_hits() -> usize {
4528 SB_AB_HITS.with(|c| c.get().iter().sum())
4529}
4530
4531/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`,
4532/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a
4533/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as
4534/// proof of all four.
4535#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4536pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] {
4537 SB_AB_HITS.with(std::cell::Cell::get)
4538}
4539
4540// lane-tx64x16: the two 1:4 superblock arms, counted per orientation --
4541// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64
4542// strips). Two counters, not one, because a gate that only proved "some 1:4
4543// strip fired" would pass on a stream that never coded the other axis, and
4544// every scan/context table this round added comes in a transposed pair.
4545thread_local! {
4546 static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4547 static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4548}
4549
4550/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded).
4551#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4552pub(crate) fn sb_rect4_horz_hits() -> usize {
4553 SB_RECT4_HORZ_HITS.with(|c| c.get())
4554}
4555
4556/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded).
4557#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4558pub(crate) fn sb_rect4_vert_hits() -> usize {
4559 SB_RECT4_VERT_HITS.with(|c| c.get())
4560}
4561
4562// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation --
4563// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32
4564// strips), the arms the ReelB mid-film extract stops at.
4565thread_local! {
4566 static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4567 static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4568 /// lane-inter4 r1: the INTER-frame twins of the two counters above --
4569 /// four 32x8 / 8x32 inter strips of a 32x32-level `PARTITION_HORZ_4` /
4570 /// `PARTITION_VERT_4`.
4571 static RECT4_32_HORZ_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4572 static RECT4_32_VERT_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4573 /// lane-inter4 r1: superblock-level inter `PARTITION_HORZ`/`PARTITION_VERT`
4574 /// strips (64x32 / 32x64) and their 1:4 pair (64x16 / 16x64).
4575 static INTER_SB_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4576 static INTER_SB_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4577 static INTER_SB_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4578 static INTER_SB_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4579}
4580
4581// How many 32x32-level 1:4 strips actually read coefficients (non-skip):
4582// a gate that only counted strips would pass on an all-skip stream, which
4583// exercises none of the new scan/context tables.
4584thread_local! {
4585 static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4586}
4587
4588// lane-rectsplitx r1: 1:4 strips (32x8/8x32/64x16/16x64) decoded through the
4589// per-transform-unit split path, split by tx depth -- depth 1 is a 2:1 RECT
4590// unit (TX_16X8/TX_32X16), depth 2 a square one, and the two INTERLEAVE in
4591// every real stream, so a gate must prove both fired. `SUB16_SPLIT_HITS`
4592// counts the same for a 16x8/8x16 strip below 16x16.
4593thread_local! {
4594 static RECT4_SPLIT_DEPTH1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4595 static RECT4_SPLIT_DEPTH2_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4596 static SUB16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4597}
4598
4599/// Current values of `RECT4_SPLIT_DEPTH1_HITS` / `RECT4_SPLIT_DEPTH2_HITS`.
4600#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4601pub(crate) fn rect4_split_depth_hits() -> (usize, usize) {
4602 (
4603 RECT4_SPLIT_DEPTH1_HITS.with(|c| c.get()),
4604 RECT4_SPLIT_DEPTH2_HITS.with(|c| c.get()),
4605 )
4606}
4607
4608/// Current value of `SUB16_SPLIT_HITS`.
4609#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4610pub(crate) fn sub16_split_hits() -> usize {
4611 SUB16_SPLIT_HITS.with(|c| c.get())
4612}
4613
4614// lane-frame36 r2: superblock-level strips ([`decode_block_rect64`]) whose
4615// luma transform is SPLIT and which therefore leave through that fn's early
4616// return -- the arm that published no `TXFM_CONTEXT` band until this round.
4617thread_local! {
4618 static RECT64_SPLIT_TXFM_PUBLISH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4619}
4620
4621/// Current value of `RECT64_SPLIT_TXFM_PUBLISH_HITS`.
4622#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4623pub(crate) fn rect64_split_txfm_publish_hits() -> usize {
4624 RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.get())
4625}
4626
4627/// Current value of `RECT4_COEFF_HITS`.
4628pub(crate) fn rect4_coeff_hits() -> usize {
4629 RECT4_COEFF_HITS.with(|c| c.get())
4630}
4631
4632// lane-sbab r1: how many superblock-level (64x64) AB partitions fired IN AN
4633// INTER frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`,
4634// `_VERT_B` order (the intra-frame counterpart is `SB_AB_HITS`). Each arm is
4635// two 32x32 inter squares plus one true 64x32/32x64 inter strip; the gate
4636// asserts the arms it proves separately so a run whose RD only picked one
4637// cannot pass as proof of the others.
4638thread_local! {
4639 static SB_AB_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
4640}
4641
4642/// [`SB_AB_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 64x64 in an
4643/// inter frame).
4644pub fn sb_ab_inter_hits_by_arm() -> [usize; 4] {
4645 SB_AB_INTER_HITS.with(std::cell::Cell::get)
4646}
4647
4648// lane-inter16ab r1: how many 16x16-level AB partitions fired IN AN INTER
4649// frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B`
4650// order (the intra-frame counterpart is `AB16_HITS`). Each arm is two 8x8
4651// inter leaves (`decode_inter_block8`) plus one true 16x8/8x16 inter strip
4652// (`decode_inter_block` with `write_w`/`write_h`); the gate asserts every
4653// arm separately so a run whose RD only picked one cannot pass as proof of
4654// four.
4655thread_local! {
4656 static AB16_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
4657}
4658
4659/// [`AB16_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16 in an
4660/// inter frame).
4661pub fn ab16_inter_hits_by_arm() -> [usize; 4] {
4662 AB16_INTER_HITS.with(std::cell::Cell::get)
4663}
4664
4665// lane-inter16ab r2: the 16x16-level 1:4 pair as INTER blocks -- four 16x4
4666// (`PARTITION_HORZ_4`) or 4x16 (`PARTITION_VERT_4`) strips. `CHROMA_PAIRS`
4667// counts the odd strips that close a 4:2:0 chroma pair
4668// (`is_chroma_reference`, av1_common_int.h:1454: bh == 1 mi => odd mi_row),
4669// `SUB8_PIECES` the pair chroma blocks whose TOP (LEFT) half was built from
4670// the PREVIOUS strip's own mv/ref/filters -- libaom
4671// `build_inter_predictors_sub8x8` (reconinter_template.inc:87-160), reached
4672// through `is_sub8x8_inter` (same file, :54).
4673thread_local! {
4674 static INTER16_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4675 static INTER16_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4676 static INTER16_CHROMA_PAIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4677 static INTER16_SUB8_PIECE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4678}
4679
4680// lane-intra16x4: INTRA-coded strips of an inter 16x16-level 1:4 partition --
4681// [0] 16x4, [1] 4x16, [2] the odd (chroma-reference) ones, which carry the
4682// pair's single 8x4 (4x8) chroma unit for BOTH strips.
4683thread_local! {
4684 static INTRA16X4_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
4685 const { std::cell::Cell::new([0; 3]) };
4686}
4687
4688/// `(intra 16x4 strips, intra 4x16 strips, of which chroma-reference)` decoded
4689/// inside an INTER 16x16-level 1:4 partition (lane-intra16x4).
4690pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) {
4691 let v = INTRA16X4_IN_INTER_HITS.with(std::cell::Cell::get);
4692 (v[0], v[1], v[2])
4693}
4694
4695/// Current values of the inter 16x16-level 1:4 counters: `(16x4 strips, 4x16
4696/// strips, chroma pairs closed, chroma pairs built from two different
4697/// strips' motion vectors)`.
4698pub fn inter16_rect4_counters() -> (usize, usize, usize, usize) {
4699 (
4700 INTER16_HORZ4_HITS.with(std::cell::Cell::get),
4701 INTER16_VERT4_HITS.with(std::cell::Cell::get),
4702 INTER16_CHROMA_PAIR_HITS.with(std::cell::Cell::get),
4703 INTER16_SUB8_PIECE_HITS.with(std::cell::Cell::get),
4704 )
4705}
4706
4707/// One 16x4 / 4x16 inter strip's chroma situation, handed to
4708/// [`decode_inter_block`] out of band (the same one-shot thread-local idiom
4709/// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites
4710/// that all mean "an ordinary block, chroma of its own".
4711#[derive(Clone, Copy)]
4712pub(crate) struct InterStripChroma {
4713 /// `is_chroma_reference` for this strip: false on strips 0 and 2, which
4714 /// read and reconstruct NO chroma at all.
4715 has_chroma: bool,
4716 /// `PARTITION_HORZ_4` (16x4 strips) rather than `PARTITION_VERT_4`.
4717 horz: bool,
4718 /// The mi position of the EVEN strip of this pair -- `setup_pred_plane`'s
4719 /// `if (ss_y && (mi_row & 1) && mi_size_high[bsize] == 1) mi_row -= 1`,
4720 /// i.e. the origin of the 8x4 (4x8) chroma transform.
4721 pair_mi: (usize, usize),
4722 /// The previous (even) strip's single-reference MC parameters, `None`
4723 /// when it was intra or compound -- `is_sub8x8_inter` then returns false
4724 /// and the whole chroma block is predicted from THIS strip's mv.
4725 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
4726}
4727
4728 /// The single-reference MC parameters of the inter block that decoded
4729 /// last -- read by the next 1:4 strip to build its pair's chroma.
4730
4731fn bump_ab16_inter(arm: usize) {
4732 hit_do! {
4733 AB16_INTER_HITS.with(|c| {
4734 let mut v = c.get();
4735 v[arm] += 1;
4736 c.set(v);
4737 });
4738 }
4739}
4740
4741// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or
4742// 4x16 (`PARTITION_VERT_4`) strips, `CHROMA` counting the odd strips that
4743// close a 4:2:0 chroma pair and `COEFF` the strips with a coded residual.
4744thread_local! {
4745 static RECT4_16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4746 static RECT4_16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4747 static RECT4_16_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4748 static RECT4_16_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4749 static RECT4_16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4750 /// lane-kf1200: pairs whose chroma edge-filter type read from the PAIR's
4751 /// base mi differs from what the strip's own (odd) mi would have said --
4752 /// the shape that made 4 chroma samples of the ReelB `-ss 1200`
4753 /// key frame miss by 1. Zero here means a gate never exercised the fix.
4754 static RECT4_16_UV_PAIR_FILT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4755 /// lane-kf1200 r2: sub-8x8 chroma blocks that are `skip_txfm` AND
4756 /// `UV_CFL_PRED` -- the arm that used to drop the CfL alpha entirely.
4757 static SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4758}
4759
4760/// How many skipped sub-8x8 chroma blocks carried a CfL alpha (the shape
4761/// that reconstructed as flat DC before lane-kf1200 r2).
4762pub fn skip_cfl_hits() -> usize {
4763 SKIP_CFL_HITS.with(|c| c.get())
4764}
4765
4766/// How many 16x4/4x16 chroma pairs took a different `intra_edge_filter_type`
4767/// from the pair's base mi than the strip's own mi would have given.
4768pub fn rect4_16_uv_pair_filt_hits() -> usize {
4769 RECT4_16_UV_PAIR_FILT_HITS.with(|c| c.get())
4770}
4771
4772// lane-reelckf r1: the two chroma defects ReelC's key frames exposed --
4773// CHROMA_SKIP_CFL counts skipped intra blocks whose chroma is `UV_CFL_PRED`
4774// (prediction still runs, libaom `predict_and_reconstruct_intra_block`), and
4775// RECT4_16_CHROMA_DIR counts 1:4 chroma pairs predicted directionally (whose
4776// intra-edge filter type must come from the chroma-reference position).
4777thread_local! {
4778 static CHROMA_SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4779 static RECT4_16_CHROMA_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4780}
4781
4782/// `(skipped UV_CFL_PRED blocks, directional 1:4 chroma pairs)` -- lane-reelckf.
4783pub fn reelc_chroma_counters() -> (usize, usize) {
4784 (
4785 CHROMA_SKIP_CFL_HITS.with(|c| c.get()),
4786 RECT4_16_CHROMA_DIR_HITS.with(|c| c.get()),
4787 )
4788}
4789
4790/// Current values of the 16x16-level 1:4 counters: `(16x4 strips, 4x16
4791/// strips, chroma-reference strips, strips with a coded residual, strips
4792/// whose luma transform is split)`.
4793pub fn rect4_16_counters() -> (usize, usize, usize, usize, usize) {
4794 (
4795 RECT4_16_HORZ_HITS.with(|c| c.get()),
4796 RECT4_16_VERT_HITS.with(|c| c.get()),
4797 RECT4_16_CHROMA_HITS.with(|c| c.get()),
4798 RECT4_16_COEFF_HITS.with(|c| c.get()),
4799 RECT4_16_SPLIT_HITS.with(|c| c.get()),
4800 )
4801}
4802
4803/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded).
4804pub(crate) fn rect4_32_horz_hits() -> usize {
4805 RECT4_32_HORZ_HITS.with(|c| c.get())
4806}
4807
4808/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded).
4809pub(crate) fn rect4_32_vert_hits() -> usize {
4810 RECT4_32_VERT_HITS.with(|c| c.get())
4811}
4812
4813/// Current value of `RECT4_32_HORZ_INTER_HITS` (32x8 inter strips decoded).
4814pub(crate) fn rect4_32_horz_inter_hits() -> usize {
4815 RECT4_32_HORZ_INTER_HITS.with(|c| c.get())
4816}
4817
4818/// Current value of `RECT4_32_VERT_INTER_HITS` (8x32 inter strips decoded).
4819pub(crate) fn rect4_32_vert_inter_hits() -> usize {
4820 RECT4_32_VERT_INTER_HITS.with(|c| c.get())
4821}
4822
4823/// Current value of `INTER_SB_HORZ_HITS` (64x32 inter strips decoded).
4824pub(crate) fn inter_sb_horz_hits() -> usize {
4825 INTER_SB_HORZ_HITS.with(|c| c.get())
4826}
4827
4828/// Current value of `INTER_SB_VERT_HITS` (32x64 inter strips decoded).
4829pub(crate) fn inter_sb_vert_hits() -> usize {
4830 INTER_SB_VERT_HITS.with(|c| c.get())
4831}
4832
4833/// Current value of `INTER_SB_HORZ4_HITS` (64x16 inter strips decoded).
4834pub(crate) fn inter_sb_horz4_hits() -> usize {
4835 INTER_SB_HORZ4_HITS.with(|c| c.get())
4836}
4837
4838/// Current value of `INTER_SB_VERT4_HITS` (16x64 inter strips decoded).
4839pub(crate) fn inter_sb_vert4_hits() -> usize {
4840 INTER_SB_VERT4_HITS.with(|c| c.get())
4841}
4842
4843// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
4844// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
4845// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
4846// just inert-compiled. Zero forever on a passing gate means that gate's
4847// stream never carries `delta_q_present=1` through a rect64 block.
4848thread_local! {
4849 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
4850 const { std::cell::Cell::new(0) };
4851}
4852
4853/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
4854#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4855pub(crate) fn rect64_qidx_drift_hits() -> usize {
4856 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
4857}
4858
4859// lane-partab r1: how many 32x32 quadrants decoded an AB partition
4860// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
4861// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
4862// free-partition gate's proof this round's arms actually fired.
4863thread_local! {
4864 static PARTAB_HITS: std::cell::Cell<usize> =
4865 const { std::cell::Cell::new(0) };
4866}
4867
4868/// Current value of [`PARTAB_HITS`].
4869#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4870pub(crate) fn partab_hits() -> usize {
4871 PARTAB_HITS.with(|c| c.get())
4872}
4873
4874// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm,
4875// one counter per arm rather than one shared total -- the gate hard-asserts
4876// each of these individually nonzero so a recipe that only ever fires
4877// HORZ_A can't silently stand in for the whole set.
4878thread_local! {
4879 static INTRA_HORZ_A_HITS: std::cell::Cell<usize> =
4880 const { std::cell::Cell::new(0) };
4881 static INTRA_HORZ_B_HITS: std::cell::Cell<usize> =
4882 const { std::cell::Cell::new(0) };
4883 static INTRA_VERT_A_HITS: std::cell::Cell<usize> =
4884 const { std::cell::Cell::new(0) };
4885 static INTRA_VERT_B_HITS: std::cell::Cell<usize> =
4886 const { std::cell::Cell::new(0) };
4887}
4888
4889/// Current value of [`INTRA_HORZ_A_HITS`].
4890#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4891pub(crate) fn intra_horz_a_hits() -> usize {
4892 INTRA_HORZ_A_HITS.with(|c| c.get())
4893}
4894/// Current value of [`INTRA_HORZ_B_HITS`].
4895#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4896pub(crate) fn intra_horz_b_hits() -> usize {
4897 INTRA_HORZ_B_HITS.with(|c| c.get())
4898}
4899/// Current value of [`INTRA_VERT_A_HITS`].
4900#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4901pub(crate) fn intra_vert_a_hits() -> usize {
4902 INTRA_VERT_A_HITS.with(|c| c.get())
4903}
4904/// Current value of [`INTRA_VERT_B_HITS`].
4905#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4906pub(crate) fn intra_vert_b_hits() -> usize {
4907 INTRA_VERT_B_HITS.with(|c| c.get())
4908}
4909
4910// How many [`read_inter_compound_mode`] reads actually happened
4911// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
4912// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
4913// mvstack build), not just that `comp_mode` fired. Still refused right
4914// after (no MV assignment or MC wired), so this only counts attempted
4915// reads.
4916thread_local! {
4917 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
4918 const { std::cell::Cell::new(0) };
4919}
4920
4921/// Current value of [`COMPOUND_MODE_HITS`].
4922#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
4923pub(crate) fn compound_mode_hits() -> usize {
4924 COMPOUND_MODE_HITS.with(|c| c.get())
4925}
4926
4927/// How many query blocks folded in at least one temporal MV candidate
4928/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
4929/// temporal-MV gate's own firing counter (lane-av1tmvp).
4930///
4931/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
4932/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
4933/// this file (`decode_inter_block`) still passes `tpl: None` -- this
4934/// counter compiles and the projection math it counts is unit-tested
4935/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
4936/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
4937/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
4938/// against any real stream today. See the module doc on
4939/// `crate::motion_field` and this crate's ledger for the remaining wiring.
4940#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4941pub(crate) fn tmv_hits() -> usize {
4942 crate::mvstack::tmv_hits()
4943}
4944
4945/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
4946/// produced on this thread, the 10-bit inter gate's firing proof.
4947#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4948pub(crate) fn inter_pred_hits() -> usize {
4949 crate::mc::inter_pred_hits()
4950}
4951
4952/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
4953/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
4954/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
4955/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
4956/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
4957/// needs to turn a query block's own resolved `ref_frame` into
4958/// `TplArgs::cur_offset_0` (spec 7.9.3).
4959pub(crate) struct TplFrameArgs<'a> {
4960 pub field: &'a crate::motion_field::TplField,
4961 pub order_hint_bits: u32,
4962 pub order_hint: u32,
4963 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
4964 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
4965 /// frame's own `ref_frame_idx` names for each single reference.
4966 pub ref_order_hints: [u32; 7],
4967}
4968
4969/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
4970/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
4971/// decoded `grid`: every 4x4 unit an inter block covers reads the same
4972/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
4973/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
4974/// exact — every block this crate ever codes is at least 8x8, so no 8x8
4975/// cell straddles two different blocks' values.
4976#[allow(unsafe_code)] // lane-mf: `par::Shared` band split, same corner-cut as the filter stages
4977pub(crate) fn build_motion_field(
4978 grid: &MiGrid,
4979 mi_cols: usize,
4980 mi_rows: usize,
4981 order_hint: u32,
4982 order_hint_bits: u32,
4983 ref_order_hints: [u32; 7],
4984 fctx: &FrameCtx,
4985) -> crate::motion_field::MotionField {
4986 let mut field =
4987 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false);
4988 // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference
4989 // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other
4990 // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block
4991 // referencing one stores only its OTHER side's mv. With
4992 // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and
4993 // nothing is skipped.
4994 // lane-mf: hoisted out of the per-4x4-unit loop -- the answer depends
4995 // only on the reference frame, so it is 7 table lookups per frame instead
4996 // of two per inter unit.
4997 let other_side: [bool; 8] = std::array::from_fn(|rf| {
4998 let i = rf.wrapping_sub(LAST_FRAME as usize);
4999 order_hint_bits != 0
5000 && i < 7
5001 && (crate::motion_field::get_relative_dist(order_hint_bits, ref_order_hints[i], order_hint) > 0
5002 || ref_order_hints[i] == order_hint)
5003 });
5004 // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is
5005 // capped at 12 bits per component; a longer one is not stored at all.
5006 const REFMVS_LIMIT: i32 = (1 << 12) - 1;
5007 let (cols, rows, cells) = field.cells_mut();
5008 // Fills cell rows `r0..r1`; `out` is exactly those rows' cells, so bands
5009 // never touch each other (an 8x8 cell lives in one cell row, and mi row
5010 // `row` writes cell row `row / 2`).
5011 let fill = |r0: usize, r1: usize, out: &mut [Option<crate::motion_field::SavedMv>]| {
5012 for row in (r0 * 2)..(r1 * 2).min(mi_rows) {
5013 let out = &mut out[(row / 2 - r0) * cols..][..cols];
5014 for col in 0..mi_cols {
5015 let Some(info) = grid.get_frame(row, col) else {
5016 continue;
5017 };
5018 // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and
5019 // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`),
5020 // so an intra block -- or an inter block whose every slot is on the
5021 // other side / over the limit -- wipes what an earlier block wrote
5022 // into the same 8x8 cell (only reachable from sub-8x8 leaves, which
5023 // share a cell).
5024 if !info.is_inter {
5025 out[col / 2] = None;
5026 continue;
5027 }
5028 // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST
5029 // qualifying one wins -- a compound block stores its second
5030 // reference's mv, never its first (unless the second is on the
5031 // other side or over the limit). Storing slot 0 unconditionally
5032 // put the wrong (mv, ref_frame_offset) pair in every compound
5033 // block's cell, which a later frame's temporal candidate then
5034 // projected with the wrong reference distance.
5035 let mut saved: Option<crate::motion_field::SavedMv> = None;
5036 for (rf, mv) in [
5037 (info.ref_frame, Some(mv32(info.mv))),
5038 (info.ref_frame1.max(0), Some(mv32(info.mv1))),
5039 ] {
5040 let (Some(mv), true) = (mv, rf > 0) else {
5041 continue;
5042 };
5043 if other_side[rf as usize] {
5044 continue;
5045 }
5046 if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT {
5047 continue;
5048 }
5049 saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf });
5050 }
5051 out[col / 2] = saved;
5052 }
5053 }
5054 };
5055 // lane-mf: the whole-frame pass split over the filter pool in cell-row
5056 // bands (same `Shared` corner-cut as the filter stages -- disjointness is
5057 // the band arithmetic above, proved by the 1-vs-16-thread byte-exact gate).
5058 let bands = crate::par::bands(rows, crate::par::filter_threads());
5059 if bands.len() <= 1 {
5060 fill(0, rows, cells);
5061 } else {
5062 let shared = crate::par::Shared::new(cells);
5063 crate::par::run_bands(&bands, fctx, |r0, r1, _| {
5064 // SAFETY: cell rows `r0..r1` are this band's alone.
5065 let cells = unsafe { shared.get() };
5066 fill(r0, r1, &mut cells[r0 * cols..r1 * cols]);
5067 });
5068 }
5069 if crate::envflags::env_flag!("EC_TRACE_TPL") {
5070 eprintln!("EC_TPL_SAVED oh={order_hint}");
5071 for (r, row) in field.occupancy().iter().enumerate() {
5072 eprintln!("EC_TPL_SAVED r{r} {row}");
5073 }
5074 }
5075 field
5076}
5077
5078/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
5079/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
5080#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5081pub(crate) fn ref_hits(ref_frame: i8) -> usize {
5082 let c = match ref_frame {
5083 LAST2_FRAME => &LAST2_HITS,
5084 LAST3_FRAME => &LAST3_HITS,
5085 GOLDEN_FRAME => &GOLDEN_HITS,
5086 BWDREF_FRAME => &BWDREF_HITS,
5087 ALTREF2_FRAME => &ALTREF2_HITS,
5088 ALTREF_FRAME => &ALTREF_HITS,
5089 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
5090 };
5091 c.with(|v| v.get())
5092}
5093
5094 /// The sequence header's `enable_intra_edge_filter`, set once per
5095 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
5096 /// own read of it, kept off the call stack (see that function's own doc
5097 /// comment for why) rather than threaded through every `read_plane`/
5098 /// `decode_block`/`decode_leaf8` call between here and there.
5099
5100/// Set [`ENABLE_EDGE_FILTER`] for this thread.
5101///
5102/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
5103/// never did -- so an inter frame's intra blocks read whatever value the last
5104/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
5105/// harmless (its own key frame sets it first), but a caller that decodes an
5106/// inter frame directly, or a test harness running several streams on one
5107/// thread, inherits a foreign sequence's bit: decode stops being a pure
5108/// function of the bitstream. `decode_stream` now calls this once per stream
5109/// from the sequence header, which covers every frame including inter ones.
5110pub(crate) fn set_enable_edge_filter(value: bool, fctx: &crate::decode::FrameCtx) {
5111 fctx.enable_edge_filter.with(|f| f.set(value));
5112}
5113
5114/// Current value of [`ANGLE_DELTA_HITS`].
5115#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5116pub(crate) fn angle_delta_hits() -> usize {
5117 ANGLE_DELTA_HITS.with(|c| c.get())
5118}
5119
5120/// Current value of [`TX_CLASS1_HITS`].
5121#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5122pub(crate) fn tx_class1_hits() -> usize {
5123 TX_CLASS1_HITS.with(|c| c.get())
5124}
5125
5126// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent
5127// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion
5128// bottom) this thread's decode actually reconstructed -- the same
5129// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream
5130// genuinely exercised the sub-8x8 leaf path rather than every attempt
5131// coincidentally landing on `PARTITION_NONE`.
5132thread_local! {
5133 static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5134 /// How many 8x8 groups an INTER frame split into four BLOCK_4X4 inter
5135 /// sub-blocks (lane-intersub8).
5136 static SUB8_INTER_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5137 /// How many 8x8 groups an INTER frame split into two rectangular sub-8x8
5138 /// inter leaves (lane-intersub8 r3), indexed `[0] = HORZ` (two BLOCK_8X4),
5139 /// `[1] = VERT` (two BLOCK_4X8).
5140 static SUB8_INTER_RECT_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
5141 /// lane-sub8intra: INTRA leaves decoded inside an inter frame's sub-8x8
5142 /// HORZ/VERT partition -- `[0]` 8x4, `[1]` 4x8, `[2]` of those that were
5143 /// the chroma reference (so coded the group's 4x4 chroma intra), `[3]`
5144 /// MIXED groups whose chroma reference is INTER while its sibling is
5145 /// intra (the `is_sub8x8_inter` false path), `[4]` INTRA `BLOCK_4X4`
5146 /// leaves of an inter frame's sub-8x8 `PARTITION_SPLIT` (lane-sub8x4 r2 --
5147 /// the second lifted refusal's own witness; `[0]`/`[1]` count those too,
5148 /// so only this cell separates the split arm from the HORZ/VERT one).
5149 static SUB8_INTRA_RECT_HITS: std::cell::Cell<[usize; 5]> = const { std::cell::Cell::new([0; 5]) };
5150}
5151
5152/// Current value of [`SUB8_INTRA_RECT_HITS`]: `(8x4, 4x8, chroma-reference,
5153/// mixed groups, split 4x4 leaves)`.
5154pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) {
5155 SUB8_INTRA_RECT_HITS.with(|c| {
5156 let h = c.get();
5157 (h[0], h[1], h[2], h[3], h[4])
5158 })
5159}
5160
5161/// Current value of [`SUB8_INTER_RECT_HITS`]: `(8x4 groups, 4x8 groups)`.
5162pub fn sub8_inter_rect_hits() -> (usize, usize) {
5163 SUB8_INTER_RECT_HITS.with(|c| {
5164 let h = c.get();
5165 (h[0], h[1])
5166 })
5167}
5168
5169// lane-cdef r1: (a) how many 8x8 CDEF units `apply_cdef` EXCLUDED because all
5170// four of their mi cells are `skip_txfm` (libaom `cdef.c:29-38`
5171// `is_8x8_block_skip` / `av1_cdef_compute_sb_list`'s dlist test), and (b) how
5172// many 8x8 inter leaves (`decode_inter_block8`) wrote that skip band at all.
5173// (b) was 0 for every stream before this round -- the leaf path never touched
5174// the band, so an all-skip 8x8 group kept the PREVIOUS frame's flags and got
5175// filtered where libaom skips it. A gate asserts both are non-zero.
5176thread_local! {
5177 static CDEF_SKIPPED_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5178 static INTER8_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5179 // lane-cdef r2: (c) 8x8 CDEF units that are FILTERED and whose extent
5180 // crosses the cropped frame edge -- the only units for which "clamp at
5181 // the crop" and "pad past the mi-rounded extent with CDEF_VERY_LARGE"
5182 // (libaom `cdef.c:249-256`, `cdef_prepare_fb`'s hsize/vsize are
5183 // `nhb << mi_wide_l2` off the MI grid, not the crop) differ. A frame
5184 // whose width or height is not a multiple of 8 is the only shape that
5185 // produces one; the straddling-band gate arms assert it grew.
5186 static CDEF_STRADDLE_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5187 // lane-cdefstrip r1: 8x8 CDEF units visited with an UNWRITTEN skip band
5188 // (see `Neighbours::skip_written`).
5189 static CDEF_UNWRITTEN_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5190 // lane-cdefstrip r1: (d) skip RECTANGULAR blocks (every strip arm: 32x8,
5191 // 8x32, 16x8, 32x16, 64x16, AB/1:4 pieces...) that wrote the CDEF skip
5192 // band, and (e) 8x8 CDEF units whose four mi cells do NOT agree on skip --
5193 // the shape libaom's `is_8x8_block_skip` (`cdef.c:29-38`) exists for: an
5194 // 8-tall strip pair where only one half is skip must still be FILTERED.
5195 static RECT_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5196 static CDEF_MIXED_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5197}
5198
5199/// Current value of `RECT_SKIP_BAND_HITS`.
5200pub fn rect_skip_band_hits() -> usize {
5201 RECT_SKIP_BAND_HITS.with(|c| c.get())
5202}
5203
5204/// Current value of `CDEF_MIXED_SKIP_UNITS`.
5205pub fn cdef_mixed_skip_units() -> usize {
5206 CDEF_MIXED_SKIP_UNITS.with(|c| c.get())
5207}
5208
5209/// Current value of `CDEF_SKIPPED_UNITS`.
5210#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5211pub(crate) fn cdef_skipped_units() -> usize {
5212 CDEF_SKIPPED_UNITS.with(|c| c.get())
5213}
5214
5215/// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded
5216/// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1).
5217pub fn cdef_unwritten_skip_units() -> usize {
5218 CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get())
5219}
5220
5221/// Current value of `INTER8_SKIP_BAND_HITS`.
5222#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5223pub(crate) fn inter8_skip_band_hits() -> usize {
5224 INTER8_SKIP_BAND_HITS.with(|c| c.get())
5225}
5226
5227/// Current value of `CDEF_STRADDLE_UNITS`.
5228#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5229pub(crate) fn cdef_straddle_units() -> usize {
5230 CDEF_STRADDLE_UNITS.with(|c| c.get())
5231}
5232
5233/// Current value of [`SUB8_SPLIT_HITS`].
5234#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5235pub(crate) fn sub8_split_hits() -> usize {
5236 SUB8_SPLIT_HITS.with(|c| c.get())
5237}
5238
5239/// Current value of [`SUB8_INTER_SPLIT_HITS`].
5240pub fn sub8_inter_split_hits() -> usize {
5241 SUB8_INTER_SPLIT_HITS.with(|c| c.get())
5242}
5243
5244// lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherits a
5245// `tx_type` DIFFERENT from the group's FIRST sub-block -- the only shape that
5246// tells the two rules apart (`av1_get_tx_type` indexes `xd->tx_type_map`,
5247// which `set_mi_offsets` re-points to the CHROMA-REFERENCE sub-block, so the
5248// first sub-block's type is never the one). Reading it off sub-block 0
5249// inverted one 4x4 chroma unit on the wrong basis with the entropy stream
5250// perfectly in sync (no chroma `tx_type` symbol is coded), so a gate can only
5251// see this rule through this counter.
5252thread_local! {
5253 static SUB8_CHROMA_TX_FROM_REF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5254}
5255
5256/// Current value of `SUB8_CHROMA_TX_FROM_REF_HITS`.
5257pub fn sub8_chroma_tx_from_ref_hits() -> usize {
5258 SUB8_CHROMA_TX_FROM_REF_HITS.with(|c| c.get())
5259}
5260
5261fn note_sub8_chroma_tx(first_sub: TxType, chroma_ref: TxType, coeffs: bool) {
5262 if coeffs && first_sub != chroma_ref {
5263 hit!(SUB8_CHROMA_TX_FROM_REF_HITS);
5264 }
5265}
5266
5267// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ`
5268// of an 8x8 block) this thread's decode reconstructed with REAL coefficients
5269// -- a skipped leaf exercises the prediction and the mi bookkeeping but never
5270// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate
5271// asserts on these two rather than a plain leaf count.
5272thread_local! {
5273 static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5274 static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5275 /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's
5276 /// two 4x4 transform units, predicted one after the other. A separate
5277 /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so
5278 /// the gate can prove THIS path fired.
5279 static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5280 /// 16x8/8x16 intra strips whose prediction actually read past the block's
5281 /// own width (above-right) or height (below-left) -- the samples
5282 /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/
5283 /// `has_bl_*` table row can corrupt (lane-tx4x8 r3).
5284 static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5285 /// Every 16x8/8x16 intra strip predicted, reaching or not -- the
5286 /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of.
5287 static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5288}
5289
5290/// Current value of [`RECT8_SPLIT_TX_HITS`].
5291#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5292pub(crate) fn rect8_split_tx_hits() -> usize {
5293 RECT8_SPLIT_TX_HITS.with(|c| c.get())
5294}
5295
5296/// Current value of [`RECT_STRIP_PRED_HITS`].
5297#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5298pub(crate) fn rect_strip_pred_hits() -> usize {
5299 RECT_STRIP_PRED_HITS.with(|c| c.get())
5300}
5301
5302/// Current value of [`RECT_STRIP_REACH_HITS`].
5303#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5304pub(crate) fn rect_strip_reach_hits() -> usize {
5305 RECT_STRIP_REACH_HITS.with(|c| c.get())
5306}
5307
5308/// Current value of [`TX4X8_CODED_HITS`].
5309#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5310pub(crate) fn tx4x8_coded_hits() -> usize {
5311 TX4X8_CODED_HITS.with(|c| c.get())
5312}
5313
5314/// Current value of [`TX8X4_CODED_HITS`].
5315#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5316pub(crate) fn tx8x4_coded_hits() -> usize {
5317 TX8X4_CODED_HITS.with(|c| c.get())
5318}
5319
5320// How many CHROMA coefficient blocks read their `eob_pt` from the class-1
5321// (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread.
5322// Chroma never codes a `tx_type` symbol -- it inherits the colocated luma
5323// type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on
5324// an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired
5325// (`eob_pt_{16,64,128,256}_chroma_class1`).
5326thread_local! {
5327 static CHROMA_EOB_CLASS1_HITS: std::cell::Cell<usize> =
5328 const { std::cell::Cell::new(0) };
5329}
5330
5331/// Current value of [`CHROMA_EOB_CLASS1_HITS`].
5332#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5333pub(crate) fn chroma_eob_class1_hits() -> usize {
5334 CHROMA_EOB_CLASS1_HITS.with(|c| c.get())
5335}
5336
5337/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
5338/// `tx_type` put this block's `eob_pt` on the class-1 row.
5339fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
5340 if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD {
5341 hit!(CHROMA_EOB_CLASS1_HITS);
5342 }
5343}
5344
5345const SUB_MI: u32 = 4;
5346const MI: usize = 4;
5347const SB: usize = 64;
5348/// The `above_side`/`left_side` value a cell with no decoded neighbour holds
5349/// (tile start, superblock-row start).
5350///
5351/// [`Neighbours::partition_ctx_mi`] reads it as libaom's
5352/// `av1_get_partition_plane_context` reads its own zero-initialised
5353/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at
5354/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB`
5355/// (64), which reads identically at every level up to 64x64 but sets the bit
5356/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition
5357/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec
5358/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`).
5359const NO_NEIGHBOUR_SIDE: usize = 128;
5360const BLOCK: usize = 32;
5361const SUB: usize = 16;
5362const TX32: usize = 32;
5363const TX16: usize = 16;
5364const TX8: usize = 8;
5365const TX4: usize = 4;
5366const DC_PRED: usize = 0;
5367/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
5368/// carries an angle delta — [`crate::tile`]'s own private copy of the same
5369/// constant.
5370const V_PRED: usize = 1;
5371const H_PRED: usize = 2;
5372/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
5373/// `Fimode_To_Intradir`, libaom `blockd.h`).
5374const D157_PRED: usize = 6;
5375/// The last directional mode, `D67_PRED`.
5376const D67_PRED: usize = 8;
5377/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
5378/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
5379/// codes anything else, so this decoder never reads anything else either.
5380const ANGLE_DELTA_ZERO: usize = 3;
5381const NUM_BASE_LEVELS: i32 = 2;
5382const COEFF_BASE_RANGE: i32 = 12;
5383const BR_STEP: i32 = 3;
5384const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
5385
5386/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
5387/// whose probability mass a superblock or block half outside the frame
5388/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
5389/// duplicated here (that module is another lane's territory this round) and
5390/// kept in step with it by the byte-exact round-trip tests below rather than
5391/// by sharing code.
5392const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
5393const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
5394
5395fn trace_edge(mi_r: usize, mi_c: usize, bsize: u32, ctx: usize, rng: u32) {
5396 if crate::envflags::env_flag!("EC_AV1_TRACE") {
5397 eprintln!("OUR_PART mi_row={mi_r} mi_col={mi_c} bsize={bsize} ctx={ctx} rng={rng}");
5398 }
5399}
5400
5401fn element_prob(cdf: &[u16], element: usize) -> u16 {
5402 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
5403}
5404
5405/// The two-symbol CDF a partial superblock/block's forced-split flag is read
5406/// with: the mass of `elements` becomes the probability of the one partition
5407/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
5408/// (the encoder's non-adapting counterpart to this read).
5409fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
5410 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
5411 [32768 - split, 32768, 0]
5412}
5413
5414fn unsupported(what: impl Into<String>) -> Error {
5415 Error::unsupported("AV1 tile", what.into())
5416}
5417
5418/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
5419/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
5420/// same rule.
5421pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
5422 match base_q_idx {
5423 0..=20 => 0,
5424 21..=60 => 1,
5425 61..=120 => 2,
5426 _ => 3,
5427 }
5428}
5429
5430/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
5431/// [`crate::tile`]'s writer generates its scan tables with.
5432fn default_scan(side: usize) -> &'static [u16] {
5433 // One table per transform side (4/8/16/32), built once: this used to be a
5434 // fresh heap allocation plus the whole anti-diagonal walk on every
5435 // transform block read.
5436 static SCANS: std::sync::LazyLock<[Vec<u16>; 4]> = std::sync::LazyLock::new(|| {
5437 [
5438 default_scan_gen(4),
5439 default_scan_gen(8),
5440 default_scan_gen(16),
5441 default_scan_gen(32),
5442 ]
5443 });
5444 assert!(
5445 matches!(side, 4 | 8 | 16 | 32),
5446 "no default scan for a {side}-point transform"
5447 );
5448 &SCANS[side.trailing_zeros() as usize - 2]
5449}
5450
5451fn default_scan_gen(side: usize) -> Vec<u16> {
5452 let mut scan = Vec::with_capacity(side * side);
5453 for d in 0..(2 * side - 1) {
5454 let lo = d.saturating_sub(side - 1);
5455 let hi = d.min(side - 1);
5456 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
5457 if d % 2 == 0 {
5458 scan.extend(diagonal.rev());
5459 } else {
5460 scan.extend(diagonal);
5461 }
5462 }
5463 scan
5464}
5465
5466/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
5467/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
5468/// in, instead of the default zigzag. libaom's own tables are keyed by a
5469/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
5470/// physically column-major level buffer, but they decompose to the exact
5471/// same (row, col) walk as a flat row-major traversal of *our* row-major
5472/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
5473/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
5474/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
5475/// transposed (column 0 down every row, then column 1, ...).
5476fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
5477 class_scan_table_wh(side, side, class)
5478}
5479
5480/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
5481/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
5482/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
5483/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
5484/// transcribed with -- `mrow` is the plain row-major raster in our indexing
5485/// and `mcol` its transpose, at rect sizes exactly as at square ones.
5486fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
5487 match class {
5488 TxClass::Vert => (0..(w * h) as u16).collect(),
5489 TxClass::Horiz => (0..w)
5490 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
5491 .collect(),
5492 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
5493 }
5494}
5495
5496fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
5497 match scan_idx {
5498 0 => 0,
5499 i if i <= area / 8 => 1,
5500 i if i <= area / 4 => 2,
5501 _ => 3,
5502 }
5503}
5504
5505/// One cell of [`read_coeffs`]'s level buffer.
5506///
5507/// lane-coef2: the buffer is now PADDED (libaom's `TX_PAD_HOR`/`TX_PAD_VER`,
5508/// `txb_common.h`) -- four zero columns to the right of `side` and four zero
5509/// rows below it, at a fixed `stride = side + 4` -- so the four-away reads
5510/// `base_ctx` makes (`(0, 4)`/`(4, 0)` are its widest offsets) land on real
5511/// zero cells instead of needing the `row >= side || col >= side` edge test
5512/// this used to run five times per coefficient. Nothing writes a padding
5513/// cell, so the values are the same zeros the test returned.
5514#[inline]
5515fn neighbour(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
5516 grid[row * stride + col] as i32
5517}
5518
5519/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
5520/// `txb_common.h`): everything but the two lone-axis-identity types this
5521/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
5522#[derive(Clone, Copy, PartialEq, Eq)]
5523enum TxClass {
5524 TwoD,
5525 Horiz,
5526 Vert,
5527}
5528
5529impl TxClass {
5530 fn of(tx_type: TxType) -> Self {
5531 match tx_type {
5532 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
5533 // key on axis alone -- FLIPADST is still ADST for this purpose.
5534 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
5535 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
5536 _ => Self::TwoD,
5537 }
5538 }
5539}
5540
5541/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
5542/// table (indexed by the position along the transform's *coded* axis --
5543/// `col` for horiz, `row` for vert) that places their contexts past the 2D
5544/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
5545/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
5546fn nz_map_ctx_offset_1d(i: usize) -> usize {
5547 match i {
5548 0 => 26,
5549 1 => 31,
5550 _ => 36,
5551 }
5552}
5553
5554fn base_ctx(
5555 grid: &[u8],
5556 stride: usize,
5557 row: usize,
5558 col: usize,
5559 class: TxClass,
5560 rect_shape: Option<(usize, usize)>,
5561) -> usize {
5562 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
5563 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
5564 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
5565 // position through the full 1D neighbour sum and offset table. Skipping
5566 // that for every class desynced the last (DC) coefficient of a
5567 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
5568 // 0, which then read one extra `BR` symbol at the max and forced a
5569 // spurious third Golomb call).
5570 if class == TxClass::TwoD && row == 0 && col == 0 {
5571 return 0;
5572 }
5573 let offsets: [(usize, usize); 5] = match class {
5574 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
5575 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
5576 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
5577 };
5578 let mag: i32 = offsets
5579 .iter()
5580 .map(|&(dr, dc)| neighbour(grid, stride, row + dr, col + dc).min(3))
5581 .sum();
5582 let ctx = ((mag + 1) >> 1).min(4) as usize;
5583 match class {
5584 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
5585 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
5586 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
5587 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
5588 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
5589 // strip, which own a genuinely different table from the square one
5590 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
5591 // square table vs the real ctx 13 the rect table gives).
5592 TxClass::TwoD => {
5593 // lane-rectsplit r4: apply libaom's GENERATING RULE
5594 // (`txb_common.h:199-209`) directly instead of indexing the
5595 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
5596 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
5597 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
5598 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
5599 // so 32 consecutive entries are one COLUMN: the [`cdf`]
5600 // transcriptions are `[col][row]` and this read had them as
5601 // `[row][col]` -- the transpose, i.e. the other shape's rule with
5602 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
5603 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
5604 // pins the rule against the tables over their whole 5x5 domain.
5605 if let Some((w, h)) = rect_shape {
5606 if crate::envflags::env_flag!("EC_NZOFF_DUMP") {
5607 eprintln!("NZOFF stride={stride} shape={w}x{h} row={row} col={col}");
5608 }
5609 if w < h && row < 2 {
5610 return ctx + 11;
5611 }
5612 if w > h && col < 2 {
5613 return ctx + 16;
5614 }
5615 }
5616 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
5617 }
5618 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
5619 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
5620 }
5621}
5622
5623/// The five `base_ctx` neighbour taps and the three `br_ctx` ones as FLAT
5624/// offsets into the padded level frame (lane-coefread): the tap pattern is a
5625/// function of the tx class alone, which is fixed for a whole transform unit,
5626/// so resolving it once per unit takes the class match and the `(dr, dc)`
5627/// -> `dr * stride + dc` arithmetic out of the per-coefficient path. Same
5628/// taps as [`base_ctx`]/[`br_ctx`] read, stated once;
5629/// `flat_taps_match_the_row_col_neighbour_reads` pins them against the
5630/// original `(dr, dc)` form.
5631fn flat_taps(stride: usize, class: TxClass) -> ([usize; 5], [usize; 3]) {
5632 match class {
5633 TxClass::TwoD => (
5634 [stride, 1, stride + 1, 2 * stride, 2],
5635 [stride, 1, stride + 1],
5636 ),
5637 TxClass::Horiz => ([stride, 1, 2, 3, 4], [stride, 1, 2]),
5638 TxClass::Vert => (
5639 [stride, 1, 2 * stride, 3 * stride, 4 * stride],
5640 [stride, 1, 2 * stride],
5641 ),
5642 }
5643}
5644
5645/// [`base_ctx`]'s neighbour sum, off flat taps: `((sum of five clamped
5646/// neighbours) + 1) >> 1`, clamped to 4.
5647#[inline(always)]
5648fn base_mag(grid: &[u8], idx: usize, taps: &[usize; 5]) -> usize {
5649 let mut mag = 0u32;
5650 for &t in taps {
5651 mag += u32::from(grid[idx + t]).min(3);
5652 }
5653 (((mag + 1) >> 1) as usize).min(4)
5654}
5655
5656/// [`br_ctx`]'s neighbour sum, off flat taps.
5657#[inline(always)]
5658fn br_mag(grid: &[u8], idx: usize, taps: &[usize; 3]) -> usize {
5659 let mut mag = 0u32;
5660 for &t in taps {
5661 mag += u32::from(grid[idx + t]);
5662 }
5663 (((mag + 1) >> 1) as usize).min(6)
5664}
5665
5666/// lane-coefread: superseded on the decode path by [`br_mag`] plus the
5667/// origin-offset tail the two coefficient readers state inline; kept as the
5668/// `(row, col)` form `flat_taps_match_the_row_col_neighbour_reads` pins the
5669/// flat one against.
5670#[cfg(test)]
5671fn br_ctx(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize {
5672 let extra = match class {
5673 TxClass::TwoD => neighbour(grid, stride, row + 1, col + 1),
5674 TxClass::Horiz => neighbour(grid, stride, row, col + 2),
5675 TxClass::Vert => neighbour(grid, stride, row + 2, col),
5676 };
5677 let mag = neighbour(grid, stride, row + 1, col)
5678 + neighbour(grid, stride, row, col + 1)
5679 + extra;
5680 let mag = (((mag + 1) >> 1).min(6)) as usize;
5681 if row == 0 && col == 0 {
5682 return mag;
5683 }
5684 let near_origin = match class {
5685 TxClass::TwoD => row < 2 && col < 2,
5686 TxClass::Horiz => col == 0,
5687 TxClass::Vert => row == 0,
5688 };
5689 if near_origin { mag + 7 } else { mag + 14 }
5690}
5691
5692/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
5693/// transposed from libaom's column-major buffer into this decoder's row-major
5694/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
5695/// against the real table). Not the square zigzag formula generalized to
5696/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
5697const SCAN_32X16: [u16; 512] = [
5698 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161,
5699 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39,
5700 8, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72,
5701 41, 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229,
5702 198, 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44,
5703 13, 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418,
5704 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326,
5705 295, 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234,
5706 203, 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142,
5707 111, 80, 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19,
5708 485, 454, 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424,
5709 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332,
5710 301, 270, 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240,
5711 209, 178, 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148,
5712 117, 86, 55, 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25,
5713 491, 460, 429, 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430,
5714 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338,
5715 307, 276, 245, 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246,
5716 215, 184, 153, 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154,
5717 123, 92, 61, 30, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31,
5718 497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405,
5719 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251,
5720 220, 189, 158, 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439,
5721 408, 377, 346, 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503,
5722 472, 441, 410, 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443,
5723 412, 381, 350, 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415,
5724 509, 478, 447, 510, 479, 511,
5725];
5726
5727/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
5728/// [`SCAN_32X16`]'s doc comment).
5729const SCAN_16X32: [u16; 512] = [
5730 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,
5731 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
5732 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
5733 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
5734 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
5735 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
5736 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
5737 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
5738 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
5739 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
5740 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
5741 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
5742 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
5743 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
5744 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
5745 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
5746 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
5747 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
5748 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
5749 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
5750 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
5751 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
5752 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
5753 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
5754 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
5755 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
5756];
5757
5758/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
5759/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
5760/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
5761/// the same source).
5762const SCAN_4X8: [u16; 32] = [
5763 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,
5764 23, 26, 29, 27, 30, 31,
5765];
5766
5767/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
5768const SCAN_8X4: [u16; 32] = [
5769 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,
5770 29, 22, 15, 30, 23, 31,
5771];
5772
5773/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
5774/// [`SCAN_32X16`]'s doc comment).
5775const SCAN_16X8: [u16; 128] = [
5776 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,
5777 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
5778 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
5779 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
5780 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
5781 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
5782];
5783
5784/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
5785/// [`SCAN_32X16`]'s doc comment).
5786const SCAN_8X16: [u16; 128] = [
5787 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,
5788 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
5789 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
5790 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
5791 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
5792 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
5793];
5794
5795/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
5796/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
5797/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
5798/// scans column-major (`p = col * height + row`), so a naive copy of
5799/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
5800/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
5801/// are byte-identical to this decoder's [`SCAN_8X16`].
5802const SCAN_32X8: [u16; 256] = [
5803 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
5804 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226, 195,
5805 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104, 73, 42,
5806 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200, 169,
5807 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78, 47, 16,
5808 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205, 174, 143,
5809 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83, 52, 21, 239,
5810 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210, 179, 148, 117,
5811 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88, 57, 26, 244, 213,
5812 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215, 184, 153, 122, 91,
5813 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93, 62, 31, 249, 218, 187,
5814 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127, 252, 221, 190, 159, 253,
5815 222, 191, 254, 223, 255,
5816];
5817/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
5818/// 16x64 `PARTITION_VERT_4` strip).
5819const SCAN_8X32: [u16; 256] = [
5820 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,
5821 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
5822 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
5823 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
5824 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
5825 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
5826 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
5827 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
5828 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
5829 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
5830 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
5831 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
5832 239, 246, 253, 247, 254, 255,
5833];
5834/// `Default_Scan_16x4`, this decoder's own row-major transcription of
5835/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
5836/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
5837/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
5838/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
5839/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
5840/// were emitted -- a naive copy installs the transpose (class
5841/// reference-layout-not-spec).
5842const SCAN_16X4: [u16; 64] = [
5843 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,
5844 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
5845 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
5846];
5847/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
5848/// 8x32 `PARTITION_VERT_4` strip).
5849const SCAN_4X16: [u16; 64] = [
5850 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,
5851 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
5852 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
5853];
5854
5855/// [`neighbour`]'s rect form (lane-rectwire): same lane-coef2 padding
5856/// (`stride = w + 4`, four spare rows), so the edge test is the zeros the
5857/// padding already holds.
5858#[inline]
5859fn neighbour_rect(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
5860 grid[row * stride + col] as i32
5861}
5862
5863/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
5864/// the rect generalization is libaom's own comment in
5865/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
5866/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
5867/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
5868/// [`decode_block_rect`] codes (see that function's own doc comment).
5869fn base_ctx_rect(
5870 grid: &[u8],
5871 stride: usize,
5872 w: usize,
5873 h: usize,
5874 row: usize,
5875 col: usize,
5876 class: TxClass,
5877) -> usize {
5878 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
5879 // the 2D class short-circuits the DC position.
5880 if class == TxClass::TwoD && row == 0 && col == 0 {
5881 return 0;
5882 }
5883 let offsets: [(usize, usize); 5] = match class {
5884 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
5885 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
5886 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
5887 };
5888 let mag: i32 = offsets
5889 .iter()
5890 .map(|&(dr, dc)| neighbour_rect(grid, stride, row + dr, col + dc).min(3))
5891 .sum();
5892 let ctx = ((mag + 1) >> 1).min(4) as usize;
5893 match class {
5894 TxClass::TwoD => {
5895 if w < h && row < 2 {
5896 return ctx + 11;
5897 }
5898 if w > h && col < 2 {
5899 return ctx + 16;
5900 }
5901 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
5902 }
5903 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
5904 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
5905 // position along one axis only).
5906 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
5907 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
5908 }
5909}
5910
5911/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
5912/// neighbour-offset math itself is shape-independent, only the boundary
5913/// clamp needs the real bound in each axis.
5914/// lane-coefread: superseded by [`br_mag`] on the rect decode path too --
5915/// its body was character-for-character [`br_ctx`]'s, which
5916/// `flat_taps_match_the_row_col_neighbour_reads` now asserts.
5917#[cfg(test)]
5918fn br_ctx_rect(
5919 grid: &[u8],
5920 stride: usize,
5921 row: usize,
5922 col: usize,
5923 class: TxClass,
5924) -> usize {
5925 let extra = match class {
5926 TxClass::TwoD => neighbour_rect(grid, stride, row + 1, col + 1),
5927 TxClass::Horiz => neighbour_rect(grid, stride, row, col + 2),
5928 TxClass::Vert => neighbour_rect(grid, stride, row + 2, col),
5929 };
5930 let mag = neighbour_rect(grid, stride, row + 1, col)
5931 + neighbour_rect(grid, stride, row, col + 1)
5932 + extra;
5933 let mag = (((mag + 1) >> 1).min(6)) as usize;
5934 if row == 0 && col == 0 {
5935 return mag;
5936 }
5937 let near_origin = match class {
5938 TxClass::TwoD => row < 2 && col < 2,
5939 TxClass::Horiz => col == 0,
5940 TxClass::Vert => row == 0,
5941 };
5942 if near_origin { mag + 7 } else { mag + 14 }
5943}
5944
5945fn dc_vote(dc: Option<bool>) -> i32 {
5946 match dc {
5947 None => 0,
5948 Some(true) => -1,
5949 Some(false) => 1,
5950 }
5951}
5952
5953fn dc_sign_ctx(vote: i32) -> usize {
5954 match vote.signum() {
5955 0 => 0,
5956 -1 => 1,
5957 _ => 2,
5958 }
5959}
5960
5961/// The `tx_type` a CDF symbol names, given the width of the row it was read
5962/// from.
5963///
5964/// The row's own width names its set (spec `Tx_Type_Intra_Inv_Set*` /
5965/// `Tx_Type_Inter_Inv_Set*`): 17 slots (16 symbols) is `EXT_TX_SET_ALL16`, 13
5966/// (12) `EXT_TX_SET_DTT9_IDTX_1DDCT`, 8 (7) `TX_SET_INTRA_1`, and everything
5967/// narrower the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` order, whose two
5968/// members are a prefix of the five.
5969///
5970/// One function rather than a `match` at each reader, so
5971/// [`crate::refusal_inventory`]'s enumeration of every (width, symbol) pair
5972/// tests the mapping the readers actually use.
5973pub(crate) fn tx_type_from_symbol(cdf_len: usize, t: usize) -> Option<TxType> {
5974 match cdf_len {
5975 17 => TxType::from_symbol_all16(t),
5976 13 => TxType::from_symbol_set2_12(t),
5977 8 => TxType::from_symbol_set1(t),
5978 _ => TxType::from_symbol(t),
5979 }
5980}
5981
5982/// The remainder of a level the base and base-range syntax could not reach
5983/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
5984/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
5985pub(crate) fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
5986 // lane-scaledref r1: this cap MASKS A REAL DEFECT and must not be lifted
5987 // on its own. Reading up to 32 leading zeros (dav1d's `len < 32`; libaom
5988 // itself calls a 21st bit a corrupt frame, decodetxb.c:30) is bit-identical
5989 // for every tail any encoder writes -- our own writer tops out at 19 zeros
5990 // (`tile::MAX_LEVEL == MAX_BR_LEVEL + (1 << 19)`) -- and was implemented
5991 // and round-trip tested here (commit ee1f980, reverted in 314ee08). It
5992 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
5993 // RED: seed 67 stops here today, and with the cap raised it decodes to a
5994 // frame-0 LUMA MISMATCH instead. A key frame cannot legitimately carry a
5995 // level above 1<<19, so the long tail is the SYMPTOM of an earlier desync
5996 // in that intra rect64 stream -- class `refusal-hides-a-defect`. Lift this
5997 // together with that defect's fix, not before.
5998 let mut length = 1u32;
5999 while dec.literal(1) == 0 {
6000 length += 1;
6001 if length > 20 {
6002 return Err(unsupported("a Golomb tail longer than this decoder reads"));
6003 }
6004 }
6005 let mut x = 1u32;
6006 for _ in 1..length {
6007 x = (x << 1) | dec.literal(1);
6008 }
6009 Ok(x - 1)
6010}
6011
6012/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
6013/// [`crate::tile`]'s `write_eob`.
6014fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
6015 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
6016 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
6017
6018 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
6019 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
6020 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
6021 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
6022 // `eob_multi_ctx`). Missing that split desynced the very first
6023 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
6024 // against a real aomdec trace).
6025 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
6026 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
6027 (_, Some(class1)) => class1,
6028 };
6029 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
6030 let (range, value) = dec.debug_state();
6031 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
6032 }
6033 let group = dec.symbol(eob_pt) + 1;
6034 if trace {
6035 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
6036 }
6037 let bits = OFFSET_BITS[group];
6038 let mut offset = 0u32;
6039 if bits > 0 {
6040 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
6041 if trace {
6042 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
6043 }
6044 offset = top << (bits - 1);
6045 if bits > 1 {
6046 offset |= dec.literal(bits - 1);
6047 }
6048 }
6049 GROUP_START[group] + offset as usize
6050}
6051
6052/// One transform block's levels, the inverse of [`crate::tile`]'s
6053/// `write_coeffs`, returned as a `side * side` grid in raster order, along
6054/// with the transform type that grid was coded under (`DCT_DCT` when the
6055/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
6056/// 64-point transforms, which never code anything else).
6057///
6058/// # Errors
6059/// Returns an error if the `tx_type` symbol decodes to a value outside its
6060/// CDF's own set (a corrupt or unsupported bitstream) — every value the
6061/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
6062/// produce dispatches to a real inverse transform.
6063/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
6064/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
6065/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
6066/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
6067/// the plane's own predicted mode instead. Every entry this table can
6068/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
6069/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
6070/// table ever names), so unlike the CDF-coded luma path there is no
6071/// ext-tx-set membership check to fall back from here.
6072pub(crate) fn default_intra_tx_type(mode: u8) -> TxType {
6073 use crate::intra::{
6074 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
6075 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
6076 };
6077 match mode {
6078 DC_PRED | D45_PRED => TxType::DctDct,
6079 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
6080 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
6081 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
6082 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
6083 }
6084}
6085
6086/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
6087/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
6088/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
6089fn is_smooth_mode(mode: usize) -> bool {
6090 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
6091}
6092
6093/// lane-coefread: the per-coefficient trace sites, one `#[cold]` call each.
6094/// `eprintln!` builds its `fmt::Arguments` on the stack AT THE CALL SITE, so
6095/// nine of them inside the base/sign loops pinned nine sets of values in the
6096/// hot loop's frame (the annotated profile was full of `mov ...(%rsp)` spill
6097/// traffic). Out of line, the loop keeps its values in registers and the
6098/// trace output is character-for-character what it was.
6099#[cold]
6100#[inline(never)]
6101fn trace_base_eob(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
6102 eprintln!("TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}");
6103}
6104
6105#[cold]
6106#[inline(never)]
6107fn trace_base(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
6108 eprintln!("TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}");
6109}
6110
6111#[cold]
6112#[inline(never)]
6113fn trace_br(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, k: i32) {
6114 eprintln!("TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}");
6115}
6116
6117#[cold]
6118#[inline(never)]
6119fn coeff_step_base(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, v: i32) {
6120 let (rng, _) = dec.debug_state();
6121 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}");
6122}
6123
6124#[cold]
6125#[inline(never)]
6126fn coeff_step_br(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, k: i32) {
6127 let (rng, _) = dec.debug_state();
6128 eprintln!("EC_COEFF_STEP tag=br c={scan_idx} pos={apos} ctx={ctx} k={k} rng={rng}");
6129}
6130
6131#[cold]
6132#[inline(never)]
6133fn coeff_step_sign(dec: &SymbolDecoder, c: usize, negative: bool) {
6134 let (rng, _) = dec.debug_state();
6135 eprintln!("EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}", negative as i32);
6136}
6137
6138#[cold]
6139#[inline(never)]
6140fn coeff_step_post_golomb(dec: &SymbolDecoder, c: usize, level: i32) {
6141 let (rng, _) = dec.debug_state();
6142 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
6143}
6144
6145#[cold]
6146#[inline(never)]
6147fn coeff_step_base_eob_level(dec: &SymbolDecoder, level: i32) {
6148 let (rng, _) = dec.debug_state();
6149 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
6150}
6151
6152fn read_coeffs(
6153 dec: &mut SymbolDecoder,
6154 coding: &mut TxbTables,
6155 scan: &[u16],
6156 skip_ctx: usize,
6157 sign_ctx: usize,
6158 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
6159 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
6160 // nothing at all; `DctDct` for every luma call and every chroma call at
6161 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
6162 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
6163 default_tx_type: TxType,
6164 // `Some((w, h))` with `w != h` when this read is a superblock-level
6165 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
6166 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
6167 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
6168 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
6169 // caller's block genuinely is `side` x `side`.
6170 rect_shape: Option<(usize, usize)>,
6171) -> Result<(Grid, TxType)> {
6172 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
6173 let side = coding.side;
6174 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
6175 let (range, value) = dec.debug_state();
6176 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
6177 }
6178 let dbg_txbskip = if coeff_trace_on() {
6179 coding.txb_skip[skip_ctx]
6180 } else {
6181 [0; 3]
6182 };
6183 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
6184 if coeff_trace_on() {
6185 let (rng, _) = dec.debug_state();
6186 eprintln!(
6187 "EC_COEFF_STEP tag=all_zero side={} ctx={skip_ctx} dcctx={sign_ctx} cdf={dbg_txbskip:?} all_zero={} rng={rng}",
6188 coding.side,
6189 all_zero as i32
6190 );
6191 }
6192 if crate::envflags::env_flag!("EC_AV1_TELL") {
6193 eprintln!(
6194 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
6195 all_zero as u8, dec.debug_bitpos(), dec.debug_state().0
6196 );
6197 }
6198 if trace {
6199 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
6200 }
6201 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
6202 let (range, value) = dec.debug_state();
6203 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
6204 }
6205 if all_zero {
6206 // lane-coefgrid: the all-zero unit (60% of the 4K segment's) names the
6207 // shared zero grid instead of allocating and zeroing its own.
6208 return Ok((Grid::Zero(side * side), TxType::DctDct));
6209 }
6210 let mut grid = vec![0i32; side * side];
6211 let mut tx_type = default_tx_type;
6212 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
6213 // The CDF row's own width names its set (lane-cdffwd2: extended
6214 // past the original two-way intra split once wider `reduced_tx_set
6215 // == 0` inter sets joined the table): 17 slots (16 symbols) is
6216 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
6217 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
6218 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
6219 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
6220 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
6221 let len = tx_type_cdf.len();
6222 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") && len == 3 {
6223 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
6224 }
6225 let t = dec.symbol(tx_type_cdf);
6226 crate::census::tx_type(len, t);
6227 if coeff_trace_on() {
6228 let (rng, _) = dec.debug_state();
6229 eprintln!("EC_COEFF_STEP tag=tx_type len={len} rng={rng}");
6230 }
6231 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
6232 let (range, value) = dec.debug_state();
6233 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
6234 }
6235 if trace {
6236 eprintln!("TRACE tx_type value={t} len={len}");
6237 }
6238 tx_type = tx_type_from_symbol(len, t)
6239 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
6240 }
6241
6242 let class = TxClass::of(tx_type);
6243 if class != TxClass::TwoD {
6244 hit!(TX_CLASS1_HITS);
6245 hit!(RECT_CLASS1_HITS);
6246 }
6247 let eob = read_eob(dec, coding, class);
6248 if trace {
6249 eprintln!("TRACE eob value={eob}");
6250 }
6251 let ec_trace_coeff = coeff_trace_on();
6252 if ec_trace_coeff {
6253 let (rng, _) = dec.debug_state();
6254 let cls = match class { TxClass::TwoD => "2d", TxClass::Horiz => "horiz", TxClass::Vert => "vert" };
6255 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
6256 }
6257 let class_scan;
6258 let scan: &[u16] = if class == TxClass::TwoD {
6259 scan
6260 } else {
6261 class_scan = class_scan_table(side, class);
6262 &class_scan
6263 };
6264 // `side` is one of 4/8/16/32 (every `TxbTables` row), so the per-
6265 // coefficient `pos / side`, `pos % side` was a hardware divide where a
6266 // shift and a mask say the same thing, and the level buffer fits a fixed
6267 // 32x32 frame of stack instead of a heap allocation per transform block.
6268 debug_assert!(side.is_power_of_two() && side <= 32);
6269 let sh = side.trailing_zeros();
6270 let col_mask = side - 1;
6271 // lane-coef2: padded like libaom's own level buffer (see [`neighbour`]):
6272 // `stride = side + 4` columns and four spare rows, so the widest read
6273 // `base_ctx` makes -- `(row + 4, col)` / `(row, col + 4)` with
6274 // `row, col <= side - 1` -- stays inside `(side + 4) * (side + 4)`, at
6275 // most `36 * 36`. Only `col < side`, `row < side` cells are ever written.
6276 let stride = side + 4;
6277 let mut levels_buf = [0u8; 36 * 36];
6278 let levels = &mut levels_buf[..stride * stride];
6279 // lane-coefread: the sign pass used to re-walk `scan[..eob]`, redo the
6280 // `pos >> sh` / `& mask` decomposition and load the level back out of the
6281 // padded frame just to skip the zeros. The base pass already knows both,
6282 // so it records `(scan_idx << 4) | level` for each NON-ZERO coefficient
6283 // (`scan_idx < 1024`, `level <= 15` -- both loops assert it), and the sign
6284 // pass walks that list in reverse (the base pass runs in reverse scan
6285 // order, so reversing it is forward scan order: the same coefficients, in
6286 // the same order, with the same `c` the trace prints).
6287 let mut nz_buf = [0u16; 1024];
6288 let mut nz_n = 0usize;
6289 let (base_taps, br_taps) = flat_taps(stride, class);
6290 for scan_idx in (0..eob).rev() {
6291 let pos = scan[scan_idx] as usize;
6292 let (row, col) = (pos >> sh, pos & col_mask);
6293 let idx = row * stride + col;
6294 let level = if scan_idx == eob - 1 {
6295 let ctx = eob_coeff_ctx(scan_idx, side * side);
6296 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
6297 if trace {
6298 trace_base_eob(scan_idx, pos, row, col, ctx, v);
6299 }
6300 v
6301 } else {
6302 let ctx = if class == TxClass::TwoD && rect_shape.is_none() {
6303 if row == 0 && col == 0 {
6304 0
6305 } else {
6306 base_mag(levels, idx, &base_taps)
6307 + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
6308 }
6309 } else {
6310 base_ctx(levels, stride, row, col, class, rect_shape)
6311 };
6312 let v = dec.symbol(&mut coding.base[ctx]) as i32;
6313 if ec_trace_coeff {
6314 // `pos` in libaom's column-major `coeff_idx` convention, so
6315 // the ladder lines up with instrumented `aomdec`.
6316 coeff_step_base(dec, scan_idx, col * side + row, ctx, v);
6317 }
6318 if trace {
6319 trace_base(scan_idx, pos, row, col, ctx, v);
6320 }
6321 v
6322 };
6323 let level = if level > NUM_BASE_LEVELS {
6324 let ctx = {
6325 let mag = br_mag(levels, idx, &br_taps);
6326 if row == 0 && col == 0 {
6327 mag
6328 } else {
6329 let near_origin = match class {
6330 TxClass::TwoD => row < 2 && col < 2,
6331 TxClass::Horiz => col == 0,
6332 TxClass::Vert => row == 0,
6333 };
6334 if near_origin { mag + 7 } else { mag + 14 }
6335 }
6336 };
6337 let mut level = level;
6338 let mut sent = 0;
6339 loop {
6340 let k = dec.symbol(&mut coding.br[ctx]) as i32;
6341 if ec_trace_coeff {
6342 // lane-leaf8tx r3: the `br` rung was missing from THIS
6343 // path's trace, so the cross-decoder range ladder was
6344 // blind to every base-range symbol and mis-reported the
6345 // first divergence (class [[gate-blind-to-feature]]).
6346 coeff_step_br(dec, scan_idx, col * side + row, ctx, k);
6347 }
6348 if trace {
6349 trace_br(scan_idx, pos, row, col, ctx, k);
6350 }
6351 level += k;
6352 sent += BR_STEP;
6353 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
6354 break;
6355 }
6356 }
6357 level
6358 } else {
6359 level
6360 };
6361 if ec_trace_coeff && scan_idx == eob - 1 {
6362 coeff_step_base_eob_level(dec, level);
6363 }
6364 // Every coded level here is a magnitude in `0..=15` (base <= 3 plus
6365 // at most `COEFF_BASE_RANGE` from the `br` loop; the Golomb tail is
6366 // added in the sign pass below, straight into `grid`), so the context
6367 // frame is bytes -- the five-tap sum in [`base_ctx`]/[`br_ctx`] is a
6368 // byte gather (lane-coefbuf).
6369 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
6370 levels[idx] = level as u8;
6371 if level != 0 {
6372 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
6373 nz_n += 1;
6374 }
6375 }
6376 if ec_trace_coeff {
6377 let (rng, _) = dec.debug_state();
6378 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
6379 }
6380
6381 for &packed in nz_buf[..nz_n].iter().rev() {
6382 let c = (packed >> 4) as usize;
6383 let pos = scan[c] as usize;
6384 let level = (packed & 15) as i32;
6385 let negative = if pos == 0 {
6386 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
6387 if trace {
6388 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
6389 }
6390 v
6391 } else {
6392 dec.literal(1) == 1
6393 };
6394 if ec_trace_coeff {
6395 coeff_step_sign(dec, c, negative);
6396 }
6397 let level = if level > MAX_BR_LEVEL {
6398 let g = read_golomb(dec)?;
6399 if trace {
6400 eprintln!("TRACE golomb pos={pos} value={g}");
6401 }
6402 level + g as i32
6403 } else {
6404 level
6405 };
6406 if ec_trace_coeff {
6407 coeff_step_post_golomb(dec, c, level);
6408 }
6409 grid[pos] = if negative { -level } else { level };
6410 }
6411 Ok((Grid::Own(grid), tx_type))
6412}
6413
6414/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
6415/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
6416/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
6417/// can ever produce, since every `tx_type` this decoder's rect sets can read
6418/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
6419/// rather than guess-decode if a non-2D class ever shows up here, since
6420/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
6421/// form for those.
6422
6423fn read_coeffs_rect(
6424 dec: &mut SymbolDecoder,
6425 coding: &mut TxbTables,
6426 scan: &[u16],
6427 w: usize,
6428 h: usize,
6429 skip_ctx: usize,
6430 sign_ctx: usize,
6431 default_tx_type: TxType,
6432) -> Result<(Grid, TxType)> {
6433 let rect_trace = coeff_trace_on();
6434 let entry_rng = dec.debug_state().0;
6435 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
6436 if rect_trace {
6437 eprintln!(
6438 "EC_COEFF_STEP tag=all_zero plane=0 ctx={skip_ctx} entry={entry_rng} all_zero={} rng={}",
6439 all_zero as i32,
6440 dec.debug_state().0
6441 );
6442 }
6443 if all_zero {
6444 return Ok((Grid::Zero(w * h), TxType::DctDct));
6445 }
6446 let mut grid = vec![0i32; w * h];
6447 hit!(RECT_COEFF_TU_HITS);
6448 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
6449 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
6450 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
6451 // context offsets -- both of which now have rect forms
6452 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
6453 // The rect sets that carry no symbol at all still pass `None` here.
6454 let mut tx_type = default_tx_type;
6455 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
6456 let len = tx_type_cdf.len();
6457 let t = dec.symbol(tx_type_cdf);
6458 crate::census::tx_type(len, t);
6459 tx_type = tx_type_from_symbol(len, t)
6460 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
6461 if rect_trace {
6462 eprintln!("EC_COEFF_STEP tag=tx_type plane=0 rng={}", dec.debug_state().0);
6463 }
6464 }
6465 let class = TxClass::of(tx_type);
6466 if class != TxClass::TwoD {
6467 hit!(TX_CLASS1_HITS);
6468 }
6469 let eob = read_eob(dec, coding, class);
6470 if rect_trace {
6471 eprintln!("EC_COEFF_STEP tag=eob eob={eob} rng={}", dec.debug_state().0);
6472 }
6473 let class_scan;
6474 let scan: &[u16] = if class == TxClass::TwoD {
6475 scan
6476 } else {
6477 class_scan = class_scan_table_wh(w, h, class);
6478 &class_scan
6479 };
6480 // lane-coef2: a heap `vec![0i32; w * h]` per rect transform unit became a
6481 // stack frame sized to the unit -- same reasoning as [`read_coeffs`]:
6482 // `neighbour_rect` returns 0 outside `(w, h)` and every write is
6483 // `levels[pos]` with `pos < w * h`. `w` is a power of two at every AV1
6484 // rect size, so the per-coefficient `pos / w`, `pos % w` is a shift and a
6485 // mask rather than a hardware divide.
6486 let stride = w + 4;
6487 let n = stride * (h + 4);
6488 debug_assert!(w.is_power_of_two() && n <= 36 * 36);
6489 let (mut b96, mut b256, mut b768);
6490 // Byte levels, same `0..=15` bound [`read_coeffs`] states.
6491 let levels: &mut [u8] = if n <= 96 {
6492 b96 = [0u8; 96];
6493 &mut b96[..n]
6494 } else if n <= 256 {
6495 b256 = [0u8; 256];
6496 &mut b256[..n]
6497 } else {
6498 b768 = [0u8; 768];
6499 &mut b768[..n]
6500 };
6501 let wsh = w.trailing_zeros();
6502 let wmask = w - 1;
6503 // lane-coefread: the non-zero list [`read_coeffs`] documents.
6504 let mut nz_buf = [0u16; 1024];
6505 let mut nz_n = 0usize;
6506 let (base_taps, br_taps) = flat_taps(stride, class);
6507 let (wlt, wgt) = (w < h, w > h);
6508 for scan_idx in (0..eob).rev() {
6509 let pos = scan[scan_idx] as usize;
6510 let (row, col) = (pos >> wsh, pos & wmask);
6511 let idx = row * stride + col;
6512 // libaom's column-major `coeff_idx`, for ladder comparison.
6513 let _apos = col * h + row;
6514 let level = if scan_idx == eob - 1 {
6515 let ctx = eob_coeff_ctx(scan_idx, w * h);
6516 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
6517 if rect_trace {
6518 eprintln!(
6519 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
6520 dec.debug_state().0
6521 );
6522 }
6523 v
6524 } else {
6525 let ctx = if class == TxClass::TwoD {
6526 if row == 0 && col == 0 {
6527 0
6528 } else {
6529 let m = base_mag(levels, idx, &base_taps);
6530 if wlt && row < 2 {
6531 m + 11
6532 } else if wgt && col < 2 {
6533 m + 16
6534 } else {
6535 m + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
6536 }
6537 }
6538 } else {
6539 base_ctx_rect(levels, stride, w, h, row, col, class)
6540 };
6541 let v = dec.symbol(&mut coding.base[ctx]) as i32;
6542 if rect_trace {
6543 eprintln!(
6544 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
6545 dec.debug_state().0
6546 );
6547 }
6548 v
6549 };
6550 let level = if level > NUM_BASE_LEVELS {
6551 let ctx = {
6552 let mag = br_mag(levels, idx, &br_taps);
6553 if row == 0 && col == 0 {
6554 mag
6555 } else {
6556 let near_origin = match class {
6557 TxClass::TwoD => row < 2 && col < 2,
6558 TxClass::Horiz => col == 0,
6559 TxClass::Vert => row == 0,
6560 };
6561 if near_origin { mag + 7 } else { mag + 14 }
6562 }
6563 };
6564 let mut level = level;
6565 let mut sent = 0;
6566 loop {
6567 let k = dec.symbol(&mut coding.br[ctx]) as i32;
6568 if rect_trace {
6569 eprintln!(
6570 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
6571 dec.debug_state().0
6572 );
6573 }
6574 level += k;
6575 sent += BR_STEP;
6576 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
6577 break;
6578 }
6579 }
6580 level
6581 } else {
6582 level
6583 };
6584 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
6585 levels[idx] = level as u8;
6586 if level != 0 {
6587 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
6588 nz_n += 1;
6589 }
6590 if rect_trace {
6591 let (rng, _) = dec.debug_state();
6592 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}");
6593 }
6594 }
6595 if rect_trace {
6596 let (rng, _) = dec.debug_state();
6597 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
6598 }
6599 for &packed in nz_buf[..nz_n].iter().rev() {
6600 let pos = scan[(packed >> 4) as usize] as usize;
6601 let level = (packed & 15) as i32;
6602 let negative = if pos == 0 {
6603 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
6604 } else {
6605 dec.literal(1) == 1
6606 };
6607 if rect_trace {
6608 let (rng, _) = dec.debug_state();
6609 eprintln!("EC_COEFF_STEP tag=sign_rect pos={pos} sign={} dcctx={sign_ctx} rng={rng}", u8::from(negative));
6610 }
6611 let level = if level > MAX_BR_LEVEL {
6612 let g = read_golomb(dec)?;
6613 level + g as i32
6614 } else {
6615 level
6616 };
6617 grid[pos] = if negative { -level } else { level };
6618 }
6619 Ok((Grid::Own(grid), tx_type))
6620}
6621
6622/// What one coded block leaves behind for the blocks that read it as a
6623/// neighbour: whether it coded anything at all, and the sign of its DC —
6624/// [`crate::tile`]'s own private `Neighbour`.
6625#[derive(Clone, Copy, Default)]
6626struct Neighbour {
6627 /// The transform unit's cumulative coefficient level (spec `cul_level`,
6628 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
6629 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
6630 /// boolean (`level != 0`) is enough for every context this decoder read
6631 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
6632 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
6633 /// needs the actual magnitude tier of its above/left neighbours, not
6634 /// just whether they coded anything.
6635 level: u8,
6636 dc: Option<bool>,
6637}
6638
6639/// `dst[start .. start + n] = v`, with the same per-cell bounds behaviour the
6640/// per-4x4-cell `get_mut` loops it replaces had: a cell past the end of the
6641/// grid is dropped, never a panic. One `memset` per grid row instead of a
6642/// bounds check per cell (lane-mi) -- the index span a row of a mi rect covers
6643/// is contiguous, so this writes exactly the cells the cell loop did,
6644/// including the ones a `mi_c + cc` past `skip_grid_cols_mi` folded into the
6645/// next row.
6646#[inline]
6647fn fill_span<T: Copy>(dst: &mut [T], start: usize, n: usize, v: T) {
6648 let end = (start + n).min(dst.len());
6649 if start < end {
6650 dst[start..end].fill(v);
6651 }
6652}
6653
6654fn neighbour_state(grid: &[i32]) -> Neighbour {
6655 // lane-coefgrid: the shared zero grid sums to zero by construction; this
6656 // sum has no early exit, so the 60% of units that code nothing used to
6657 // walk their whole grid here.
6658 if is_zero_grid(grid) {
6659 return Neighbour::default();
6660 }
6661 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
6662 Neighbour {
6663 level: cul.min(7) as u8,
6664 dc: (grid[0] != 0).then_some(grid[0] < 0),
6665 }
6666}
6667
6668/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
6669/// transform unit smaller than the block it sits in): `top`/`left` are the
6670/// above/left neighbours' magnitude tiers, each already clamped to 4.
6671pub(crate) const SKIP_CONTEXTS: [[usize; 5]; 5] = [
6672 [1, 2, 2, 2, 3],
6673 [2, 4, 4, 4, 5],
6674 [2, 4, 4, 4, 5],
6675 [2, 4, 4, 4, 5],
6676 [3, 5, 5, 5, 6],
6677];
6678
6679/// The `skip` flag, its written-instrument bit, and the covering coded
6680/// block's origin and dims, packed into ONE 8-byte cell (lane-publish): the
6681/// four maps are written together by `Neighbours::fill_skip_grid_rect` and by
6682/// nothing else, so a block's row is one fill instead of four, and the
6683/// deblocker's `pu_edge` reads origin and dims off one cache line.
6684#[derive(Clone, Copy)]
6685struct BlkCell {
6686 skip: bool,
6687 written: bool,
6688 org: [u16; 2],
6689 dim: [u8; 2],
6690}
6691
6692/// The neighbour state a block's contexts are read from — a duplicate of
6693/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
6694/// territory this round), kept at the same two granularities the real writer
6695/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
6696/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
6697/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
6698/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
6699/// chroma transform straddling the true, odd-sized frame edge see its
6700/// neighbour's state clamped at its own subsampled edge rather than luma's.
6701#[derive(Clone)]
6702struct Neighbours {
6703 above: Vec<[Neighbour; 3]>,
6704 left: Vec<[Neighbour; 3]>,
6705 above_mode: Vec<usize>,
6706 left_mode: Vec<usize>,
6707 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
6708 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
6709 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
6710 /// luma one -- the same block can (and often does) code a different
6711 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
6712 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
6713 /// within-block neighbour finer than this grid) is luma-only -- a known,
6714 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
6715 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
6716 above_uv_mode: Vec<usize>,
6717 left_uv_mode: Vec<usize>,
6718 above_side: Vec<usize>,
6719 left_side: Vec<usize>,
6720 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
6721 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
6722 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
6723 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
6724 /// array cannot tell the second leaf's partition symbol that the first
6725 /// one was coded at 8x8.
6726 /// lane-publish2: `u8` (a block side is at most 128 px, and so is
6727 /// [`NO_NEIGHBOUR_SIDE`]) -- every block stamps these per mi.
6728 above_side_mi: Vec<u8>,
6729 left_side_mi: Vec<u8>,
6730 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
6731 /// / row, with the mi position it was written at
6732 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
6733 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
6734 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
6735 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
6736 /// leaf whose neighbour is another split group needs that group's leaf 3
6737 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
6738 /// and read only by [`decode_leaf_split4`]; the position guard makes it
6739 /// fall back to the coarse slot whenever the real neighbour was a block
6740 /// of 8x8 or larger (whose one mode is correct for every row it spans).
6741 /// lane-publish2: `(mi position, mode)` narrowed from `(usize, usize)` to
6742 /// `(u16, u8)` -- every block stamps these mi-granular maps, and 16 bytes
6743 /// per mi per side of publish traffic was pure width. `u16::MAX` is the
6744 /// "never written" sentinel (an mi index cannot reach it: AV1's largest
6745 /// frame is 65536 px = 16384 mi).
6746 sub8_mode_col: Vec<(u16, u8)>,
6747 sub8_mode_row: Vec<(u16, u8)>,
6748 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
6749 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
6750 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
6751 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
6752 /// the leaf above writes the same row slot the block to the left owns.
6753 uv_mode_col: Vec<(u16, u8)>,
6754 uv_mode_row: Vec<(u16, u8)>,
6755 /// Every mi cell's own `uv_mode`, the mi grid libaom's
6756 /// `chroma_above_mbmi`/`chroma_left_mbmi` read directly (`set_mi_row_col`,
6757 /// blockd.h). lane-t900 r12: the one-slot-per-column
6758 /// `uv_mode_col`/`uv_mode_row` maps above hold only the LAST block written
6759 /// in that column, so a sub-8x8 pair's own first (non-chroma-ref) half
6760 /// overwrote the row the pair's chroma-ref half then wanted to read --
6761 /// the mi-exact match failed and the coarse [`SUB`] band answered instead.
6762 /// `u8::MAX` = no block has written this cell yet (fall back to the maps).
6763 uv_mode_grid: Vec<u8>,
6764 /// [`Self::uv_mode_grid`]'s stride, in mi units (superblock-padded, like
6765 /// every other band here).
6766 uv_grid_cols: usize,
6767 /// Whether the block above/left of this column/row was coded `skip` --
6768 /// an inter frame's own `skip` context (spec `SkipContext`), which the
6769 /// key-frame writer never tracks (its skip context is always zero); a
6770 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
6771 /// `left_skip`.
6772 above_skip: Vec<bool>,
6773 left_skip: Vec<bool>,
6774 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
6775 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
6776 /// pixels last written over each unit by `set_txfm_ctxs`/
6777 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
6778 /// symbol reads its context from (lane-txselect, spec 5.11.17).
6779 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
6780 /// array is exactly libaom's per-superblock-row reset, since each mi row
6781 /// is only ever visited inside one superblock row.
6782 above_txfm: Vec<u8>,
6783 left_txfm: Vec<u8>,
6784 /// Whether the block above/left of this column/row coded `skip_mode`
6785 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
6786 /// lane-av1comp round 14.
6787 above_skip_mode: Vec<bool>,
6788 left_skip_mode: Vec<bool>,
6789 /// Whether the block above/left was coded inter -- the `is_inter`
6790 /// context (spec `av1_get_intra_inter_context`), a duplicate of
6791 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
6792 above_inter: Vec<bool>,
6793 left_inter: Vec<bool>,
6794 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
6795 /// alphabet) the block above/left of this column/row coded, or `-1` for
6796 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
6797 /// functions (`mvstack::ref_ctx` family) need the real reference, not
6798 /// just "was it inter" (lane-av1refs: every inter block used to be
6799 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
6800 /// enough).
6801 above_ref: Vec<i8>,
6802 left_ref: Vec<i8>,
6803 /// The block above/left's *second* reference frame when it was coded
6804 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
6805 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
6806 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
6807 /// `i8`, once a compound `read_ref_frames` lands.
6808 /// lane-publish2 audit: the "always `None` today" note this doc used to
6809 /// carry is long stale -- compound blocks do occur, and
6810 /// [`Self::record_compound_ctx_rect_mi`] stamps the real second reference
6811 /// over their span right after [`Self::record_inter_rect_mi`]'s reset.
6812 /// The array IS read: `single_ref_p*`/`comp_ref` contexts and every
6813 /// [`crate::mvstack::NeighbourRef`] construction (class
6814 /// [[branch-dropped-as-unreachable]] -- the note, not the code, was wrong).
6815 above_ref1: Vec<Option<i8>>,
6816 left_ref1: Vec<Option<i8>>,
6817 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
6818 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
6819 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
6820 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
6821 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
6822 above_comp_group_idx: Vec<u8>,
6823 left_comp_group_idx: Vec<u8>,
6824 above_compound_idx: Vec<u8>,
6825 left_compound_idx: Vec<u8>,
6826 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
6827 /// `3` = "no info": an intra neighbour or the frame's own border) of the
6828 /// block above/left of this column/row -- spec
6829 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
6830 above_filter: Vec<[u8; 2]>,
6831 left_filter: Vec<[u8; 2]>,
6832 mi_cols: usize,
6833 mi_rows: usize,
6834 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
6835 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
6836 /// 7.15) never filters an 8x8 luma block whose covering coded block read
6837 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
6838 /// grain [`Self::record_mi`] already writes at), read back at 8x8
6839 /// granularity by [`apply_cdef`] since `skip` is constant across every
6840 /// mi cell one coded block covers.
6841 /// The four per-mi maps [`Neighbours::blk_grid`] packs, in one cell.
6842 /// lane-cdefstrip r1 instrument: whether any coded block actually WROTE
6843 /// the `skip` bit at this mi cell during this frame. A fresh
6844 /// `Neighbours` seeds `skip_grid` all-`false` ("not skip"), so a decode
6845 /// arm that forgets [`Self::fill_skip_grid_rect`] silently makes
6846 /// [`apply_cdef`] filter an 8x8 unit libaom's `is_8x8_block_skip`
6847 /// (`cdef.c:29-38`) excludes -- exactly the lane-cdef defect, and
6848 /// unobservable from the pixels alone. Counted by
6849 /// [`cdef_unwritten_skip_units`].
6850 /// Per-4x4-mi origin `(mi_row, mi_col)` of the coded (prediction) block
6851 /// covering that cell -- spec 7.14.2's `isBlockEdge`/libaom `pu_edge`,
6852 /// which re-enables the loop filter at a prediction boundary between two
6853 /// skipped inter blocks (lane-mergefix r4). Written by
6854 /// [`Self::fill_skip_grid_rect`], whose `at_mi` IS that origin.
6855 /// Per-4x4-mi `(width, height)` in mi units of the coded block covering
6856 /// that cell -- the other half of `pu_edge`: libaom tests the edge
6857 /// coordinate against the block's size in the FILTERED plane's own
6858 /// pixels, which for chroma is `max(luma_dim / 2, 4)` (lane-t900 r30b).
6859 blk_grid: Vec<BlkCell>,
6860 skip_grid_cols_mi: usize,
6861 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
6862 /// never splits a coded block's transform below its own size (round 2:
6863 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
6864 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
6865 /// edge-length lookup (`apply_deblock`).
6866 tx_grid: Vec<u8>,
6867 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
6868 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
6869 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
6870 tx_h_grid: Vec<u8>,
6871 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
6872 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
6873 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
6874 /// does NOT follow luma's `tx_depth` split, so deriving it as
6875 /// `tx_grid / 2` invented chroma transform edges the deblocker then
6876 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
6877 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
6878 /// every caller routes through.
6879 uv_tx_grid: Vec<u8>,
6880 uv_tx_h_grid: Vec<u8>,
6881 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
6882 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
6883 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
6884 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
6885 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
6886 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
6887 /// reference onto `LAST_FRAME`'s own delta).
6888 ref_grid: Vec<i8>,
6889 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
6890 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
6891 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
6892 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
6893 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
6894 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
6895 /// to know which mode produced the value.
6896 delta_lf_grid: Vec<[i8; 4]>,
6897 /// The block above/left's own palette-Y size (0 = not a palette block)
6898 /// and its base colours -- `av1_get_palette_mode_ctx`/
6899 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
6900 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
6901 above_palette_size: Vec<u8>,
6902 left_palette_size: Vec<u8>,
6903 above_palette_colors: Vec<[u16; 8]>,
6904 left_palette_colors: Vec<[u16; 8]>,
6905 /// As the four fields above, for the neighbour's own chroma (U-channel
6906 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
6907 /// palette size/colours (lane-palette2 r1).
6908 above_palette_uv_size: Vec<u8>,
6909 left_palette_uv_size: Vec<u8>,
6910 above_palette_uv_colors: Vec<[u16; 8]>,
6911 left_palette_uv_colors: Vec<[u16; 8]>,
6912 /// This tile's own top-left corner, in 4x4 mode-info units (spec
6913 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
6914 /// neighbour" check compares against this instead of literal `0`, since a
6915 /// block at the tile's own top/left edge has no usable neighbour even
6916 /// though a decoded block sits there in the picture (spec `decode_tile`'s
6917 /// per-tile `clear_above_context`/`left_available`/`up_available`).
6918 /// `0` for a single-tile frame, matching every existing caller exactly.
6919 tile_row0_mi: usize,
6920 tile_col0_mi: usize,
6921}
6922
6923#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
6924impl Neighbours {
6925 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
6926 /// true (unpadded) size in 4x4 mode-info units.
6927 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize, fctx: &crate::decode::FrameCtx) -> Self {
6928 // lane-sb128c r7: a 128x64 block at the bottom frame edge records its
6929 // neighbour state over the whole 64-row extent, past the frame's last
6930 // mi row (mi_rows 198, block rows 192..208). libaom's own context
6931 // buffers are superblock-aligned for exactly that reason
6932 // (`av1_alloc_context_buffers` rounds to `MAX_MIB_SIZE`), so pad the
6933 // side arrays to a superblock multiple and leave those cells unread --
6934 // every availability check uses the true `mi_rows`/`mi_cols` below.
6935 let sb_sub = (sb_mi_cur(fctx) as usize) / (SUB / MI);
6936 let (cols, rows) = (
6937 cols.next_multiple_of(sb_sub),
6938 rows.next_multiple_of(sb_sub),
6939 );
6940 Self {
6941 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
6942 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
6943 above_mode: vec![DC_PRED; cols],
6944 left_mode: vec![DC_PRED; rows],
6945 above_uv_mode: vec![DC_PRED; cols],
6946 left_uv_mode: vec![DC_PRED; rows],
6947 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
6948 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
6949 above_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; cols * (SUB / MI)],
6950 left_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; rows * (SUB / MI)],
6951 sub8_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
6952 sub8_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
6953 uv_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
6954 uv_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
6955 uv_mode_grid: vec![u8::MAX; cols * (SUB / MI) * rows * (SUB / MI)],
6956 uv_grid_cols: cols * (SUB / MI),
6957 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
6958 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
6959 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
6960 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
6961 // 16x16 block beside it, which a SUB-grid slot cannot name
6962 // (class context-read-from-one-cell).
6963 above_skip: vec![false; cols * (SUB / MI)],
6964 left_skip: vec![false; rows * (SUB / MI)],
6965 above_skip_mode: vec![false; cols * (SUB / MI)],
6966 left_skip_mode: vec![false; rows * (SUB / MI)],
6967 above_inter: vec![false; cols * (SUB / MI)],
6968 left_inter: vec![false; rows * (SUB / MI)],
6969 above_ref: vec![-1; cols * (SUB / MI)],
6970 left_ref: vec![-1; rows * (SUB / MI)],
6971 above_ref1: vec![None; cols * (SUB / MI)],
6972 left_ref1: vec![None; rows * (SUB / MI)],
6973 above_comp_group_idx: vec![0; cols * (SUB / MI)],
6974 left_comp_group_idx: vec![0; rows * (SUB / MI)],
6975 above_compound_idx: vec![0; cols * (SUB / MI)],
6976 left_compound_idx: vec![0; rows * (SUB / MI)],
6977 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
6978 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
6979 mi_cols,
6980 mi_rows,
6981 blk_grid: vec![
6982 BlkCell { skip: false, written: false, org: [0; 2], dim: [1; 2] };
6983 cols * (SUB / MI) * rows * (SUB / MI)
6984 ],
6985 skip_grid_cols_mi: cols * (SUB / MI),
6986 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
6987 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
6988 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
6989 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
6990 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
6991 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
6992 above_palette_size: vec![0; cols * (SUB / MI)],
6993 left_palette_size: vec![0; rows * (SUB / MI)],
6994 above_palette_colors: vec![[0u16; 8]; cols * (SUB / MI)],
6995 left_palette_colors: vec![[0u16; 8]; rows * (SUB / MI)],
6996 above_palette_uv_size: vec![0; cols * (SUB / MI)],
6997 left_palette_uv_size: vec![0; rows * (SUB / MI)],
6998 above_palette_uv_colors: vec![[0u16; 8]; cols * (SUB / MI)],
6999 left_palette_uv_colors: vec![[0u16; 8]; rows * (SUB / MI)],
7000 tile_row0_mi: 0,
7001 tile_col0_mi: 0,
7002 }
7003 }
7004
7005 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
7006 /// tile's own column span (`col1_mi` exclusive), plus recording
7007 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
7008 /// availability check below. Left context resets every superblock row
7009 /// regardless of tile ([`Self::start_row`], already called once per SB
7010 /// row by every caller) so it needs no tile-specific reset here.
7011 fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize, fctx: &crate::decode::FrameCtx) {
7012 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
7013 // are tile-relative, same as every other neighbour lookup here.
7014 fctx.seg_tile_origin.with(|c| c.set((row0_mi, col0_mi)));
7015 self.tile_row0_mi = row0_mi;
7016 self.tile_col0_mi = col0_mi;
7017 let end = col1_mi.min(self.above.len());
7018 for i in col0_mi.min(end)..end {
7019 self.above[i] = Default::default();
7020 self.above_side_mi[i] = NO_NEIGHBOUR_SIDE as u8;
7021 }
7022 let (sc0, sc1) = (
7023 col0_mi / (SUB / MI),
7024 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
7025 );
7026 for i in sc0.min(sc1)..sc1 {
7027 self.above_mode[i] = DC_PRED;
7028 self.above_side[i] = NO_NEIGHBOUR_SIDE;
7029 }
7030 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
7031 // the tile's own mi column span directly.
7032 let mend = col1_mi.min(self.above_skip.len());
7033 for i in col0_mi.min(mend)..mend {
7034 self.above_skip[i] = false;
7035 self.above_skip_mode[i] = false;
7036 self.above_inter[i] = false;
7037 self.above_ref[i] = -1;
7038 self.above_ref1[i] = None;
7039 self.above_comp_group_idx[i] = 0;
7040 self.above_compound_idx[i] = 0;
7041 self.above_filter[i] = [3u8; 2];
7042 }
7043 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
7044 // stale `(row, mode)` from the tile to the LEFT names an mi row this
7045 // tile's first block would read as its own above neighbour.
7046 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
7047 for i in col0_mi.min(mcol_end)..mcol_end {
7048 self.sub8_mode_col[i] = (u16::MAX, 0);
7049 self.uv_mode_col[i] = (u16::MAX, 0);
7050 }
7051 // lane-mergefix r2: `av1_zero_above_context` also memsets the txfm row
7052 // over the tile's own column span (to `tx_size_wide[TX_SIZES_LARGEST]`,
7053 // not zero) -- without it a second tile column reads the first one's
7054 // resolved transform sizes as its own above context.
7055 let tend = col1_mi.min(self.above_txfm.len());
7056 for i in col0_mi.min(tend)..tend {
7057 self.above_txfm[i] = TXFM_CTX_INIT;
7058 }
7059 }
7060
7061 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
7062 /// for a non-palette block, clearing any stale neighbour state) into every
7063 /// [`SUB`]-grid cell it covers on both the above and left edges --
7064 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
7065 /// call sites are all square blocks).
7066 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
7067 self.record_palette_y_rect((at.0 * (SUB / MI), at.1 * (SUB / MI)), side, side, size, colors);
7068 }
7069
7070 /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
7071 /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
7072 /// [`Self::record`]): a true rect strip's above/left neighbour spans
7073 /// differ.
7074 fn record_palette_y_rect(
7075 &mut self,
7076 mi: (usize, usize),
7077 w: usize,
7078 h: usize,
7079 size: usize,
7080 colors: [u16; 8],
7081 ) {
7082 let (r, c) = mi;
7083 if crate::envflags::env_flag!("EC_PALPUB") {
7084 eprintln!("EC_PALPUB yrect mi={r},{c} bw={w} bh={h} y={size}");
7085 }
7086 // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size`
7087 // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi
7088 // cell immediately left of the block, not its 16px [`SUB`] cell. The
7089 // old SUB grid let a 16x8 strip pair share one slot, so the second
7090 // strip of mi(0,8) read the FIRST strip's palette size and the colour
7091 // cache came out one entry short (class [[context-read-from-one-cell]]).
7092 for cell in 0..(w / MI).max(1) {
7093 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
7094 *e = size as u8;
7095 // lane-publish2: spec 5.11.46 `get_palette_cache` reads a
7096 // neighbour's colours only where its palette size > 0, so a
7097 // non-palette block need not stamp 16 bytes of zeroes here.
7098 if size > 0 {
7099 self.above_palette_colors[c + cell] = colors;
7100 }
7101 }
7102 }
7103 for cell in 0..(h / MI).max(1) {
7104 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
7105 *e = size as u8;
7106 if size > 0 {
7107 self.left_palette_colors[r + cell] = colors;
7108 }
7109 }
7110 }
7111 }
7112
7113 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
7114 /// neighbours that are themselves a palette-Y block, plus
7115 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
7116 /// cache (pred_common.c:73).
7117 ///
7118 /// The SB-top-row exclusion of the above neighbour (`row % 64` in
7119 /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
7120 /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
7121 /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
7122 /// the ctx too made every superblock in the frame's second SB row read
7123 /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
7124 /// palette block decoded as "no palette" and the tile desynced from
7125 /// there (class [[cdf-row-held-constant]]).
7126 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
7127 self.palette_ctx_and_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
7128 }
7129
7130 /// [`Self::palette_ctx_and_cache`] with the block's REAL mi row, which a
7131 /// 1:4 strip does not share with its [`SUB`] cell: `av1_get_palette_cache`
7132 /// drops the above neighbour on a 64-px superblock boundary
7133 /// (pred_common.c:76, `row % (1 << MIN_SB_SIZE_LOG2)` with `row` the
7134 /// block's own PIXEL row), and strip 1 of a HORZ_4 sits 8 px into the
7135 /// cell -- reading `at.0 % 4` there excludes strip 0 from the cache of
7136 /// every strip in an SB's top cell row, which libaom does not do.
7137 fn palette_ctx_and_cache_mi(&self, mi: (usize, usize)) -> (usize, Vec<u16>) {
7138 let (r, c) = mi;
7139 let above_ok = r % 16 != 0;
7140 // `xd->above_mbmi` exists for every row but the tile's own first.
7141 let above_is_palette = r > self.tile_row0_mi && self.above_palette_size[c] > 0;
7142 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
7143 (usize::from(self.above_palette_size[c]), self.above_palette_colors[c])
7144 } else {
7145 (0, [0u16; 8])
7146 };
7147 // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which
7148 // is NULL whenever the block sits at its TILE's own left column
7149 // (`left_available`), not the frame's -- without this guard a second
7150 // tile column reads the previous tile's palette colours into its cache
7151 // and its `palette_y_mode` ctx.
7152 let left_ok = c > self.tile_col0_mi;
7153 let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 {
7154 (usize::from(self.left_palette_size[r]), self.left_palette_colors[r])
7155 } else {
7156 (0, [0u16; 8])
7157 };
7158 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
7159 let mut cache = Vec::with_capacity(16);
7160 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
7161 if cache.last() != Some(&v) {
7162 cache.push(v);
7163 }
7164 };
7165 let (mut ai, mut li) = (0usize, 0usize);
7166 while ai < above_n && li < left_n {
7167 let (va, vl) = (above_colors[ai], left_colors[li]);
7168 if vl < va {
7169 push_dedup(&mut cache, vl);
7170 li += 1;
7171 } else {
7172 push_dedup(&mut cache, va);
7173 ai += 1;
7174 if vl == va {
7175 li += 1;
7176 }
7177 }
7178 }
7179 while ai < above_n {
7180 push_dedup(&mut cache, above_colors[ai]);
7181 ai += 1;
7182 }
7183 while li < left_n {
7184 push_dedup(&mut cache, left_colors[li]);
7185 li += 1;
7186 }
7187 (ctx, cache)
7188 }
7189
7190 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
7191 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
7192 /// same way (lane-palette2 r1).
7193 fn record_palette_uv(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
7194 self.record_palette_uv_rect(
7195 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
7196 side,
7197 side,
7198 size,
7199 colors,
7200 );
7201 }
7202
7203 /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
7204 /// extents, in LUMA pixels (lane-palette2 r4, same convention as
7205 /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
7206 /// luma resolution regardless of which plane the recorded state is for).
7207 fn record_palette_uv_rect(
7208 &mut self,
7209 mi: (usize, usize),
7210 w: usize,
7211 h: usize,
7212 size: usize,
7213 colors: [u16; 8],
7214 ) {
7215 let (r, c) = mi;
7216 // mi granularity, see [`Self::record_palette_y_rect`].
7217 for cell in 0..(w / MI).max(1) {
7218 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
7219 *e = size as u8;
7220 if size > 0 {
7221 self.above_palette_uv_colors[c + cell] = colors;
7222 }
7223 }
7224 }
7225 for cell in 0..(h / MI).max(1) {
7226 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
7227 *e = size as u8;
7228 if size > 0 {
7229 self.left_palette_uv_colors[r + cell] = colors;
7230 }
7231 }
7232 }
7233 }
7234
7235 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
7236 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
7237 /// no neighbour lookup at all (it is this block's own just-decided Y
7238 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
7239 /// so only the cache is wanted here.
7240 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
7241 self.palette_uv_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
7242 }
7243
7244 /// [`Self::palette_uv_cache`] with the block's real mi row -- see
7245 /// [`Self::palette_ctx_and_cache_mi`].
7246 fn palette_uv_cache_mi(&self, mi: (usize, usize)) -> Vec<u16> {
7247 let (r, c) = mi;
7248 let above_ok = r % 16 != 0;
7249 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
7250 (usize::from(self.above_palette_uv_size[c]), self.above_palette_uv_colors[c])
7251 } else {
7252 (0, [0u16; 8])
7253 };
7254 // Same tile-relative left availability as the luma cache above.
7255 let left_ok = c > self.tile_col0_mi;
7256 let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 {
7257 (usize::from(self.left_palette_uv_size[r]), self.left_palette_uv_colors[r])
7258 } else {
7259 (0, [0u16; 8])
7260 };
7261 let mut cache = Vec::with_capacity(16);
7262 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
7263 if cache.last() != Some(&v) {
7264 cache.push(v);
7265 }
7266 };
7267 let (mut ai, mut li) = (0usize, 0usize);
7268 while ai < above_n && li < left_n {
7269 let (va, vl) = (above_colors[ai], left_colors[li]);
7270 if vl < va {
7271 push_dedup(&mut cache, vl);
7272 li += 1;
7273 } else {
7274 push_dedup(&mut cache, va);
7275 ai += 1;
7276 if vl == va {
7277 li += 1;
7278 }
7279 }
7280 }
7281 while ai < above_n {
7282 push_dedup(&mut cache, above_colors[ai]);
7283 ai += 1;
7284 }
7285 while li < left_n {
7286 push_dedup(&mut cache, left_colors[li]);
7287 li += 1;
7288 }
7289 cache
7290 }
7291
7292 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
7293 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
7294 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
7295 /// units as [`Self::fill_skip_grid`].
7296 fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8, fctx: &crate::decode::FrameCtx) {
7297 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame, fctx);
7298 }
7299
7300 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
7301 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
7302 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
7303 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
7304 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
7305 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
7306 /// libaom `set_one_param_for_line_luma`/`_chroma`: an edge that is a
7307 /// transform-unit edge but NOT a prediction-unit edge is not filtered when
7308 /// `curr_skipped = mbmi->skip_txfm && is_inter_block(mbmi)`. Widening this
7309 /// block's published transform extent to its own size is exactly that
7310 /// suppression for the deblocker's `x0 % tx != 0` test -- the only shape
7311 /// that needs it is the 128 root, whose chroma extent (64) is the one
7312 /// [`Self::fill_lf_grid_rect`]'s TX_32X32 cap narrows. An INTRA block is
7313 /// never suppressed (libaom's `is_inter_block` term), so this is called
7314 /// only from the skipped-inter branch.
7315 fn suppress_internal_lf_edges(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize) {
7316 let (mi_r, mi_c) = at_mi;
7317 let (uv_w, uv_h) = ((w_mi * MI / 2).max(4) as u8, (h_mi * MI / 2).max(4) as u8);
7318 for rr in 0..h_mi {
7319 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
7320 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_w);
7321 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_h);
7322 }
7323 }
7324
7325 fn fill_lf_grid_rect(
7326 &mut self,
7327 at_mi: (usize, usize),
7328 w_mi: usize,
7329 h_mi: usize,
7330 tx_px: u8,
7331 tx_h_px: u8,
7332 ref_frame: i8, fctx: &crate::decode::FrameCtx,
7333 ) {
7334 let (mi_r, mi_c) = at_mi;
7335 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
7336 // half its luma one (min 4 px, the smallest transform), capped at
7337 // TX_32X32 -- independent of this block's luma `tx_depth`.
7338 let uv_tx_w = ((w_mi * MI / 2).max(4).min(32)) as u8;
7339 let uv_tx_h = ((h_mi * MI / 2).max(4).min(32)) as u8;
7340 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
7341 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}");
7342 }
7343 crate::census::tx(tx_px, tx_h_px);
7344 let cur = fctx.current_delta_lf.with(|c| c.get());
7345 let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) {
7346 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
7347 } else {
7348 [cur[0].clamp(-63, 63) as i8; 4]
7349 };
7350 for rr in 0..h_mi {
7351 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
7352 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
7353 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
7354 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_tx_w);
7355 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_tx_h);
7356 fill_span(&mut self.ref_grid, start, w_mi, ref_frame);
7357 fill_span(&mut self.delta_lf_grid, start, w_mi, snapshot);
7358 }
7359 }
7360
7361 /// One var-tx / split-tx LEAF's own LUMA transform dims over its mi span.
7362 /// libaom `get_transform_size` (av1_loopfilter.c:207) applies the split
7363 /// override only `if ((plane == AOM_PLANE_Y) && ...)` -- chroma keeps
7364 /// `av1_get_max_uv_txsize(mbmi->bsize)`, the whole BLOCK's uv transform.
7365 /// Routing a leaf through [`Self::fill_lf_grid_rect`] recomputed the uv
7366 /// dims from the LEAF span and so invented chroma transform edges the
7367 /// deblocker then filtered (lane-golomb r6). `ref_grid`/`delta_lf_grid`
7368 /// are already correct from the block's own fill over the same span.
7369 fn fill_lf_grid_leaf_luma(
7370 &mut self,
7371 at_mi: (usize, usize),
7372 w_mi: usize,
7373 h_mi: usize,
7374 tx_px: u8,
7375 tx_h_px: u8,
7376 ) {
7377 let (mi_r, mi_c) = at_mi;
7378 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
7379 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}");
7380 }
7381 for rr in 0..h_mi {
7382 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
7383 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
7384 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
7385 }
7386 }
7387
7388 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
7389 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
7390 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
7391 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
7392 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
7393 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
7394 }
7395
7396 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
7397 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
7398 let (mi_r, mi_c) = at_mi;
7399 if skip && w_mi != h_mi {
7400 hit!(RECT_SKIP_BAND_HITS);
7401 }
7402 // lane-census: an INTRA frame's blocks never reach the inter
7403 // publisher, and this one is what every coded block writes.
7404 crate::census::block_intra_frame(w_mi, h_mi, skip);
7405 for rr in 0..h_mi {
7406 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
7407 fill_span(
7408 &mut self.blk_grid,
7409 start,
7410 w_mi,
7411 BlkCell {
7412 skip,
7413 written: true,
7414 org: [mi_r as u16, mi_c as u16],
7415 dim: [w_mi as u8, h_mi as u8],
7416 },
7417 );
7418 }
7419 }
7420
7421 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
7422 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
7423 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
7424 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
7425 /// straddle the region with a mix of skip/non-skip blocks).
7426 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
7427 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
7428 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
7429 /// filtered edge's two sides are each exactly one coded block wide.
7430 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
7431 self.blk_grid
7432 .get(mi_r * self.skip_grid_cols_mi + mi_c)
7433 .is_some_and(|c| c.skip)
7434 }
7435
7436 /// The `skip_txfm` context of a block whose top-left mi cell is
7437 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
7438 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
7439 /// with an absent neighbour contributing 0. The mi grid is per tile, so
7440 /// row/column 0 is a tile edge and has no neighbour on that axis.
7441 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
7442 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
7443 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
7444 }
7445
7446 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
7447 (0..2).all(|rr| {
7448 (0..2).all(|cc| {
7449 self.blk_grid
7450 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
7451 .is_some_and(|c| c.skip)
7452 })
7453 })
7454 }
7455
7456 fn start_row(&mut self) {
7457 self.left.iter_mut().for_each(|l| *l = Default::default());
7458 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
7459 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
7460 self.left_side.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
7461 self.left_side_mi.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE as u8);
7462 self.left_skip.iter_mut().for_each(|s| *s = false);
7463 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
7464 self.left_inter.iter_mut().for_each(|i| *i = false);
7465 self.left_ref.iter_mut().for_each(|r| *r = -1);
7466 self.left_ref1.iter_mut().for_each(|r| *r = None);
7467 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
7468 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
7469 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
7470 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
7471 // context (a tile/SB-row boundary has no left neighbour).
7472 self.sub8_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0));
7473 self.uv_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0));
7474 // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands
7475 // are per-mi maps like every other one here, so they reset with the
7476 // row too -- the left guard above is what actually stops a cross-tile
7477 // read, this keeps a stale colour out of the arrays at all.
7478 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
7479 self.left_palette_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
7480 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
7481 self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
7482 // lane-mergefix r2: `av1_zero_left_context` memsets
7483 // `left_txfm_context_buffer` to `tx_size_high[TX_SIZES_LARGEST]` at
7484 // every superblock row of every tile -- the var-tx left context does
7485 // NOT carry over a tile boundary (its `txfm_partition` ctx read the
7486 // previous tile column's last block otherwise).
7487 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
7488 }
7489
7490 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
7491 /// block that reads it as a neighbour -- [`crate::tile`]'s
7492 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
7493 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
7494 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
7495 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
7496 /// the real value, not just `is_inter`).
7497 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7498 fn record_inter(
7499 &mut self,
7500 at: (usize, usize),
7501 side: usize,
7502 skip: bool,
7503 is_inter: bool,
7504 ref_frame: i8,
7505 filter: [u8; 2],
7506 skip_mode: bool,
7507 ) {
7508 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
7509 }
7510
7511 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
7512 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
7513 /// r1: a true rectangular strip's above-context span (its own width) and
7514 /// left-context span (its own height) differ, unlike every caller before
7515 /// this round (class neighbour-votes-all-its-fields).
7516 #[allow(clippy::too_many_arguments)]
7517 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7518 fn record_inter_rect(
7519 &mut self,
7520 at: (usize, usize),
7521 w_sub: usize,
7522 h_sub: usize,
7523 skip: bool,
7524 is_inter: bool,
7525 ref_frame: i8,
7526 filter: [u8; 2],
7527 skip_mode: bool,
7528 ) {
7529 let (r, c) = at;
7530 self.record_inter_rect_mi(
7531 (r * (SUB / MI), c * (SUB / MI)),
7532 w_sub / MI,
7533 h_sub / MI,
7534 skip,
7535 is_inter,
7536 ref_frame,
7537 filter,
7538 skip_mode,
7539 );
7540 }
7541
7542 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
7543 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
7544 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
7545 /// routes through the wrapper above.
7546 #[allow(clippy::too_many_arguments)]
7547 fn record_inter_rect_mi(
7548 &mut self,
7549 at_mi: (usize, usize),
7550 w_mi: usize,
7551 h_mi: usize,
7552 skip: bool,
7553 is_inter: bool,
7554 ref_frame: i8,
7555 filter: [u8; 2],
7556 skip_mode: bool,
7557 ) {
7558 let (r, c) = at_mi;
7559 crate::census::block(w_mi, h_mi, is_inter, ref_frame, skip);
7560 // lane-t900 r8 (class new-map-ignores-tile-edge's twin: a map NOBODY
7561 // writes for a whole block class): an INTER block left the luma mode
7562 // map untouched, so a later intra block's `get_intra_edge_filter_type`
7563 // (spec 7.11.2, libaom `reconintra.h`'s `is_smooth`) fell back to the
7564 // coarse SUB-row band, which still held a SMOOTH mode from an earlier
7565 // block in that pixel row -- the directional edge filter then ran at
7566 // strength 3 instead of 2. libaom reads `mbmi->mode` of the neighbour,
7567 // which for an inter block is an INTER mode (>= NEARESTMV) and is
7568 // never smooth; DC_PRED is this map's equivalent (the sub-8x8 groups
7569 // already stamped it).
7570 // The chroma twin: `is_smooth(mbmi, plane > 0)` returns 0 outright for
7571 // an inter neighbour ("uv_mode is not set for inter blocks"), so the
7572 // uv map must read DC_PRED over an inter block's cells too.
7573 if is_inter {
7574 self.record_mode_mi(r, c, w_mi, h_mi, DC_PRED);
7575 self.record_uv_mode_mi(r, c, w_mi, h_mi, DC_PRED);
7576 }
7577 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
7578 self.above_skip[c..c + w_mi].fill(skip);
7579 self.above_skip_mode[c..c + w_mi].fill(skip_mode);
7580 self.above_inter[c..c + w_mi].fill(is_inter);
7581 self.above_ref[c..c + w_mi].fill(ref_frame);
7582 // The single-ref default: `record_compound_ctx_rect_mi` overwrites
7583 // this with the block's real second reference for a compound block,
7584 // called right after this one (lane-publish2 audit).
7585 self.above_ref1[c..c + w_mi].fill(None);
7586 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
7587 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
7588 // as `3`/`1` even though this block has no second reference.
7589 // `record_compound_ctx` overwrites this with the real bit for an
7590 // actual compound block's cells, called right after this one.
7591 self.above_comp_group_idx[c..c + w_mi].fill(if altref { 3 } else { 0 });
7592 self.above_compound_idx[c..c + w_mi].fill(u8::from(altref));
7593 self.above_filter[c..c + w_mi].fill(filter);
7594 self.left_skip[r..r + h_mi].fill(skip);
7595 self.left_skip_mode[r..r + h_mi].fill(skip_mode);
7596 self.left_inter[r..r + h_mi].fill(is_inter);
7597 self.left_ref[r..r + h_mi].fill(ref_frame);
7598 self.left_ref1[r..r + h_mi].fill(None);
7599 self.left_comp_group_idx[r..r + h_mi].fill(if altref { 3 } else { 0 });
7600 self.left_compound_idx[r..r + h_mi].fill(u8::from(altref));
7601 self.left_filter[r..r + h_mi].fill(filter);
7602 }
7603
7604 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
7605 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
7606 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
7607 /// `get_comp_index_context`) -- called right after `record_inter` for
7608 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
7609 /// stamps `above_ref1`/`left_ref1` with the block's real second
7610 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
7611 /// this is the one caller that actually knows it) -- so the next block's
7612 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
7613 /// neighbour instead of `record_inter`'s single-ref default.
7614 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7615 fn record_compound_ctx(
7616 &mut self,
7617 at: (usize, usize),
7618 side: usize,
7619 ref1: i8,
7620 comp_group_idx: u8,
7621 compound_idx: u8,
7622 ) {
7623 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
7624 }
7625
7626 /// [`Self::record_compound_ctx`] with independent above/left extents,
7627 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
7628 #[allow(clippy::too_many_arguments)]
7629 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7630 fn record_compound_ctx_rect(
7631 &mut self,
7632 at: (usize, usize),
7633 w_sub: usize,
7634 h_sub: usize,
7635 ref1: i8,
7636 comp_group_idx: u8,
7637 compound_idx: u8,
7638 ) {
7639 let (r, c) = at;
7640 self.record_compound_ctx_rect_mi(
7641 (r * (SUB / MI), c * (SUB / MI)),
7642 w_sub / MI,
7643 h_sub / MI,
7644 ref1,
7645 comp_group_idx,
7646 compound_idx,
7647 );
7648 }
7649
7650 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
7651 /// [`Self::record_inter_rect_mi`]).
7652 fn record_compound_ctx_rect_mi(
7653 &mut self,
7654 at_mi: (usize, usize),
7655 w_mi: usize,
7656 h_mi: usize,
7657 ref1: i8,
7658 comp_group_idx: u8,
7659 compound_idx: u8,
7660 ) {
7661 let (r, c) = at_mi;
7662 crate::census::compound();
7663 for cell in 0..w_mi {
7664 self.above_ref1[c + cell] = Some(ref1);
7665 self.above_comp_group_idx[c + cell] = comp_group_idx;
7666 self.above_compound_idx[c + cell] = compound_idx;
7667 }
7668 for cell in 0..h_mi {
7669 self.left_ref1[r + cell] = Some(ref1);
7670 self.left_comp_group_idx[r + cell] = comp_group_idx;
7671 self.left_compound_idx[r + cell] = compound_idx;
7672 }
7673 }
7674
7675 /// The context of a block's partition symbol: delegates to the mi-precise
7676 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
7677 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
7678 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
7679 /// only touches the finer mi arrays -- leaves them stale for the *next*
7680 /// sibling's own partition symbol.
7681 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
7682 let (r, c) = at;
7683 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
7684 }
7685
7686 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
7687 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
7688 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
7689 /// than the enclosing 16x16 slot's stale, shared state.
7690 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
7691 2 * usize::from(usize::from(self.left_side_mi[mi_r]) * 2 <= side)
7692 + usize::from(usize::from(self.above_side_mi[mi_c]) * 2 <= side)
7693 }
7694
7695 /// The gathered coded/DC-sign state of the blocks above and to the left
7696 /// of a block `side` samples across, per plane.
7697 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
7698 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
7699 }
7700
7701 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
7702 /// units, for the same reason [`Self::record_mi`] does.
7703 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
7704 let side_mi = side / MI;
7705 // One pass over the cells accumulating all three planes, not one pass
7706 // per plane: the three planes of a cell live in the same
7707 // `[Neighbour; 3]` (6 bytes), so the per-plane form loaded the same
7708 // cache lines three times (lane-publish).
7709 let mut out = [(false, false, 0i32); 3];
7710 for cell in 0..side_mi {
7711 let above = &self.above[mi_c + cell];
7712 let left = &self.left[mi_r + cell];
7713 for (plane, o) in out.iter_mut().enumerate() {
7714 o.0 |= above[plane].level != 0;
7715 o.1 |= left[plane].level != 0;
7716 o.2 += dc_vote(above[plane].dc) + dc_vote(left[plane].dc);
7717 }
7718 }
7719 out
7720 }
7721
7722 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
7723 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
7724 /// extent pattern for a true rectangular strip's own coefficient context.
7725 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
7726 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
7727 }
7728
7729 /// [`Self::around_rect`] taking the block's position directly in 4x4
7730 /// mode-info units, mirroring [`Self::around_mi`].
7731 fn around_mi_rect(&self, (mi_r, mi_c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
7732 let (w_mi, h_mi) = (w / MI, h / MI);
7733 // [`Self::around_mi`]'s single pass, with the two extents split.
7734 let mut out = [(false, false, 0i32); 3];
7735 for cell in 0..w_mi {
7736 let above = &self.above[mi_c + cell];
7737 for (plane, o) in out.iter_mut().enumerate() {
7738 o.0 |= above[plane].level != 0;
7739 o.2 += dc_vote(above[plane].dc);
7740 }
7741 }
7742 for cell in 0..h_mi {
7743 let left = &self.left[mi_r + cell];
7744 for (plane, o) in out.iter_mut().enumerate() {
7745 o.1 |= left[plane].level != 0;
7746 o.2 += dc_vote(left[plane].dc);
7747 }
7748 }
7749 if crate::envflags::env_flag!("EC_DCDUMP") {
7750 for (plane, o) in out.iter().enumerate() {
7751 let vote = o.2;
7752 let ab: Vec<String> = (0..w_mi)
7753 .map(|k| format!("{:?}/{}", self.above[mi_c + k][plane].dc, self.above[mi_c + k][plane].level))
7754 .collect();
7755 let lf: Vec<String> = (0..h_mi)
7756 .map(|k| format!("{:?}/{}", self.left[mi_r + k][plane].dc, self.left[mi_r + k][plane].level))
7757 .collect();
7758 eprintln!("EC_DCDUMP mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]", ab.join(","), lf.join(","));
7759 }
7760 }
7761 out
7762 }
7763
7764 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
7765 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
7766 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
7767 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
7768 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
7769 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
7770 /// is always 0, spec's `plane_bsize == tx_size` branch).
7771 fn luma_skip_ctx(&self, at_mi: (usize, usize), side_mi: usize) -> usize {
7772 self.luma_skip_ctx_rect(at_mi, side_mi, side_mi)
7773 }
7774
7775 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi
7776 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above
7777 /// context over `tx_size_wide` and the left one over `tx_size_high`.
7778 fn luma_skip_ctx_rect(
7779 &self,
7780 (mi_r, mi_c): (usize, usize),
7781 w_mi: usize,
7782 h_mi: usize,
7783 ) -> usize {
7784 let side_mi = w_mi;
7785 let mut top = 0u8;
7786 let mut left = 0u8;
7787 for cell in 0..w_mi {
7788 top |= self.above[mi_c + cell][0].level;
7789 }
7790 for cell in 0..h_mi {
7791 left |= self.left[mi_r + cell][0].level;
7792 }
7793 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
7794 if crate::envflags::env_flag!("EC_ECDUMP") {
7795 let ab: Vec<String> =
7796 (0..w_mi).map(|k| self.above[mi_c + k][0].level.to_string()).collect();
7797 let lf: Vec<String> =
7798 (0..h_mi).map(|k| self.left[mi_r + k][0].level.to_string()).collect();
7799 eprintln!(
7800 "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},]",
7801 ab.join(","), lf.join(",")
7802 );
7803 }
7804 if crate::envflags::env_flag!("EC_AV1_TRACE") {
7805 eprintln!(
7806 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx} band={:?}",
7807 self.left.iter().map(|e| e[0].level).collect::<Vec<_>>()
7808 );
7809 }
7810 ctx
7811 }
7812
7813 /// Writes one coded block into every cell it covers, on both grids: the
7814 /// mode/side arrays up to `side`'s own width, and the coefficient-context
7815 /// arrays up to the true frame edge — the units past it are left at their
7816 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
7817 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
7818 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
7819 /// not from this block's own side).
7820 fn record(
7821 &mut self,
7822 at: (usize, usize),
7823 side: usize,
7824 mode: usize,
7825 uv_mode: usize,
7826 grids: &[&[i32]; 3],
7827 ) {
7828 self.record_rect(at, side, side, mode, uv_mode, grids);
7829 }
7830
7831 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
7832 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
7833 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
7834 /// spec's per-edge partition-context rule, so a true rectangular block
7835 /// naturally wants two different values here rather than one.
7836 /// Writes this block's luma `mode` into the mi-granular
7837 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
7838 /// position a *later* neighbour would read it from: the block's LAST mi
7839 /// row for every column it spans (what the block below reads via
7840 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
7841 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
7842 /// read these back, and only when the recorded position is exactly their
7843 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
7844 fn record_mode_mi(
7845 &mut self,
7846 mi_r: usize,
7847 mi_c: usize,
7848 mi_w: usize,
7849 mi_h: usize,
7850 mode: usize,
7851 ) {
7852 let (last_r, last_c) = ((mi_r + mi_h - 1) as u16, (mi_c + mi_w - 1) as u16);
7853 let mode = mode as u8;
7854 for cell in 0..mi_w {
7855 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
7856 *slot = (last_r, mode);
7857 }
7858 }
7859 for cell in 0..mi_h {
7860 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
7861 *slot = (last_c, mode);
7862 }
7863 }
7864 }
7865
7866 /// The mi-exact above/left neighbour luma mode for a block whose top-left
7867 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
7868 /// mi position (then the coarse [`SUB`]-grid slot is right by
7869 /// construction). See [`Self::record_mode_mi`].
7870 fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
7871 match self.sub8_mode_col.get(mi_c) {
7872 Some(&(row, m)) if mi_r > self.tile_row0_mi && usize::from(row) == mi_r - 1 => Some(usize::from(m)),
7873 _ => None,
7874 }
7875 }
7876
7877 fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
7878 match self.sub8_mode_row.get(mi_r) {
7879 Some(&(col, m)) if mi_c > self.tile_col0_mi && usize::from(col) == mi_c - 1 => Some(usize::from(m)),
7880 _ => None,
7881 }
7882 }
7883
7884 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
7885 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
7886 fn record_uv_mode_mi(
7887 &mut self,
7888 mi_r: usize,
7889 mi_c: usize,
7890 mi_w: usize,
7891 mi_h: usize,
7892 uv_mode: usize,
7893 ) {
7894 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
7895 fill_span(&mut self.uv_mode_col, mi_c, mi_w, (last_r as u16, uv_mode as u8));
7896 fill_span(&mut self.uv_mode_row, mi_r, mi_h, (last_c as u16, uv_mode as u8));
7897 // libaom writes one `MB_MODE_INFO` pointer into every mi cell a block
7898 // covers, so the chroma neighbour read below is a plain grid read.
7899 let stride = self.uv_grid_cols;
7900 let n = stride.saturating_sub(mi_c).min(last_c + 1 - mi_c);
7901 for row in mi_r..=last_r {
7902 fill_span(&mut self.uv_mode_grid, row * stride + mi_c, n, uv_mode as u8);
7903 }
7904 }
7905
7906 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
7907 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
7908 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
7909 /// block has recorded the exact neighbouring mi.
7910 fn smooth_uv_neighbour(&self, mi_r: usize, mi_c: usize, r: usize, c: usize) -> bool {
7911 // lane-kf900 r2: libaom reads the chroma neighbours off the CHROMA
7912 // REFERENCE block, not off the mi that carries the chroma syntax.
7913 // `set_mi_row_col` (`blockd.h`) takes
7914 // `base_mi = &xd->mi[-(mi_row & ss_y) * stride - (mi_col & ss_x)]` and
7915 // only then `chroma_above_mbmi = base_mi[-stride]` /
7916 // `chroma_left_mbmi = base_mi[-1]`. A sub-8 pair codes its chroma at
7917 // the ODD mi, so without the snap we looked one mi row/column too far
7918 // down/right -- the mi-exact slot never matched and the coarse
7919 // fallback answered instead. Measured on a 4K 10-bit key frame, chroma
7920 // 8x4 at (688, 100) = mi (51, 344): libaom's
7921 // `get_intra_edge_filter_type` is 1 (the chroma block above it is
7922 // `UV_SMOOTH_PRED`), ours was 0, which flips
7923 // `av1_use_intra_edge_upsample(8, 4, -6, type)` (`blk_wh == 12`:
7924 // false for type 1, TRUE for type 0) and upsampled an edge libaom
7925 // leaves alone -- +1 on rows 2/3 of that block and every chroma block
7926 // predicting from it (class `context-read-from-one-cell`).
7927 self.smooth_uv_neighbour_unsnapped(mi_r & !1, mi_c & !1, r, c)
7928 }
7929
7930 /// [`Self::smooth_uv_neighbour`] without the chroma-reference snap, i.e.
7931 /// read off the mi passed in exactly. Only the 16x4/4x16 pair witness
7932 /// counter wants this: it measures how often the snap CHANGES the answer,
7933 /// which is what the lane-kf1200/kf900 chroma-reference fix buys. Every
7934 /// decode path uses the snapping form.
7935 fn smooth_uv_neighbour_unsnapped(
7936 &self,
7937 mi_r: usize,
7938 mi_c: usize,
7939 r: usize,
7940 c: usize,
7941 ) -> bool {
7942 // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the
7943 // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid
7944 // array that `start_tile` does not clear, so a block on a tile's first
7945 // mi row used to read the uv_mode of the block above it in the tile
7946 // ABOVE and filter its chroma edge at that neighbour's strength
7947 // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block
7948 // at chroma (120, 32), the top-right tile's first block).
7949 let have_above = mi_r > self.tile_row0_mi;
7950 let have_left = mi_c > self.tile_col0_mi;
7951 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
7952 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
7953 {
7954 hit!(UV_TILE_EDGE_SUPPRESSED_HITS);
7955 }
7956 // The mi grid is libaom's own read; the two maps below stay as the
7957 // fallback for cells no block has written (see [`Self::uv_mode_grid`]).
7958 let cell = |grid: &Vec<u8>, row: usize, col: usize| -> Option<usize> {
7959 (col < self.uv_grid_cols)
7960 .then(|| grid.get(row * self.uv_grid_cols + col).copied())
7961 .flatten()
7962 .filter(|&m| m != u8::MAX)
7963 .map(usize::from)
7964 };
7965 let above = match self.uv_mode_col.get(mi_c) {
7966 _ if have_above && let Some(m) = cell(&self.uv_mode_grid, mi_r - 1, mi_c) => m,
7967 Some(&(row, m)) if have_above && usize::from(row) == mi_r - 1 => usize::from(m),
7968 _ if have_above => self.above_uv_mode[c],
7969 _ => DC_PRED,
7970 };
7971 let left = match self.uv_mode_row.get(mi_r) {
7972 _ if have_left && let Some(m) = cell(&self.uv_mode_grid, mi_r, mi_c - 1) => m,
7973 Some(&(col, m)) if have_left && usize::from(col) == mi_c - 1 => usize::from(m),
7974 _ if have_left => self.left_uv_mode[r],
7975 _ => DC_PRED,
7976 };
7977 if have_above && cell(&self.uv_mode_grid, mi_r - 1, mi_c).is_some_and(|m| {
7978 !matches!(self.uv_mode_col.get(mi_c), Some(&(row, cm)) if usize::from(row) == mi_r - 1 && usize::from(cm) == m)
7979 }) || have_left && cell(&self.uv_mode_grid, mi_r, mi_c - 1).is_some_and(|m| {
7980 !matches!(self.uv_mode_row.get(mi_r), Some(&(col, cm)) if usize::from(col) == mi_c - 1 && usize::from(cm) == m)
7981 }) {
7982 hit!(UV_MODE_GRID_OVERRIDE_HITS);
7983 }
7984 // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs
7985 // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would
7986 // have been filtered at the wrong strength by the coarse map alone.
7987 if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] {
7988 hit!(UV_MODE_MI_OVERRIDE_HITS);
7989 }
7990 if (is_smooth_mode(self.above_uv_mode[c]) && !is_smooth_mode(above))
7991 || (is_smooth_mode(self.left_uv_mode[r]) && !is_smooth_mode(left))
7992 {
7993 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
7994 }
7995 is_smooth_mode(above) || is_smooth_mode(left)
7996 }
7997
7998 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
7999 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
8000 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
8001 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
8002 /// holding an OLDER, larger block's mode -- it only ever recorded into the
8003 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
8004 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
8005 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
8006 /// a different CDF for the same mode value).
8007 /// lane-rectsplitx r2: availability-correct above/left luma modes for a
8008 /// block whose top-left mi is `(mi_r, mi_c)`. libaom reads `above_mbmi`
8009 /// only when `up_available` and `left_mbmi` only when `left_available`;
8010 /// the coarse [`SUB`] bands cannot express that, and with 8-px strips they
8011 /// actively lie -- four 32x8 strips of one `HORZ_4` share ONE 16x16
8012 /// `left_mode` cell, so the second strip at tile column 0 read the FIRST
8013 /// strip's mode as its "left neighbour" (measured on the band fixture at
8014 /// mi(10,0): mode 2 where libaom has DC, a different `kf_y_mode` row).
8015 fn modes_above_left_mi(
8016 &self,
8017 mi_r: usize,
8018 mi_c: usize,
8019 fallback: (usize, usize),
8020 ) -> (usize, usize) {
8021 let above = if mi_r > self.tile_row0_mi {
8022 self.mode_above_mi(mi_r, mi_c).unwrap_or(fallback.0)
8023 } else {
8024 DC_PRED
8025 };
8026 let left = if mi_c > self.tile_col0_mi {
8027 self.mode_left_mi(mi_r, mi_c).unwrap_or(fallback.1)
8028 } else {
8029 DC_PRED
8030 };
8031 (above, left)
8032 }
8033
8034 /// lane-modectx r1: the coarse-[`SUB`]-grid entry point, now availability
8035 /// correct. The mi-exact lookups already refuse to cross a tile edge, but
8036 /// their FALLBACK (`above_mode`/`left_mode`) did not: `left_mode` is reset
8037 /// per superblock row and never per tile, so the first block column of
8038 /// tile 2..N read the previous tile's mode as its left neighbour, and the
8039 /// above band survives across a tile ROW boundary the same way lane-mtfix's
8040 /// `above_uv_mode` did. libaom reads `above_mbmi`/`left_mbmi` only when
8041 /// `up_available`/`left_available` and uses DC_PRED otherwise
8042 /// ([`Self::modes_above_left_mi`]).
8043 fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
8044 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
8045 let (above, left) =
8046 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));
8047 if above != self.above_mode[c] || left != self.left_mode[r] {
8048 hit!(MODE_MI_OVERRIDE_HITS);
8049 }
8050 if (is_smooth_mode(self.above_mode[c]) && !is_smooth_mode(above))
8051 || (is_smooth_mode(self.left_mode[r]) && !is_smooth_mode(left))
8052 {
8053 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
8054 }
8055 // A neighbour the coarse band offered where the tile edge makes it
8056 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).
8057 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)
8058 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)
8059 {
8060 hit!(MODE_TILE_EDGE_COARSE_LEAKS);
8061 }
8062 (above, left)
8063 }
8064
8065 fn record_rect(
8066 &mut self,
8067 at: (usize, usize),
8068 w: usize,
8069 h: usize,
8070 mode: usize,
8071 uv_mode: usize,
8072 grids: &[&[i32]; 3],
8073 ) {
8074 self.record_rect_mi(sub16_to_mi(at), w, h, mode, uv_mode, grids);
8075 }
8076
8077 /// [`Self::record_rect`] in mi (4 px) units -- lane-inter4 r1: a
8078 /// 32x8/8x32 strip of a 32-level 1:4 partition sits at an 8-px offset the
8079 /// [`SUB`]-unit `at` cannot name. The coarse 16-px bands are still keyed
8080 /// by the enclosing cell (a sub-16 extent writes none of them, exactly as
8081 /// the [`SUB`]-unit path does).
8082 fn record_rect_mi(
8083 &mut self,
8084 at_mi: (usize, usize),
8085 w: usize,
8086 h: usize,
8087 mode: usize,
8088 uv_mode: usize,
8089 grids: &[&[i32]; 3],
8090 ) {
8091 let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI));
8092 // lane-inter4 r2: a strip whose own footprint runs past the frame's
8093 // last 16-px column/row stamps only the cells that exist (libaom's
8094 // arrays are padded past the frame and those cells are never read).
8095 for cell in 0..w / SUB {
8096 if c + cell >= self.above_mode.len() {
8097 break;
8098 }
8099 self.above_mode[c + cell] = mode;
8100 self.above_uv_mode[c + cell] = uv_mode;
8101 self.above_side[c + cell] = w;
8102 }
8103 for cell in 0..h / SUB {
8104 if r + cell >= self.left_mode.len() {
8105 break;
8106 }
8107 self.left_mode[r + cell] = mode;
8108 self.left_uv_mode[r + cell] = uv_mode;
8109 self.left_side[r + cell] = h;
8110 }
8111 self.record_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, mode);
8112 self.record_uv_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, uv_mode);
8113 self.record_mi_rect(at_mi, w, h, grids);
8114 }
8115
8116 /// The coefficient-context half of [`Self::record`], taking the block's
8117 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
8118 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
8119 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
8120 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[&[i32]; 3]) {
8121 self.record_mi_rect(at_mi, side, side, grids);
8122 }
8123
8124 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
8125 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
8126 fn record_mi_rect(
8127 &mut self,
8128 at_mi: (usize, usize),
8129 w: usize,
8130 h: usize,
8131 grids: &[&[i32]; 3],
8132 ) {
8133 let (mi_r, mi_c) = at_mi;
8134 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(grids[plane]));
8135 let (w_mi, h_mi) = (w / MI, h / MI);
8136 if crate::envflags::env_flag!("EC_ECPUB") {
8137 eprintln!("EC_ECPUB blk mi=({mi_r},{mi_c}) wh=({w},{h}) lvl={}", states[0].level);
8138 }
8139 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
8140 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
8141 // A chroma 4x4 unit straddling the true luma edge is still whole in
8142 // chroma's own halved grid, so libaom rounds the luma bound up to the
8143 // plane's own 4x4 unit before clamping a subsampled plane
8144 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
8145 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8146 let bound_h = [
8147 self.mi_rows,
8148 round_up_even(self.mi_rows),
8149 round_up_even(self.mi_rows),
8150 ];
8151 let bound_w = [
8152 self.mi_cols,
8153 round_up_even(self.mi_cols),
8154 round_up_even(self.mi_cols),
8155 ];
8156 // lane-sb128c r7: a 128x64 at the bottom frame edge names mi rows
8157 // past the padded side arrays (mi_rows 198, block rows 192..208);
8158 // libaom's own arrays are superblock-sized, so those cells simply
8159 // have no reader -- [`fill_span`] drops them, as the `break` did.
8160 // `bound_h[1] == bound_h[2] >= bound_h[0]`, so the per-cell plane
8161 // predicate is three contiguous runs: all planes, chroma only, none
8162 // (lane-mi).
8163 let luma_h = h_mi.min(bound_h[0].saturating_sub(mi_r));
8164 let chroma_h = h_mi.min(bound_h[1].saturating_sub(mi_r));
8165 let uv_only = [Neighbour::default(), states[1], states[2]];
8166 fill_span(&mut self.left, mi_r, luma_h, states);
8167 fill_span(&mut self.left, mi_r + luma_h, chroma_h - luma_h, uv_only);
8168 fill_span(
8169 &mut self.left,
8170 mi_r + chroma_h,
8171 h_mi - chroma_h,
8172 [Neighbour::default(); 3],
8173 );
8174 let luma_w = w_mi.min(bound_w[0].saturating_sub(mi_c));
8175 let chroma_w = w_mi.min(bound_w[1].saturating_sub(mi_c));
8176 let uv_only_w = [Neighbour::default(), states[1], states[2]];
8177 fill_span(&mut self.above, mi_c, luma_w, states);
8178 fill_span(&mut self.above, mi_c + luma_w, chroma_w - luma_w, uv_only_w);
8179 fill_span(
8180 &mut self.above,
8181 mi_c + chroma_w,
8182 w_mi - chroma_w,
8183 [Neighbour::default(); 3],
8184 );
8185 }
8186
8187 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
8188 /// inside a coded block whose luma transform is smaller than its own
8189 /// side (`TxMode::Select`): the real per-transform-unit coefficient
8190 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
8191 /// coarse per-block `tx_grid`/`fill_lf_grid` state
8192 /// [`Self::record_split_luma`] still writes once for the whole block.
8193 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
8194 /// the caller's own [`Self::record_split_luma`] call sets those once,
8195 /// at the block's own true side, not this TU's.
8196 fn record_mi_luma(&mut self, at_mi: (usize, usize), tx_px: usize, grid: &[i32]) {
8197 self.record_mi_luma_rect(at_mi, tx_px, tx_px, grid);
8198 }
8199
8200 /// [`Self::record_mi_luma`] for ONE CHROMA transform unit of a block whose
8201 /// uv plane block is several units (lane-sb128b r2: a 128x128 block's
8202 /// 64x64 uv plane block is four TX_32X32 units, `av1_get_max_uv_txsize`).
8203 /// `w_px`/`h_px` are the unit's extent in LUMA pixels -- the chroma
8204 /// coefficient-context arrays are indexed by luma mi, the convention
8205 /// [`Self::record_split_luma_rect_mi`] already writes them in, frame-edge
8206 /// clamp included.
8207 fn record_mi_chroma(
8208 &mut self,
8209 (mi_r, mi_c): (usize, usize),
8210 w_px: usize,
8211 h_px: usize,
8212 plane: usize,
8213 grid: &[i32],
8214 ) {
8215 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8216 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
8217 let state = neighbour_state(grid);
8218 for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) {
8219 self.left[mi_r + cell][plane] = state;
8220 }
8221 for cell in 0..(w_px / MI).min(bound_w.saturating_sub(mi_c)) {
8222 self.above[mi_c + cell][plane] = state;
8223 }
8224 }
8225
8226 /// [`Self::record_mi_luma`] for a RECTANGULAR transform unit (lane-rectsplitx
8227 /// r1): the above context spans the unit's width, the left context its
8228 /// height, which for a square unit is the same loop it always was.
8229 fn record_mi_luma_rect(
8230 &mut self,
8231 (mi_r, mi_c): (usize, usize),
8232 w_px: usize,
8233 h_px: usize,
8234 grid: &[i32],
8235 ) {
8236 let state = neighbour_state(grid);
8237 if crate::envflags::env_flag!("EC_ECPUB") {
8238 eprintln!("EC_ECPUB tu mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={}", state.level);
8239 }
8240 for cell in 0..h_px / MI {
8241 if mi_r + cell < self.mi_rows {
8242 self.left[mi_r + cell][0] = state;
8243 }
8244 }
8245 for cell in 0..w_px / MI {
8246 if mi_c + cell < self.mi_cols {
8247 self.above[mi_c + cell][0] = state;
8248 }
8249 }
8250 }
8251
8252 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
8253 /// block whose luma was decoded as several transform units through
8254 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
8255 /// whole-block luma write -- everything [`Self::record`] does except
8256 /// plane 0, which is already correct per-TU by the time this runs.
8257 fn record_split_luma(
8258 &mut self,
8259 at: (usize, usize),
8260 side: usize,
8261 mode: usize,
8262 uv_mode: usize,
8263 chroma_grids: [&[i32]; 2],
8264 ) {
8265 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
8266 }
8267
8268 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
8269 /// extents in pixels (lane-rectsplit r1), the same relationship
8270 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
8271 /// luma transform split into several square units needs exactly this
8272 /// bookkeeping, at its own true rectangular extents.
8273 fn record_split_luma_rect(
8274 &mut self,
8275 at: (usize, usize),
8276 w: usize,
8277 h: usize,
8278 mode: usize,
8279 uv_mode: usize,
8280 chroma_grids: [&[i32]; 2],
8281 ) {
8282 let (r, c) = at;
8283 self.record_split_luma_rect_mi(
8284 (r * (SUB / MI), c * (SUB / MI)),
8285 w,
8286 h,
8287 mode,
8288 uv_mode,
8289 chroma_grids,
8290 );
8291 }
8292
8293 /// [`Self::record_split_luma_rect`] addressed in mi units (lane-rectsplitx
8294 /// r1) -- a strip 8 px tall starts mid-[`SUB`]-cell, which the coarse
8295 /// `(r, c)` form cannot name. The coarse mode/side arrays are stamped for
8296 /// every cell the strip TOUCHES (`div_ceil`), last writer wins, the
8297 /// convention [`decode_block_rect4`] already established for 1:4 strips.
8298 fn record_split_luma_rect_mi(
8299 &mut self,
8300 at_mi: (usize, usize),
8301 w: usize,
8302 h: usize,
8303 mode: usize,
8304 uv_mode: usize,
8305 chroma_grids: [&[i32]; 2],
8306 ) {
8307 let (mi_r, mi_c) = at_mi;
8308 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
8309 for cell in 0..w.div_ceil(SUB) {
8310 if c + cell >= self.above_mode.len() {
8311 break;
8312 }
8313 self.above_mode[c + cell] = mode;
8314 self.above_uv_mode[c + cell] = uv_mode;
8315 self.above_side[c + cell] = w;
8316 }
8317 for cell in 0..h.div_ceil(SUB) {
8318 if r + cell >= self.left_mode.len() {
8319 break;
8320 }
8321 self.left_mode[r + cell] = mode;
8322 self.left_uv_mode[r + cell] = uv_mode;
8323 self.left_side[r + cell] = h;
8324 }
8325
8326 let (w_mi, h_mi) = (w / MI, h / MI);
8327 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
8328 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
8329 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
8330 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
8331 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8332 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
8333 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
8334 let plane = plane_idx + 1;
8335 let state = neighbour_state(grid);
8336 for cell in 0..h_mi {
8337 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
8338 self.left[mi_r + cell][plane] = state;
8339 }
8340 }
8341 for cell in 0..w_mi {
8342 if cell < w_mi.min(bound_w.saturating_sub(mi_c)) {
8343 self.above[mi_c + cell][plane] = state;
8344 }
8345 }
8346 }
8347 }
8348}
8349
8350/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
8351/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
8352/// exactly — including its skip context, which the real key-frame writer
8353/// always writes at a fixed context of zero (it never tracks a neighbour-based
8354/// one for intra blocks; that is the inter-frame writer's rule instead).
8355/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
8356/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
8357/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
8358/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
8359/// plain DC chroma.
8360/// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which
8361/// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's
8362/// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode
8363/// instead (the defect commit 1a89ed9 fixed at the square sites).
8364pub(crate) fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize {
8365 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
8366 filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi])
8367}
8368
8369/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
8370/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
8371/// bound (spec `filter_intra_mode_info` never reads a symbol there).
8372pub(crate) fn filter_intra_size_class(side: usize) -> Option<usize> {
8373 match side {
8374 4 => Some(0),
8375 8 => Some(1),
8376 16 => Some(2),
8377 32 => Some(3),
8378 _ => None,
8379 }
8380}
8381
8382/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
8383/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
8384/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
8385/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
8386fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
8387 match (bw, bh) {
8388 (32, 16) => Some(4),
8389 (16, 32) => Some(5),
8390 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
8391 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
8392 // here dropped that symbol on every DC_PRED strip of that size and
8393 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
8394 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
8395 (16, 8) => Some(6),
8396 (8, 16) => Some(7),
8397 // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <=
8398 // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of
8399 // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0.
8400 (4, 8) => Some(8),
8401 (8, 4) => Some(9),
8402 // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair
8403 // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no
8404 // `use_filter_intra` symbol on those strips although aomenc writes
8405 // one for every DC_PRED block of that shape with
8406 // `--enable-filter-intra=1` (its default), silently desyncing the
8407 // tile (class symbol-consumption-gap).
8408 (32, 8) => Some(10),
8409 (8, 32) => Some(11),
8410 // lane-r14: the 16x16-level 1:4 pair (`decode_rect4_16`'s 16x4/4x16
8411 // strips), rows 17/16 of `default_filter_intra_cdfs`.
8412 (16, 4) => Some(12),
8413 (4, 16) => Some(13),
8414 _ if bw == bh => filter_intra_size_class(bw),
8415 _ => None,
8416 }
8417}
8418
8419/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
8420/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
8421/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
8422/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
8423/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
8424pub(crate) fn palette_bsize_ctx(side: usize) -> Option<usize> {
8425 palette_bsize_ctx_wh(side, side)
8426}
8427
8428/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
8429/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
8430/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
8431/// for ANY bsize, not just the square ones a hand-picked table happened to
8432/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
8433/// row breaks the moment its indexing field moves off the diagonal, and a
8434/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
8435/// block dimension is a power of two, so `bw*bh` always is too and
8436/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
8437/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
8438fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
8439 // lane-r14: `av1_allow_palette`'s bound is `sb_type >= BLOCK_8X8` by the
8440 // BLOCK_SIZES_ALL enum INDEX, which the 1:4 shapes BLOCK_4X16 (16) and
8441 // BLOCK_16X4 (17) clear -- a 64-pixel block, so `av1_get_palette_bsize_ctx`
8442 // (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`) is 0 for them, exactly as
8443 // for an 8x8. Reading the dimension bound as "both sides >= 8" dropped
8444 // `palette_y_mode` on every 16x4/4x16 strip of a screen-content frame.
8445 if bw > 64 || bh > 64 || bw * bh < 64 {
8446 return None;
8447 }
8448 Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
8449}
8450
8451/// A just-decoded palette-Y block's own size, base colours (only the first
8452/// `size` entries are real), and per-pixel colour-index map (`side*side`,
8453/// row-major, each entry `< size`).
8454struct PaletteY {
8455 size: usize,
8456 colors: [u16; 8],
8457 map: Vec<u8>,
8458}
8459
8460/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
8461/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
8462/// shared between U and V, both co-located after 4:2:0 subsampling) plus
8463/// each plane's own base colours.
8464struct PaletteUv {
8465 size: usize,
8466 u_colors: [u16; 8],
8467 v_colors: [u16; 8],
8468 map: Vec<u8>,
8469}
8470
8471/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
8472/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
8473/// `get_unsigned_bits`, which is the same formula): smallest `n` with
8474/// `2^n >= x`, `0` for `x <= 1`.
8475pub(crate) fn ceil_log2(x: u32) -> u32 {
8476 if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() }
8477}
8478
8479/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
8480/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
8481fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
8482 let l = ceil_log2(n as u32);
8483 let m = (1usize << l) - n;
8484 let v = dec.literal(l - 1) as usize;
8485 if v < m {
8486 v
8487 } else {
8488 (v << 1) - m + dec.literal(1) as usize
8489 }
8490}
8491
8492/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
8493/// colours (already-known, from the above/left neighbours) with the
8494/// ascending `transmitted` ones (delta-coded off the wire) back into one
8495/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
8496/// value picks the cached copy first, matching the C `<=`.
8497fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
8498 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
8499 let (mut ci, mut ti) = (0, 0);
8500 while ci < cached.len() && ti < transmitted.len() {
8501 if cached[ci] <= transmitted[ti] {
8502 out.push(cached[ci]);
8503 ci += 1;
8504 } else {
8505 out.push(transmitted[ti]);
8506 ti += 1;
8507 }
8508 }
8509 out.extend_from_slice(&cached[ci..]);
8510 out.extend_from_slice(&transmitted[ti..]);
8511 out
8512}
8513
8514/// `read_palette_colors_y` (decodemv.c:478), at the sequence's real
8515/// `bit_depth` -- lane-kf900 r3: every raw literal here (the first colour,
8516/// each delta's width, the `range` bound and the clamp) is sized by
8517/// `bit_depth`, and hardcoding 8 read 2 bits too few per colour on every
8518/// 10-bit palette block. Raw literals are EQUIPROBABLE, and at the ranges
8519/// this stream reaches (e.g. 62728) an equiprobable read is a FIXED POINT of
8520/// the msac range, so a cross-decoder range ladder stays bit-identical
8521/// through the whole miscount -- only the decoded VALUE differs (class
8522/// `compare-range-not-tell`'s blind spot). (this
8523/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
8524/// (one flag bit each, in cache order), then delta-codes the remainder
8525/// (first value raw, each following delta `>= 1` off a shrinking bit width),
8526/// and merges the two ascending lists back together.
8527fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16], fctx: &crate::decode::FrameCtx) -> [u16; 8] {
8528 let mut cached = Vec::with_capacity(n);
8529 for &c in cache {
8530 if cached.len() >= n {
8531 break;
8532 }
8533 if dec.literal(1) == 1 {
8534 cached.push(c);
8535 }
8536 }
8537 let bd = u32::from(bit_depth(fctx));
8538 let max_val = (1i32 << bd) - 1;
8539 let mut colors = [0u16; 8];
8540 let n_cached = cached.len();
8541 if n_cached < n {
8542 let mut transmitted = Vec::with_capacity(n - n_cached);
8543 let first = dec.literal(bd) as u16;
8544 transmitted.push(first);
8545 if n_cached + 1 < n {
8546 let min_bits = bd - 3;
8547 let mut bits = min_bits + dec.literal(2);
8548 let mut range = (1i32 << bd) - i32::from(first) - 1;
8549 for _ in (n_cached + 1)..n {
8550 let delta = dec.literal(bits) as i32 + 1;
8551 let prev = *transmitted.last().unwrap();
8552 let val = (i32::from(prev) + delta).clamp(0, max_val) as u16;
8553 range -= i32::from(val) - i32::from(prev);
8554 bits = bits.min(ceil_log2(range.max(0) as u32));
8555 transmitted.push(val);
8556 }
8557 }
8558 let merged = merge_colors(&transmitted, &cached);
8559 colors[..n].copy_from_slice(&merged);
8560 } else {
8561 colors[..n].copy_from_slice(&cached[..n]);
8562 }
8563 colors
8564}
8565
8566/// `read_palette_colors_uv` (decodemv.c:509), at the sequence's real
8567/// `bit_depth` (see [`read_palette_colors_y`]): U reads
8568/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
8569/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
8570/// unbiased by `+1` -- both differences from Y's own reader, matching the C
8571/// side by side). V never uses a cache: a leading bit picks either `n` raw
8572/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
8573/// rather than clamp.
8574fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16], fctx: &crate::decode::FrameCtx) -> ([u16; 8], [u16; 8]) {
8575 let mut cached = Vec::with_capacity(n);
8576 for &c in cache {
8577 if cached.len() >= n {
8578 break;
8579 }
8580 if dec.literal(1) == 1 {
8581 cached.push(c);
8582 }
8583 }
8584 let bd = u32::from(bit_depth(fctx));
8585 let max_val = 1i32 << bd;
8586 let mut u_colors = [0u16; 8];
8587 let n_cached = cached.len();
8588 if n_cached < n {
8589 let mut transmitted = Vec::with_capacity(n - n_cached);
8590 let first = dec.literal(bd) as u16;
8591 transmitted.push(first);
8592 if n_cached + 1 < n {
8593 let min_bits = bd - 3;
8594 let mut bits = min_bits + dec.literal(2);
8595 let mut range = max_val - i32::from(first);
8596 for _ in (n_cached + 1)..n {
8597 let delta = dec.literal(bits) as i32;
8598 let prev = *transmitted.last().unwrap();
8599 let val = (i32::from(prev) + delta).clamp(0, max_val - 1) as u16;
8600 range -= i32::from(val) - i32::from(prev);
8601 bits = bits.min(ceil_log2(range.max(0) as u32));
8602 transmitted.push(val);
8603 }
8604 }
8605 let merged = merge_colors(&transmitted, &cached);
8606 u_colors[..n].copy_from_slice(&merged);
8607 } else {
8608 u_colors[..n].copy_from_slice(&cached[..n]);
8609 }
8610 let mut v_colors = [0u16; 8];
8611 if dec.literal(1) == 1 {
8612 let min_bits_v = bd - 4;
8613 let bits = min_bits_v + dec.literal(2);
8614 v_colors[0] = dec.literal(bd) as u16;
8615 for i in 1..n {
8616 let mut delta = dec.literal(bits) as i32;
8617 if delta != 0 && dec.literal(1) == 1 {
8618 delta = -delta;
8619 }
8620 let mut val = i32::from(v_colors[i - 1]) + delta;
8621 if val < 0 {
8622 val += max_val;
8623 }
8624 if val >= max_val {
8625 val -= max_val;
8626 }
8627 v_colors[i] = val as u16;
8628 }
8629 } else {
8630 for i in 0..n {
8631 v_colors[i] = dec.literal(bd) as u16;
8632 }
8633 }
8634 (u_colors, v_colors)
8635}
8636
8637/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
8638/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
8639/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
8640const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
8641
8642/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
8643/// map's own per-pixel context and colour-order permutation, from the
8644/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
8645/// selection sort). `map`'s stride is `side` (this decoder never crops a
8646/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
8647/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
8648/// actual colour index to store.
8649pub(crate) fn palette_color_index_context(
8650 map: &[u8],
8651 side: usize,
8652 row: usize,
8653 col: usize,
8654 n: usize,
8655) -> (usize, [u8; 8]) {
8656 let left = if col >= 1 { Some(map[row * side + col - 1]) } else { None };
8657 let up_left = if col >= 1 && row >= 1 {
8658 Some(map[(row - 1) * side + col - 1])
8659 } else {
8660 None
8661 };
8662 let up = if row >= 1 { Some(map[(row - 1) * side + col]) } else { None };
8663 let mut scores = [0i32; 8];
8664 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
8665 if let Some(v) = neighbour {
8666 scores[v as usize] += weight;
8667 }
8668 }
8669 let mut color_order = [0u8; 8];
8670 for i in 0..8 {
8671 color_order[i] = i as u8;
8672 }
8673 for i in 0..3 {
8674 let mut max = scores[i];
8675 let mut max_idx = i;
8676 for j in (i + 1)..n {
8677 if scores[j] > max {
8678 max = scores[j];
8679 max_idx = j;
8680 }
8681 }
8682 if max_idx != i {
8683 let max_score = scores[max_idx];
8684 let max_color = color_order[max_idx];
8685 for k in (i + 1..=max_idx).rev() {
8686 scores[k] = scores[k - 1];
8687 color_order[k] = color_order[k - 1];
8688 }
8689 scores[i] = max_score;
8690 color_order[i] = max_color;
8691 }
8692 }
8693 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
8694 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
8695 (ctx as usize, color_order)
8696}
8697
8698/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
8699/// map's wavefront decode over a `side x side` grid -- this decoder's
8700/// palette blocks are always square and never straddle the frame's true
8701/// (possibly odd) edge without already allocating the full `side*side`
8702/// region (every other skip/residual path here does the same), so no
8703/// rows/cols-vs-plane_width/height cropping special case is needed, unlike
8704/// libaom's own non-block-aligned split.
8705fn decode_color_index_map(
8706 dec: &mut SymbolDecoder,
8707 cdfs: &mut Cdfs,
8708 n: usize,
8709 side: usize,
8710 uv: bool,
8711) -> Vec<u8> {
8712 decode_color_index_map_wh(dec, cdfs, n, side, side, uv)
8713}
8714
8715/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
8716/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
8717/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
8718/// independently rather than one shared `side` -- the square call above is
8719/// just `bw == bh`.
8720fn decode_color_index_map_wh(
8721 dec: &mut SymbolDecoder,
8722 cdfs: &mut Cdfs,
8723 n: usize,
8724 bw: usize,
8725 bh: usize,
8726 uv: bool,
8727) -> Vec<u8> {
8728 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
8729 let mut map = vec![0u8; bw * bh];
8730 if trace {
8731 let (rng, _) = dec.debug_state();
8732 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
8733 }
8734 map[0] = read_uniform(dec, n) as u8;
8735 if trace {
8736 let (rng, _) = dec.debug_state();
8737 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
8738 }
8739 for i in 1..(bw + bh - 1) {
8740 let j_hi = i.min(bw - 1);
8741 let j_lo = i.saturating_sub(bh - 1);
8742 for j in (j_lo..=j_hi).rev() {
8743 let row = i - j;
8744 let col = j;
8745 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
8746 if trace {
8747 let (rng, _) = dec.debug_state();
8748 let row_cdf = if uv {
8749 &cdfs.palette_uv_color_index[n - 2][ctx]
8750 } else {
8751 &cdfs.palette_y_color_index[n - 2][ctx]
8752 };
8753 eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} cdf0={} cnt={} rng={rng}", row_cdf[0], row_cdf[n]);
8754 }
8755 let symbol = if uv {
8756 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
8757 } else {
8758 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
8759 };
8760 map[row * bw + col] = color_order[symbol];
8761 if trace {
8762 let (rng, _) = dec.debug_state();
8763 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
8764 }
8765 }
8766 }
8767 map
8768}
8769
8770/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
8771/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
8772/// size class comes from [`filter_intra_size_class_rect`] instead of the
8773/// square-only [`filter_intra_size_class`], and the palette read (when
8774/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
8775/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
8776/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
8777/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
8778#[allow(clippy::too_many_arguments)]
8779fn read_intra_mode_rect(
8780 dec: &mut SymbolDecoder,
8781 cdfs: &mut Cdfs,
8782 above_mode: usize,
8783 left_mode: usize,
8784 cfl: bool,
8785 // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall
8786 // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads
8787 // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's
8788 // chroma is coded once, on the closing strip). Every other caller is a
8789 // block big enough to own its chroma and passes `true`.
8790 has_chroma: bool,
8791 bw: usize,
8792 bh: usize,
8793 enable_filter_intra: bool,
8794 skip_ctx: usize,
8795 allow_screen_content_tools: bool,
8796 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
8797 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
8798 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
8799 palette: Option<(usize, &[u16])>,
8800 palette_uv_cache: &[u16],
8801 mi_r: usize,
8802 mi_c: usize, fctx: &crate::decode::FrameCtx,
8803) -> Result<(
8804 bool,
8805 usize,
8806 i32,
8807 usize,
8808 i32,
8809 Option<(i32, i32)>,
8810 Option<usize>,
8811 Option<PaletteY>,
8812 Option<PaletteUv>,
8813)> {
8814 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
8815 if ec_istep {
8816 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
8817 // (decodemv.c:818), printed at the same point: before the first
8818 // mode-info symbol of the block, so a cross-decoder range ladder can
8819 // be keyed on the BLOCK, not just on the symbol sequence.
8820 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);
8821 }
8822 macro_rules! istep {
8823 ($name:literal, $val:expr) => {
8824 if ec_istep {
8825 let (rng, _) = dec.debug_state();
8826 eprintln!(
8827 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
8828 $name, $val
8829 );
8830 }
8831 };
8832 }
8833 // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is
8834 // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at
8835 // the one point every rect caller routes through, so no call site can
8836 // offer the 14-symbol CFL alphabet on a 64-axis block (class
8837 // wrong-alphabet-same-value: same value, wrong interval, silent desync).
8838 let cfl = if cfl && bw.max(bh) > 32 {
8839 hit!(NOCFL_UV_MODE_HITS);
8840 false
8841 } else {
8842 cfl
8843 };
8844 // lane-intra14 r1: on the INTER block path everything up to and including
8845 // `is_inter` was already read by [`decode_inter_block`], so this reader
8846 // starts at the mode syntax with the `skip` that caller read.
8847 let inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get);
8848 let skip = if let Some((_, skip)) = inter {
8849 skip
8850 } else {
8851 // Same `intra_segment_id` placement as the square reader above.
8852 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
8853 if seg_id_pre_skip(fctx) {
8854 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
8855 }
8856 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
8857 istep!("skip", skip as i32);
8858 if !seg_id_pre_skip(fctx) {
8859 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
8860 }
8861 maybe_read_cdef_idx(dec, mi_r, mi_c, skip, fctx);
8862 istep!("cdef", 0);
8863 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
8864 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
8865 // `false`.
8866 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
8867 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
8868 istep!("dq", 0);
8869 // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after
8870 // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the
8871 // `use_intrabc` symbol is read for EVERY intra block of an `allow_intrabc`
8872 // frame -- `av1_allow_intrabc` is a frame-level test with no shape term, so
8873 // rect strips read it exactly like square leaves ([`read_intra_mode`],
8874 // [`read_intra_mode_sub8`]). Missing it here desynced the arithmetic
8875 // decoder at the FIRST symbol of the first rect block of every
8876 // `--tune-content=screen` key frame. Reconstruction of a real intrabc
8877 // block at this shape is out of scope, so the flag is consumed and
8878 // refused by name when it fires.
8879 if allow_intrabc_frame(fctx) {
8880 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
8881 hit!(RECT_INTRABC_READS);
8882 istep!("intrabc", use_intrabc as i32);
8883 if use_intrabc {
8884 hit!(INTRABC_HITS);
8885 return Err(unsupported(
8886 "intra block copy on a HORZ/VERT/1:4 rect intra strip (reconstruction is not ported at this shape)",
8887 ));
8888 }
8889 }
8890 skip
8891 };
8892 // libaom `read_intra_block_mode_info` (decodemv.c:1189) vs the key
8893 // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode`
8894 // off `kf_y_mode_cdf[above][left]`).
8895 let mode = if let Some((size_group, _)) = inter {
8896 dec.symbol(&mut cdfs.y_mode[size_group])
8897 } else {
8898 let above_ctx = INTRA_MODE_CTX[above_mode];
8899 let left_ctx = INTRA_MODE_CTX[left_mode];
8900 dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx])
8901 };
8902 istep!("mode", mode as i32);
8903 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
8904 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
8905 } else {
8906 0
8907 };
8908 istep!("angle_y", angle_delta_y);
8909 // lane-sb128c r3 (class sweep): libaom `read_intra_mode_uv(.., is_cfl_allowed(xd), ..)`
8910 // and `is_cfl_allowed` (blockd.h) is `block_size_wide[bsize] <= 32 &&
8911 // block_size_high[bsize] <= 32` on the LUMA bsize. Deciding the alphabet
8912 // here, from the block's own size, is the single point every caller routes
8913 // through -- a caller passing `true` for a >32 strip used to pick the
8914 // 14-symbol CFL CDF, same value but a different range (class
8915 // wrong-alphabet-same-value).
8916 let cfl = cfl && cfl_allowed_px(bw, bh, fctx);
8917 let uv_mode = if !has_chroma {
8918 DC_PRED
8919 } else if cfl {
8920 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
8921 } else {
8922 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
8923 };
8924 istep!("uv_mode", uv_mode as i32);
8925 let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED {
8926 Some(read_cfl_alphas(dec, cdfs))
8927 } else {
8928 None
8929 };
8930 if has_chroma && (9..=12).contains(&uv_mode) {
8931 hit!(SMOOTH_UV_HITS);
8932 }
8933 let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) {
8934 hit!(DIRECTIONAL_UV_HITS);
8935 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
8936 } else {
8937 0
8938 };
8939 istep!("angle_uv", angle_delta_uv);
8940 if angle_delta_uv != 0 {
8941 hit!(UV_ANGLE_DELTA_HITS);
8942 }
8943 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
8944 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
8945 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
8946 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
8947 // colours only here, the colour-index maps deferred past `filter_intra`
8948 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
8949 // runs from the caller, after the whole mode-info read).
8950 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
8951 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
8952 if allow_screen_content_tools
8953 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
8954 {
8955 // r6: this is the exact site the removed blanket refusal used to
8956 // guard -- reached for EVERY rect strip in a screen-content frame,
8957 // independent of whether the block ends up using a palette.
8958 hit!(RECT_SCREEN_CONTENT_HITS);
8959 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
8960 let use_palette_y =
8961 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
8962 if use_palette_y {
8963 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
8964 let colors = read_palette_colors_y(dec, n, cache, fctx);
8965 palette_y_pending = Some((n, colors));
8966 }
8967 let palette_uv_mode_ctx = usize::from(use_palette_y);
8968 // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard.
8969 if has_chroma
8970 && uv_mode == DC_PRED
8971 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
8972 {
8973 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
8974 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
8975 palette_uv_pending = Some((n, u_colors, v_colors));
8976 }
8977 }
8978 let mut filter_intra = None;
8979 if crate::envflags::env_flag!("EC_AV1_TRACE") {
8980 let (rng, _) = dec.debug_state();
8981 eprintln!(
8982 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
8983 class={:?} rng={rng}",
8984 enable_filter_intra as i32,
8985 filter_intra_size_class_rect(bw, bh)
8986 );
8987 }
8988 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
8989 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
8990 if mode == DC_PRED
8991 && enable_filter_intra
8992 && palette_y_pending.is_none()
8993 && let Some(class) = filter_intra_size_class_rect(bw, bh)
8994 {
8995 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
8996 if crate::envflags::env_flag!("EC_AV1_TRACE") {
8997 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
8998 }
8999 istep!("use_filter_intra", use_filter_intra as i32);
9000 if use_filter_intra {
9001 hit!(FILTER_INTRA_HITS);
9002 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
9003 istep!("filter_intra_mode", fi_mode as i32);
9004 filter_intra = Some(fi_mode);
9005 }
9006 }
9007 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
9008 // same order as [`read_intra_mode`]'s own square path.
9009 let palette_y = palette_y_pending.map(|(n, colors)| {
9010 let map = decode_color_index_map_wh(dec, cdfs, n, bw, bh, false);
9011 hit!(PALETTE_HITS);
9012 hit!(PALETTE_RECT_HITS);
9013 PaletteY { size: n, colors, map }
9014 });
9015 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
9016 // `av1_get_plane_block_size(bsize, 1, 1)` (`ss_size_lookup`), NOT a
9017 // plain halving: BLOCK_16X4 subsamples to BLOCK_8X4 and BLOCK_4X16 to
9018 // BLOCK_4X8, both floored at the 4-px transform. Halving the short
9019 // axis to 2 read HALF the colour-index symbols of a 1:4 strip's
9020 // chroma palette and desynced the tile from there.
9021 let (cw, ch) = ((bw / 2).max(4), (bh / 2).max(4));
9022 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, true);
9023 hit!(PALETTE_UV_HITS);
9024 PaletteUv { size: n, u_colors, v_colors, map }
9025 });
9026 Ok((
9027 skip,
9028 mode,
9029 angle_delta_y,
9030 uv_mode,
9031 angle_delta_uv,
9032 alpha,
9033 filter_intra,
9034 palette_y,
9035 palette_uv,
9036 ))
9037}
9038
9039/// Stamps a 1:4 strip's palette state into the mi-granular above/left arrays,
9040/// at the strip's REAL mi position. `av1_get_palette_cache` reads
9041/// `xd->above_mbmi`/`xd->left_mbmi`, i.e. the mi cell above/left of the
9042/// block, so each strip owns its own rows and columns and no aliasing rule
9043/// is needed (lane-kf900 r6).
9044#[allow(clippy::too_many_arguments)]
9045fn record_strip_palette(
9046 n: &mut Neighbours,
9047 mi: (usize, usize),
9048 bw: usize,
9049 bh: usize,
9050 y_size: usize,
9051 y_colors: [u16; 8],
9052 uv_size: usize,
9053 uv_colors: [u16; 8],
9054) {
9055 let (r, c) = mi;
9056 // lane-t900 r23 rung: every publication of a block's palette state into
9057 // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode
9058 // path left a stale `left_palette_size` behind when
9059 // `av1_get_palette_mode_ctx` disagrees with libaom's.
9060 if crate::envflags::env_flag!("EC_PALPUB") {
9061 eprintln!("EC_PALPUB strip mi={r},{c} bw={bw} bh={bh} y={y_size} uv={uv_size}");
9062 }
9063 // lane-kf900 r6: the palette side bands are mi-granular now, so a strip
9064 // writes its OWN span on BOTH axes -- the old `last` split-axis rule only
9065 // existed because the 16px [`SUB`] cell held one slot for all the strips
9066 // of a HORZ_4/VERT_4 and leaf 0 zeroing the other axis threw away the
9067 // real neighbour leaf 1 reads.
9068 {
9069 for cell in 0..(bw / MI).max(1) {
9070 if let Some(e) = n.above_palette_size.get_mut(c + cell) {
9071 *e = y_size as u8;
9072 n.above_palette_uv_size[c + cell] = uv_size as u8;
9073 // lane-publish2, see [`Neighbours::record_palette_y_rect`]:
9074 // colours of a size-0 neighbour are never read.
9075 if y_size > 0 {
9076 n.above_palette_colors[c + cell] = y_colors;
9077 }
9078 if uv_size > 0 {
9079 n.above_palette_uv_colors[c + cell] = uv_colors;
9080 }
9081 }
9082 }
9083 }
9084 {
9085 for cell in 0..(bh / MI).max(1) {
9086 if n.left_palette_size.get(r + cell).is_none() {
9087 break;
9088 }
9089 n.left_palette_size[r + cell] = y_size as u8;
9090 n.left_palette_uv_size[r + cell] = uv_size as u8;
9091 if y_size > 0 {
9092 n.left_palette_colors[r + cell] = y_colors;
9093 }
9094 if uv_size > 0 {
9095 n.left_palette_uv_colors[r + cell] = uv_colors;
9096 }
9097 }
9098 }
9099}
9100
9101/// [`tx_size_context`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
9102/// `get_tx_size_context` (libaom `pred_common.h`) compares the neighbour
9103/// above against this block's own *width* and the neighbour to the left
9104/// against its own *height* -- for a square block those are the same value,
9105/// which is why the square-only version can get away with one `own_side`.
9106fn tx_size_context_rect(
9107 n: &Neighbours,
9108 (mi_r, mi_c): (usize, usize),
9109 own_w: usize,
9110 own_h: usize,
9111) -> usize {
9112 // `get_tx_size_context` compares against `max_txsize_rect_lookup[bsize]`,
9113 // not the block's own side: no transform is wider or taller than 64, so a
9114 // block with a 128 side resolves against 64 (the square path already caps
9115 // this way, lane-sb128b r1). Without the cap the 64x128 half of a 128-root
9116 // VERT reads the tx-depth symbol off row 0 where libaom uses row 1.
9117 let (own_w, own_h) = (own_w.min(64), own_h.min(64));
9118 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w;
9119 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h;
9120 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
9121 eprintln!(
9122 "EC_TXCTX mi_row={mi_r} mi_col={mi_c} w={own_w} h={own_h} above_px={} left_px={} ctx={}",
9123 if mi_r > n.tile_row0_mi { tx_px_at(n, false, mi_r - 1, mi_c) } else { 0 },
9124 if mi_c > n.tile_col0_mi { tx_h_px_at(n, false, mi_r, mi_c - 1) } else { 0 },
9125 usize::from(above) + usize::from(left)
9126 );
9127 }
9128 usize::from(above) + usize::from(left)
9129}
9130
9131/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
9132fn cfl_ac_q3_rect(y: &PlaneBuf<'_>, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
9133 cfl_ac_q3_at(px, py, bw, bh, |lx, ly| i32::from(y.data[ly * y.width + lx]))
9134}
9135
9136/// Everything a rect strip already read out of the stream before its luma
9137/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
9138/// (nine values that would otherwise be nine more parameters).
9139struct RectStripModes {
9140 skip: bool,
9141 mode: usize,
9142 angle_delta_y: i32,
9143 uv_predict_mode: usize,
9144 angle_delta_uv: i32,
9145 alpha: Option<(i32, i32)>,
9146 filter_intra: Option<usize>,
9147 smooth_neighbor: bool,
9148 smooth_neighbor_uv: bool,
9149 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
9150 /// mapped through the colour table), sliced per transform unit below --
9151 /// palette prediction reads no edge pixels, so a unit's slice of the
9152 /// whole-block map IS its prediction. Without this a palette strip whose
9153 /// transform splits predicted DC and came out flat grey while the entropy
9154 /// stream stayed in sync (the coefficients are read either way).
9155 palette_y: Option<Vec<u16>>,
9156 /// As `palette_y`, for the un-split chroma transform (U, V).
9157 palette_uv: Option<(Vec<u16>, Vec<u16>)>,
9158}
9159
9160/// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth`
9161/// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times
9162/// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the
9163/// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's
9164/// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 ->
9165/// TX_32X16`) and only the second reaches a square -- the reason
9166/// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
9167/// already square) mis-tiled 1:4 strips.
9168fn depth_to_tx_wh(
9169 bw: usize,
9170 bh: usize,
9171 depth: usize,
9172 fctx: &crate::decode::FrameCtx,
9173) -> (usize, usize) {
9174 // lane-lossless: TX_4X4 whatever the strip's own size and depth (libaom
9175 // `read_tx_size`: the lossless early return comes before
9176 // `max_txsize_rect_lookup`), and no `tx_depth` symbol was read to get here.
9177 if lossless(fctx) {
9178 return (4, 4);
9179 }
9180 let (mut w, mut h) = (bw.min(64), bh.min(64));
9181 for _ in 0..depth {
9182 match w.cmp(&h) {
9183 std::cmp::Ordering::Greater => w /= 2,
9184 std::cmp::Ordering::Less => h /= 2,
9185 std::cmp::Ordering::Equal => {
9186 w /= 2;
9187 h /= 2;
9188 }
9189 }
9190 }
9191 (w, h)
9192}
9193
9194/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
9195/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
9196/// rect path here refused by name until now ("per-unit rect prediction is not
9197/// ported").
9198///
9199/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
9200/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
9201/// strip the very first step already lands on a SQUARE transform
9202/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
9203/// every further step halves a square) -- so each unit is square and reads
9204/// through the ordinary square [`read_plane`]. What is genuinely rectangular
9205/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
9206/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
9207/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
9208/// split by luma's depth.
9209///
9210/// Each unit predicts off whatever the earlier units of this same block
9211/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
9212/// inside `av1_foreach_transformed_block`, raster order), which is exactly
9213/// what predicting the whole strip in one shot got wrong.
9214#[allow(clippy::too_many_arguments)]
9215fn decode_rect_split(
9216 dec: &mut SymbolDecoder,
9217 cdfs: &mut Cdfs,
9218 neighbours: &mut Neighbours,
9219 at_mi: (usize, usize),
9220 bw: usize,
9221 bh: usize,
9222 // The transform unit's own width and height in pixels. Square for every
9223 // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
9224 // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
9225 // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
9226 tx_w: usize,
9227 tx_h: usize,
9228 m: &RectStripModes,
9229 y: &mut PlaneBuf<'static>,
9230 u: &mut PlaneBuf<'static>,
9231 v: &mut PlaneBuf<'static>,
9232 base_q_idx: u8,
9233 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
9234) -> Result<()> {
9235 let (mi_r, mi_c) = at_mi;
9236 let (px, py) = (mi_c * MI, mi_r * MI);
9237 let (cpx, cpy) = (px / 2, py / 2);
9238 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
9239 // The chroma transform is picked before any symbol is read, so an
9240 // unsupported chroma shape refuses before this strip desyncs the tile.
9241 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
9242 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
9243 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
9244 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
9245 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
9246 // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32
9247 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx`
9248 // squares a rect transform down to a CDF set by
9249 // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set,
9250 // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets
9251 // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`)
9252 // paths already prove for these same shapes.
9253 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
9254 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
9255 (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])),
9256 (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])),
9257 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
9258 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
9259 _ => None,
9260 };
9261 if !m.skip {
9262 if let Some(i) = match (chroma_w, chroma_h) {
9263 (32, 8) => Some(0),
9264 (8, 32) => Some(1),
9265 (8, 4) => Some(2),
9266 (4, 8) => Some(3),
9267 _ => None,
9268 } {
9269 hit_do! {
9270 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
9271 let mut hits = c.get();
9272 hits[i] += 1;
9273 c.set(hits);
9274 });
9275 }
9276 }
9277 if chroma.is_none() {
9278 // Diagnostic for the next caller that lands here (class
9279 // refusal-names-a-correlate: the message names the tool, not the
9280 // shape); the refusal below keeps its inventory-pinned wording.
9281 eprintln!("EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} chroma={chroma_w}x{chroma_h}");
9282 }
9283 }
9284 // lane-rectsplit r2 (verifier finding): with both callers wired
9285 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
9286 // 64x32/32x64) every shape that reaches here has a table above, so this
9287 // arm is UNREACHABLE today. It stays as the shape guard for the next
9288 // caller -- a new strip size would otherwise hit the `expect` below and
9289 // panic instead of refusing by name -- and so stays in
9290 // `refusal_inventory::REFUSALS`.
9291 if !m.skip && chroma.is_none() {
9292 return Err(unsupported(
9293 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
9294 ));
9295 }
9296 hit!(RECT_SPLIT_TX_HITS);
9297 if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 {
9298 hit!(RECT_SPLIT_SB_INTERIOR_TU_HITS);
9299 }
9300 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
9301 // A square unit reads through the ordinary square [`read_plane`]; a rect
9302 // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with
9303 // the very tables the unsplit 16x8/32x16 paths use.
9304 let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) {
9305 (w, h) if w == h => None,
9306 (16, 8) | (8, 16) => Some((
9307 if reduced_tx_set {
9308 TxbSet::LumaRect16x8
9309 } else {
9310 TxbSet::LumaRect16x8Set1
9311 },
9312 if tx_w == 16 { &SCAN_16X8[..] } else { &SCAN_8X16[..] },
9313 )),
9314 (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])),
9315 (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])),
9316 // lane-rect64port r1: the un-split TX_64X32/TX_32X64 of a 64-level
9317 // strip, read through the `luma_64corner` arm below instead of a rect
9318 // table -- a 64-length axis codes only its low 32 coefficients
9319 // (`av1_get_max_eob` / the zero-out of `av1_get_adjusted_tx_size`), so
9320 // the coded unit is the 32x32 corner [`decode_block_rect64`]'s own
9321 // depth-0 arm already reads on the key-frame path.
9322 //
9323 // lane-sub8x4 r3: WITNESS FOUND, so this is no longer behind
9324 // `EC_RECT64_SPLIT`. r1's "no witness" was true only while the
9325 // sub-8x8 intra leaves still refused: with those lifted (r2) the
9326 // first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode
9327 // all 33 frames pixel-exact against ffmpeg while this arm fires 90x
9328 // 64x32 + 5x 32x64 -- pinned as `fixtures/reelb_rect64_intra16x4_witness.obu`
9329 // and gated by `a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact`.
9330 // lane-wit16x4 r1 re-measured that fixture on the merged tip: this arm
9331 // fires 64x32=148 32x64=123 (the 90/5 above were counted out of the
9332 // frame-33 desync lane-frame36 r2 fixed), all 33 frames pixel-exact.
9333 (64, 32) | (32, 64) => None,
9334 _ => {
9335 return Err(unsupported(format!(
9336 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \
9337 coefficient tables for that shape here)"
9338 )))
9339 }
9340 };
9341 // The `None` above that is NOT the square arm.
9342 let luma_64corner = tx_w != tx_h;
9343 // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact
9344 // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole
9345 // frame exactly, two sub-16 split strips in it), but the RECT-unit arm --
9346 // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the
9347 // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the
9348 // per-unit rect walk stay wired above/below; the round that finds that
9349 // defect deletes this refusal and nothing else.
9350 let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set);
9351 let luma_scan = default_scan(tx_w.min(tx_h));
9352 let zero_tu = vec![0i32; tx_w * tx_h];
9353 // The strip's OWN edge availability, the fallback for a transform unit
9354 // whose top-right/bottom-left pixels fall outside the strip.
9355 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
9356 for tu_row in 0..bh / tx_h {
9357 for tu_col in 0..bw / tx_w {
9358 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
9359 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
9360 let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h);
9361 // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged):
9362 // libaom clips `av1_foreach_transformed_block_in_plane` to
9363 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
9364 // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose
9365 // TOP-LEFT sample falls outside the frame is never coded. We read
9366 // coefficients for those phantom units and desynced the stream at
9367 // the very next symbol.
9368 if tu_px >= y.true_width || tu_py >= y.true_height {
9369 continue;
9370 }
9371 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
9372 // transform unit INSIDE a block, which is a different rule from
9373 // the standalone-block table [`Reach::of`] applies -- and the
9374 // reason a depth-2 superblock strip came out one sample off
9375 // before this: `Reach::of(tx, ..)` answered as if the unit were
9376 // its own block at that superblock position.
9377 // * top-right: if the unit's right neighbour is still inside the
9378 // strip the pixels are already reconstructed (`col_off +
9379 // tx_wide < plane_bw`); otherwise only the strip's own top row
9380 // of units can reach past it, through the block-level answer.
9381 // * bottom-left: a unit that is not in the strip's left column
9382 // has none (`col_off > 0` returns 0); inside the strip
9383 // (`row_off + tx_high < plane_bh`) they are the left
9384 // neighbour's, already reconstructed; the last row falls back
9385 // to the block-level answer.
9386 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach);
9387 // The unit's own window on the block's palette prediction.
9388 if let Some(buf) = &m.palette_y {
9389 let tu_buf: Vec<u16> = (0..tx_h)
9390 .flat_map(|i| {
9391 let base = (row_off + i) * bw + col_off;
9392 buf[base..base + tx_w].iter().copied()
9393 })
9394 .collect();
9395 set_palette_pred(tu_buf, fctx);
9396 }
9397 if m.skip {
9398 push_intra_rect(0,
9399 tu_px,
9400 tu_py,
9401 tx_w,
9402 tx_h,
9403 m.mode,
9404 m.angle_delta_y,
9405 tu_reach,
9406 &zero_tu,
9407 None,
9408 m.filter_intra,
9409 m.smooth_neighbor, fctx,
9410 );
9411 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
9412 } else if luma_64corner && luma_rect.is_none() {
9413 // The un-split 64-level luma transform: `read_coeffs` on the
9414 // 32x32 CDF set [`TxbSet::Luma64`] with `default_scan(TX32)`
9415 // and the real rect shape passed through for
9416 // `av1_nz_map_ctx_offset` -- byte for byte
9417 // [`decode_block_rect64`]'s depth-0 read, which the key-frame
9418 // 64-level strip gate already proves. `tx_type` is not coded
9419 // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once
9420 // the square-up size is TX_64X64), and this unit covers its
9421 // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat.
9422 if crate::envflags::env_flag!("EC_RECT64TU") {
9423 eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode);
9424 }
9425 hit_do! {
9426 RECT64_CORNER_TU_HITS.with(|c| {
9427 let mut v = c.get();
9428 v[usize::from(tx_h > tx_w)] += 1;
9429 c.set(v);
9430 });
9431 }
9432 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
9433 let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra));
9434 let (corner, tu_tx_type) = read_coeffs(
9435 dec,
9436 &mut coding,
9437 default_scan(TX32),
9438 0,
9439 dc_sign_ctx(tu_around.2),
9440 TxType::DctDct,
9441 Some((tx_w, tx_h)),
9442 )?;
9443 let (cw, ch) = (tx_w.min(TX32), tx_h.min(TX32));
9444 let mut tu_grid = vec![0i32; tx_w * tx_h];
9445 for row in 0..ch {
9446 tu_grid[row * tx_w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
9447 }
9448 let residual = dequant_and_inverse_typed_wh(
9449 &tu_grid,
9450 tx_w,
9451 tx_h,
9452 crate::decode::bit_depth(fctx),
9453 block_q_idx(fctx),
9454 plane_q_delta(0, fctx).0,
9455 plane_q_delta(0, fctx).1,
9456 tu_tx_type,
9457 );
9458 push_intra_rect(0,
9459 tu_px,
9460 tu_py,
9461 tx_w,
9462 tx_h,
9463 m.mode,
9464 m.angle_delta_y,
9465 tu_reach,
9466 &residual,
9467 None,
9468 m.filter_intra,
9469 m.smooth_neighbor, fctx,
9470 );
9471 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
9472 } else if let Some((rect_set, rect_scan)) = luma_rect {
9473 // The rect-unit twin of the square arm below: same contexts,
9474 // same order, through the rect coefficient reader. The
9475 // `tx_type` CDF row of a filter-intra block is
9476 // `fimode_to_intradir[filter_intra_mode]`, never the block's
9477 // own (always DC_PRED) mode -- [`read_plane`] applies that
9478 // for the square arm, so this one must too.
9479 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
9480 // libaom `get_txb_ctx`: a LUMA transform that covers its whole
9481 // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the
9482 // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the
9483 // neighbour-magnitude table is for a unit SMALLER than its
9484 // block. [`decode_block_rect`]'s own unsplit read passes a
9485 // literal 0 for the same reason; this arm applied the table
9486 // unconditionally and desynced every depth-0 rect strip that
9487 // reached it (lane-intrarect r2: ctx 5 where aomdec read 0).
9488 let tu_skip_ctx = if tx_w == bw && tx_h == bh {
9489 0
9490 } else {
9491 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI)
9492 };
9493 let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra));
9494 let (tu_grid, tu_tx_type) = read_coeffs_rect(
9495 dec,
9496 &mut coding,
9497 rect_scan,
9498 tx_w,
9499 tx_h,
9500 tu_skip_ctx,
9501 dc_sign_ctx(tu_around.2),
9502 TxType::DctDct,
9503 )?;
9504 let residual = dequant_and_inverse_typed_wh(
9505 &tu_grid,
9506 tx_w,
9507 tx_h,
9508 crate::decode::bit_depth(fctx),
9509 block_q_idx(fctx),
9510 plane_q_delta(0, fctx).0,
9511 plane_q_delta(0, fctx).1,
9512 tu_tx_type,
9513 );
9514 push_intra_rect(0,
9515 tu_px,
9516 tu_py,
9517 tx_w,
9518 tx_h,
9519 m.mode,
9520 m.angle_delta_y,
9521 tu_reach,
9522 &residual,
9523 None,
9524 m.filter_intra,
9525 m.smooth_neighbor, fctx,
9526 );
9527 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
9528 } else {
9529 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
9530 // This unit is smaller than the block it sits in, so
9531 // `txb_skip_ctx` is the neighbour-magnitude table, not the
9532 // lone-TU 0 (spec `get_txb_ctx_general`).
9533 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
9534 let tu_grid = read_plane(
9535 dec,
9536 cdfs,
9537 luma_set,
9538 &luma_scan,
9539 0,
9540 tu_around,
9541 m.mode,
9542 m.mode,
9543 m.angle_delta_y,
9544 tu_reach,
9545 y,
9546 tu_px,
9547 tu_py,
9548 tx_w,
9549 tx_w,
9550 base_q_idx,
9551 None,
9552 m.filter_intra,
9553 Some(tu_skip_ctx),
9554 m.smooth_neighbor, fctx,
9555 )?;
9556 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
9557 }
9558 }
9559 }
9560 // CHROMA: one un-split rect transform for the whole strip.
9561 // lane-lossless2: except on a lossless frame, where it is a raster of 4x4
9562 // units -- each stamps its own neighbour context as it is read, and the
9563 // whole-block `record_split_luma_rect_mi` below would overwrite all of
9564 // them with the LAST unit's state (class `override-slot-on-one-arm`: the
9565 // next block then read `dc_sign_ctx` 1 where libaom reads 0). They are
9566 // collected here and replayed after that record.
9567 let mut ll_chroma_units: Vec<((usize, usize), usize, Grid)> = Vec::new();
9568 let ac = m.alpha.map(|_| cfl_src_rect(px, py, bw, bh));
9569 let reach = block_reach;
9570 let (u_grid, v_grid) = if m.skip {
9571 let zero = Grid::Zero(chroma_w * chroma_h);
9572 if let Some((ub, _)) = &m.palette_uv {
9573 set_palette_pred(ub.clone(), fctx);
9574 }
9575 push_intra_rect(1,
9576 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
9577 m.alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv, fctx,
9578 );
9579 if let Some((_, vb)) = &m.palette_uv {
9580 set_palette_pred(vb.clone(), fctx);
9581 }
9582 push_intra_rect(2,
9583 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
9584 m.alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv, fctx,
9585 );
9586 (zero.clone(), zero)
9587 } else if lossless(fctx) {
9588 // lane-lossless: the strip's chroma plane block is coded as 4x4
9589 // transform units too (libaom `read_tx_size` returns TX_4X4 for every
9590 // plane), PLANE-MAJOR inside the block -- U's units first, then V's
9591 // (`decode_token_recon_block`'s mu-chunk loop, measured against
9592 // aomdec's `EC_TRACE_COEFF` on a `-crf 0` stream: plane=1, plane=1,
9593 // plane=2, plane=2 for a 16x8 strip). `get_txb_ctx` adds its `+10`
9594 // offset (our `+3` row base) whenever the plane block is bigger than
9595 // the transform.
9596 let scan4 = default_scan(4);
9597 let offset = (chroma_w > 4 || chroma_h > 4).then_some(3);
9598 let (cw_n, ch_n) = (chroma_w / 4, chroma_h / 4);
9599 let mut last = [Grid::Zero(16), Grid::Zero(16)];
9600 for plane_idx in 1..=2 {
9601 for cu_row in 0..ch_n {
9602 for cu_col in 0..cw_n {
9603 let luma_span = 8;
9604 let cu_mi = (
9605 mi_r + cu_row * (luma_span / MI),
9606 mi_c + cu_col * (luma_span / MI),
9607 );
9608 let cu_around = neighbours.around_mi(cu_mi, luma_span);
9609 let cu_reach = tu_reach(
9610 bw, bh,
9611 cu_col * luma_span, cu_row * luma_span, luma_span,
9612 block_reach, px, py, y.width, y.height, fctx,
9613 );
9614 let (cu_x, cu_y) = (cpx + cu_col * 4, cpy + cu_row * 4);
9615 if let Some((ub, vb)) = &m.palette_uv {
9616 let pbuf = if plane_idx == 1 { ub } else { vb };
9617 set_palette_pred(
9618 palette_window(pbuf, chroma_w, cu_col * 4, cu_row * 4, 4, 4),
9619 fctx,
9620 );
9621 }
9622 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
9623 let grid = read_plane(
9624 dec, cdfs, TxbSet::Chroma4, &scan4, plane_idx,
9625 cu_around[plane_idx], m.mode, m.uv_predict_mode,
9626 m.angle_delta_uv, cu_reach, plane, cu_x, cu_y, 4, 4,
9627 base_q_idx,
9628 m.alpha.zip(ac).map(|((au, av), ac)| {
9629 (if plane_idx == 1 { au } else { av }, ac)
9630 }),
9631 None, offset, m.smooth_neighbor_uv, fctx,
9632 )?;
9633 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, plane_idx, &grid);
9634 ll_chroma_units.push((cu_mi, plane_idx, grid.clone()));
9635 last[plane_idx - 1] = grid;
9636 }
9637 }
9638 }
9639 let [ug, vg] = last;
9640 (ug, vg)
9641 } else {
9642 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
9643 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
9644 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
9645 // so only the 16x8/8x16 pair takes the mode-indexed default.
9646 let default_tx = if chroma_w.max(chroma_h) >= 32 {
9647 TxType::DctDct
9648 } else {
9649 default_intra_tx_type(m.uv_predict_mode as u8)
9650 };
9651 let around = neighbours.around_mi_rect(at_mi, bw, bh);
9652 let mut grids: Vec<Grid> = Vec::with_capacity(2);
9653 for plane_idx in 1..=2 {
9654 let skip_ctx =
9655 usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
9656 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
9657 let (levels, tx_type) = read_coeffs_rect(
9658 dec,
9659 &mut coding,
9660 chroma_scan,
9661 chroma_w,
9662 chroma_h,
9663 skip_ctx,
9664 dc_sign_ctx(around[plane_idx].2),
9665 default_tx,
9666 )?;
9667 // The same delta_q proof the unsplit rect64 path records
9668 // (lane-rectsplit r4: lifting the split-transform refusal moved
9669 // superblock strips onto this path, so only counting there would
9670 // leave the delta_q gate's counter silent for them).
9671 if bw.max(bh) == 64 && fctx.current_q_idx.with(|c| c.get()) != i32::from(base_q_idx) {
9672 hit!(RECT64_QIDX_DRIFT_HITS);
9673 }
9674 let residual = dequant_and_inverse_typed_wh(
9675 &levels,
9676 chroma_w,
9677 chroma_h,
9678 crate::decode::bit_depth(fctx),
9679 fctx.current_q_idx.with(|c| c.get()),
9680 plane_q_delta(plane_idx, fctx).0,
9681 plane_q_delta(plane_idx, fctx).1,
9682 tx_type,
9683 );
9684 let cfl = m
9685 .alpha
9686 .zip(ac)
9687 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
9688 let _plane = if plane_idx == 1 { &mut *u } else { &mut *v };
9689 if let Some((ub, vb)) = &m.palette_uv {
9690 let buf = if plane_idx == 1 { ub } else { vb };
9691 set_palette_pred(buf.clone(), fctx);
9692 }
9693 push_intra_rect(plane_idx,
9694 cpx,
9695 cpy,
9696 chroma_w,
9697 chroma_h,
9698 m.uv_predict_mode,
9699 m.angle_delta_uv,
9700 reach,
9701 &residual,
9702 cfl,
9703 None,
9704 m.smooth_neighbor_uv, fctx,
9705 );
9706 grids.push(levels);
9707 }
9708 let mut it = grids.into_iter();
9709 (it.next().unwrap(), it.next().unwrap())
9710 };
9711 neighbours.record_split_luma_rect_mi(
9712 at_mi,
9713 bw,
9714 bh,
9715 m.mode,
9716 m.uv_predict_mode,
9717 [&u_grid, &v_grid],
9718 );
9719 for (cu_mi, plane, unit) in &ll_chroma_units {
9720 neighbours.record_mi_chroma(*cu_mi, 8, 8, *plane, unit);
9721 }
9722 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
9723 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
9724 if crate::envflags::env_flag!("EC_AV1_TRACE") {
9725 let (rng, _) = dec.debug_state();
9726 eprintln!(
9727 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
9728 tx={tx_w}x{tx_h} rng={rng}"
9729 );
9730 }
9731 Ok(())
9732}
9733
9734/// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect
9735/// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name
9736/// because it predicts squares only. Every pixel here goes through the rect
9737/// machinery the key-frame paths already prove: [`decode_rect_split`], which
9738/// at `depth == 0` is the unsplit strip as a single transform unit and
9739/// beyond it the per-unit walk of [`depth_to_tx_wh`].
9740///
9741/// What is genuinely different from [`decode_block_rect`] is the mode
9742/// syntax: on an inter frame an intra block reads `y_mode[size_group]` and
9743/// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never
9744/// the key frame's `kf_y_mode` above/left pair. This mirrors the square
9745/// intra-in-inter arm's own reads at the rect footprint, including its
9746/// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe
9747/// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the
9748/// square and this arm) and a nonzero luma angle delta refused by name.
9749///
9750/// The strip's own neighbour records (luma per transform unit, chroma, skip
9751/// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the
9752/// inter-side bands and the mi map.
9753#[allow(clippy::too_many_arguments)]
9754/// The `(size_group_lookup, bsize_to_tx_size_cat)` row an INTRA block coded
9755/// inside an inter frame reads its `y_mode` and `tx_depth` symbols from, for
9756/// the rect footprints [`decode_intra_rect_in_inter`] resolves itself (the
9757/// 128-root halves and the 16x4/4x16 strips of a 1:4 partition take their own
9758/// branches before this). libaom `common_data.h:61` / `blockd.h:1347`: the 2:1
9759/// strips keep the group/category diagonal (BLOCK_16X8 -> 1/1, BLOCK_32X16 ->
9760/// 2/2, BLOCK_64X32 -> 3/3), the 1:4 ones break it (BLOCK_32X8 is group 1 but
9761/// category 2, BLOCK_64X16 group 2 and category 3), which is why the row is a
9762/// table here rather than a shift of `bw.min(bh)`.
9763fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> {
9764 Some(match (bw.min(bh), bw.max(bh)) {
9765 (8, 16) => (1usize, 1usize),
9766 (16, 32) => (2, 2),
9767 (32, 64) => (3, 3),
9768 (8, 32) => (1, 2),
9769 (16, 64) => (2, 3),
9770 _ => return None,
9771 })
9772}
9773
9774/// lane-t900 r20, refusal B ("an intra-coded {bw}x{bh} block on the inter
9775/// block path"): the shapes that can reach that arm, enumerated against the
9776/// MEASURED domain of the inter block path
9777/// ([`INTER_BLOCK_SHAPES`], the census the gate
9778/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`
9779/// fills from three real streams).
9780///
9781/// [`decode_intra_rect_in_inter`] is called from one site, under
9782/// `write_w != side || write_h != side`, and only after two earlier arms have
9783/// taken their shapes: a footprint with a side below 8 is either a 16x4/4x16
9784/// strip WITH a chroma-pair record (the `strip16` branch) or refused by name,
9785/// and a 128-px footprint returns from the `bw.max(bh) == 128` branch. What is
9786/// left is every rectangular census shape with `8 <= min` and `max <= 64` --
9787/// and each of those has a row, so the refusal names a shape no measured
9788/// stream can present.
9789#[test]
9790fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() {
9791 let mut checked = 0;
9792 for &(side, w, h) in &INTER_BLOCK_SHAPES {
9793 if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 {
9794 continue;
9795 }
9796 assert!(
9797 intra_in_inter_size_row(w, h).is_some(),
9798 "the inter path decodes {w}x{h} blocks, and an INTRA one of that shape would hit \
9799 the \"no size-group/tx-category row\" refusal"
9800 );
9801 checked += 1;
9802 }
9803 assert_eq!(
9804 checked, 10,
9805 "the block-shape census changed: {checked} rect shapes reach the intra-in-inter row \
9806 lookup, not the 10 this claim was measured over"
9807 );
9808}
9809
9810/// The `motion_mode` / `obmc` CDF row for a block footprint: libaom's
9811/// `motion_mode_cdf[mbmi->bsize]`, in this crate's packed row order (which
9812/// `cdf::MOTION_MODE` documents -- the 128-px rows come last, so they are
9813/// matched before the square arm's `log2` shortcut).
9814///
9815/// `None` is the refusal "a motion_mode symbol for a block shape with no CDF
9816/// row here"; the enumeration below is what proves no conformant block can
9817/// reach it.
9818pub(crate) fn motion_mode_cdf_row(write_w: usize, write_h: usize) -> Option<usize> {
9819 Some(match (write_w, write_h) {
9820 // lane-sb128c r5: the 128 root's own rows come FIRST -- the square arm
9821 // below maps 128 to row 4 (BLOCK_16X32).
9822 (64, 128) => 14,
9823 (128, 64) => 15,
9824 (128, 128) => 16,
9825 (w, h) if w == h => (w.trailing_zeros() - 3) as usize,
9826 (16, 32) => 4,
9827 (32, 16) => 5,
9828 (32, 64) => 6,
9829 (64, 32) => 7,
9830 (8, 32) => 8,
9831 (32, 8) => 9,
9832 (16, 64) => 10,
9833 (64, 16) => 11,
9834 // lane-inter4 r3: the 16x16-level rect inter leaves.
9835 (8, 16) => 12,
9836 (16, 8) => 13,
9837 _ => return None,
9838 })
9839}
9840
9841/// Every `BLOCK_SIZES_ALL` footprint, as `(width, height)` in pixels: the six
9842/// squares, the ten 2:1 shapes and the six 1:4 ones (libaom `common_data.h`,
9843/// `block_size_wide`/`block_size_high`).
9844#[cfg(test)]
9845const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [
9846 (4, 4),
9847 (4, 8),
9848 (8, 4),
9849 (8, 8),
9850 (8, 16),
9851 (16, 8),
9852 (16, 16),
9853 (16, 32),
9854 (32, 16),
9855 (32, 32),
9856 (32, 64),
9857 (64, 32),
9858 (64, 64),
9859 (64, 128),
9860 (128, 64),
9861 (128, 128),
9862 (4, 16),
9863 (16, 4),
9864 (8, 32),
9865 (32, 8),
9866 (16, 64),
9867 (64, 16),
9868];
9869
9870/// lane-t900 r25, enumeration: the refusal "a motion_mode symbol for a block
9871/// shape with no CDF row here" names a shape no conformant stream can present.
9872///
9873/// A `motion_mode`/`obmc` symbol is read only under `motion_mode_eligible`,
9874/// whose `write_w.min(write_h) >= 8` clause is libaom's
9875/// `is_motion_variation_allowed_bsize` (`blockd.h:1455`). So the reachable
9876/// domain of [`motion_mode_cdf_row`] is exactly the `BLOCK_SIZES_ALL`
9877/// footprints with `min(bw, bh) >= 8` -- 17 of the 22 -- and each of those
9878/// must map to a distinct row of the 17-row `Cdfs::motion_mode` table. The
9879/// five it excludes (4x4, 4x8, 8x4, 4x16, 16x4) are the ones the eligibility
9880/// clause rejects before the lookup.
9881#[test]
9882fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() {
9883 let mut rows = std::collections::BTreeSet::new();
9884 let mut excluded = 0;
9885 for (w, h) in BLOCK_SIZES_ALL_WH {
9886 if w.min(h) < 8 {
9887 excluded += 1;
9888 assert!(
9889 w == 4 || h == 4,
9890 "{w}x{h} is not one of the sub-8 shapes is_motion_variation_allowed_bsize rejects"
9891 );
9892 continue;
9893 }
9894 let row = motion_mode_cdf_row(w, h).unwrap_or_else(|| {
9895 panic!(
9896 "a {w}x{h} block passes is_motion_variation_allowed_bsize and reads a motion_mode \
9897 symbol, but has no CDF row -- the refusal is a real gap, not a dead arm"
9898 )
9899 });
9900 assert!(
9901 row < 17,
9902 "{w}x{h} maps to motion_mode row {row}, outside the 17-row table"
9903 );
9904 assert!(rows.insert(row), "{w}x{h} shares motion_mode row {row}");
9905 }
9906 assert_eq!(excluded, 5, "the sub-8 footprint set changed");
9907 assert_eq!(
9908 rows.len(),
9909 17,
9910 "17 eligible footprints must fill all 17 rows of the motion_mode table"
9911 );
9912}
9913
9914fn decode_intra_rect_in_inter(
9915 dec: &mut SymbolDecoder,
9916 cdfs: &mut Cdfs,
9917 neighbours: &mut Neighbours,
9918 at: (usize, usize),
9919 bw: usize,
9920 bh: usize,
9921 skip: bool,
9922 allow_screen_content_tools: bool,
9923 // `(PARTITION_HORZ_4, is_chroma_reference)` when this strip is one of the
9924 // four 16x4 / 4x16 strips of a 16x16-level 1:4 partition (lane-intra16x4).
9925 strip16: Option<(bool, bool)>,
9926 y: &mut PlaneBuf<'static>,
9927 u: &mut PlaneBuf<'static>,
9928 v: &mut PlaneBuf<'static>,
9929 base_q_idx: u8, fctx: &crate::decode::FrameCtx,
9930) -> Result<()> {
9931 // `at` is in MI units (the inter path's own unit since lane-inter4);
9932 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands
9933 // below are still keyed by.
9934 let (mi_r, mi_c) = at;
9935 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
9936 // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat`
9937 // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 /
9938 // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx
9939 // finding -- the category is NOT the same for every strip size).
9940 // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so
9941 // it is refused by name rather than read from the wrong CDF row.
9942 // lane-intra16x4: the 16x16-level 1:4 strip. `size_group_lookup`
9943 // (common_data.h:61) puts BLOCK_16X4/BLOCK_4X16 in group 0 and its
9944 // tx-depth category is 1 -- but nothing here has to know either, because
9945 // the strip decodes through the very body the KEY FRAME path proves for
9946 // this shape ([`decode_rect4_16_strip`]), including the 4:2:0 chroma
9947 // pairing (`is_chroma_reference`: strips 0 and 2 read no chroma at all,
9948 // strips 1 and 3 code one 8x4 (4x8) unit at the PAIR's origin). The only
9949 // inter-frame difference is the mode-info read, which
9950 // [`INTRA_IN_INTER_MODE`] switches to `read_intra_block_mode_info`'s
9951 // `y_mode[0]` plus the `skip` this caller already read.
9952 if let Some((horz, has_chroma)) = strip16 {
9953 // lane-t900 r22: the screen-content refusal here was STALE (class
9954 // stale-premise): [`decode_rect4_16_strip`] takes
9955 // `allow_screen_content_tools` and reads the whole palette syntax
9956 // (mode/size/colours/colour-index map, its own `palette_ctx_and_cache_mi`
9957 // pair) -- the key frame proves that body. Lifted with the 10-bit
9958 // witness `palette_screen_witness_10bit.obu`, whose inter frames carry
9959 // 16x4/4x16 intra strips inside a `--tune-content=screen` frame.
9960 debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) });
9961 fctx.intra_in_inter_mode.with(|c| c.set(Some((0, skip))));
9962 let res = decode_rect4_16_strip(
9963 dec,
9964 cdfs,
9965 neighbours,
9966 (mi_r, mi_c),
9967 horz,
9968 has_chroma,
9969 // The inter strips of the same partition publish their own
9970 // mi-exact mode, so the key-frame caller's coarse-cell stand-in
9971 // has nothing to add here.
9972 None,
9973 y,
9974 u,
9975 v,
9976 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
9977 allow_screen_content_tools,
9978 base_q_idx,
9979 fctx.tx_select_inter.with(std::cell::Cell::get),
9980 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
9981 );
9982 fctx.intra_in_inter_mode.with(|c| c.set(None));
9983 let (mode, uv, (tx_w, tx_h)) = res?;
9984 // lane-intra16x4, the same publication the 2:1 intra-in-inter strip
9985 // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs
9986 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` for EVERY
9987 // block of an inter frame, intra ones included, and
9988 // `txfm_partition_update` for the var-tx context. The key-frame body
9989 // writes neither (a key frame has no var-tx tree and its own readers
9990 // use the deblock grid), so the block AFTER this strip read a stale
9991 // band -- measured: a 128x128 8-bit stream decoded the two intra 16x4
9992 // strips at mi(23,16)/(23,20) exactly and then broke on the very next
9993 // 16x16 row.
9994 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
9995 for i in 0..bw / MI {
9996 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
9997 *cell = tx_w as u8;
9998 }
9999 }
10000 for i in 0..bh / MI {
10001 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
10002 *cell = tx_h as u8;
10003 }
10004 }
10005 // [`decode_rect4_16`]'s own post-loop publication, per strip (the
10006 // coarse 16-px cell holds one entry for the whole 16x16 and the last
10007 // block to write it wins).
10008 neighbours.above_mode[c] = mode;
10009 neighbours.left_mode[r] = mode;
10010 if let Some(uvm) = uv {
10011 neighbours.above_uv_mode[c] = uvm;
10012 neighbours.left_uv_mode[r] = uvm;
10013 }
10014 neighbours.above_side[c] = bw;
10015 neighbours.left_side[r] = bh;
10016 if crate::envflags::env_flag!("EC_INTRA16X4") {
10017 eprintln!(
10018 "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}",
10019 mi_c * MI,
10020 mi_r * MI
10021 );
10022 }
10023 hit_do! {
10024 INTRA16X4_IN_INTER_HITS.with(|h| {
10025 let mut v = h.get();
10026 v[usize::from(!horz)] += 1;
10027 v[2] += usize::from(has_chroma);
10028 h.set(v);
10029 });
10030 }
10031 return Ok(());
10032 }
10033 // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half
10034 // coded INTRA inside an inter frame. `size_group_lookup` (common_data.h:61)
10035 // puts BLOCK_128X64/64X128/128X128 in group 3 and
10036 // `max_txsize_rect_lookup` caps them at TX_64X64, i.e. the same
10037 // `tx_size_cat3` row [`decode_block_128rect`] already reads -- so the whole
10038 // block decodes through the very body the KEY FRAME path proves for this
10039 // shape (square 64x64 luma units, one TX_32X32 chroma unit per 64x64 mu
10040 // chunk on the offset-10 txb_skip rows, per-TU prediction, the mu-chunk
10041 // `Reach` rule and the frame-edge write clip). The only inter-frame
10042 // differences live inside that body: the mode-info read
10043 // ([`INTRA_IN_INTER_MODE`] -> `y_mode[3]` plus the `skip` this caller
10044 // already read), the `tx_depth` context (the real TXFM_CONTEXT bands) and
10045 // the `set_txfm_ctxs` publication. CfL (>32), filter intra (>32) and
10046 // palette (>64) do not exist at this size and are refused by name there.
10047 // lane-t900 r18: the opt-in is LIFTED -- the arm has a witness.
10048 // `intra128_in_inter_witness2.obu` (gate
10049 // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`)
10050 // fires it 3x 128x64 + 6x 64x128 and decodes byte-exact on every plane of
10051 // all 15 frames, so the hits are counted out of exact frames (class
10052 // `counter-from-refused-stream`). What r16/r17 could not find, and what
10053 // that recipe exploits: libaom's RD essentially never PICKS a 128-root
10054 // HORZ/VERT in the interior -- the 512x512 r16 witness and a textured
10055 // 640x384 sweep code 128 roots as NONE or SPLIT only. The shape appears
10056 // where the frame EDGE forces it: a partial last superblock row has
10057 // `has_rows128 == false`, so the 128x64 top half is implied, and a
10058 // partial last column implies the 64x128 left half. Put content no
10059 // reference holds (a fresh smooth ramp) in exactly those two bands of an
10060 // inter frame and the encoder codes those forced halves INTRA.
10061 if bw.max(bh) == 128 {
10062 // lane-t900 r32: no screen-content refusal here. `av1_allow_palette`
10063 // rejects every footprint with a 128-pixel side (`bw > 64 || bh > 64`,
10064 // enumerated by `no_block_footprint_with_a_128_pixel_side_can_carry_\
10065 // palette_syntax`), so a 128-root half consumes no palette syntax and
10066 // a screen-content frame's half is syntactically identical to the
10067 // non-screen one this arm already decodes byte-exact.
10068 if coeff_trace_on() {
10069 // lane-t900 r16: which decode-order frame this arm fires in --
10070 // interleaved with the `EC_COEFF_FRAME` markers, this is what
10071 // proves the hit is counted out of a frame that compares exact
10072 // (class `counter-from-refused-stream`).
10073 eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}");
10074 }
10075 fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip))));
10076 let res = decode_block_128rect(
10077 dec,
10078 cdfs,
10079 neighbours,
10080 (r, c),
10081 bw,
10082 bh,
10083 y,
10084 u,
10085 v,
10086 base_q_idx,
10087 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
10088 allow_screen_content_tools,
10089 fctx.tx_select_inter.with(std::cell::Cell::get),
10090 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
10091 );
10092 fctx.intra_in_inter_mode.with(|c| c.set(None));
10093 return res;
10094 }
10095 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {
10096 if crate::envflags::env_flag!("EC_OBMCREC") {
10097 eprintln!(
10098 "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}"
10099 );
10100 }
10101 // lane-obmcrec r1: the message used to name a 16x4/4x16 strip
10102 // (class refusal-names-a-correlate). lane-t900 r20: the shapes that
10103 // can arrive here are enumerated against the measured block-shape
10104 // census ([`INTER_BLOCK_SHAPES`]) by
10105 // [`every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`]
10106 // -- every one of them has a row, so this arm names a shape no stream
10107 // has been able to present.
10108 return Err(unsupported(format!(
10109 "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"
10110 )));
10111 };
10112 // lane-t900 r21: this arm used to refuse EVERY rect strip of a
10113 // screen-content frame ("palette syntax is consumed for square blocks
10114 // only"). It is not: [`read_intra_mode_rect`] generalised the palette read
10115 // to rect blocks on the key-frame path, and the 1:4 arm below goes through
10116 // it, while the 2:1 reader inlined further down now codes the same syntax
10117 // itself. A real `--tune-content=screen` inter stream reached this refusal
10118 // on 8x16 / 16x8 strips (gate
10119 // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`).
10120 // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY
10121 // FRAME path already proves for this shape ([`decode_block_rect4`] at the
10122 // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4
10123 // luma/chroma transform tables, the per-unit split walk and the strip's
10124 // own neighbour records). The ONLY difference on an inter frame is the
10125 // mode-info read, which [`INTRA_IN_INTER_MODE`] switches to
10126 // `read_intra_block_mode_info`'s `y_mode[size_group]` plus the `skip`
10127 // this caller already read. `tx_cat` above is the same category those
10128 // readers hardcode (cat 2 in `decode_block_rect4`, cat 3 in
10129 // `decode_block_rect64`), asserted here so a future shape cannot drift.
10130 if bw.max(bh) == 4 * bw.min(bh) {
10131 debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 });
10132 fctx.intra_in_inter_mode.with(|c| c.set(Some((size_group, skip))));
10133 let res = if bw.max(bh) == 64 {
10134 decode_block_rect64(
10135 dec,
10136 cdfs,
10137 neighbours,
10138 (mi_r / (SUB / MI), mi_c / (SUB / MI)),
10139 bw,
10140 bh,
10141 y,
10142 u,
10143 v,
10144 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
10145 allow_screen_content_tools,
10146 base_q_idx,
10147 fctx.tx_select_inter.with(std::cell::Cell::get),
10148 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
10149 )
10150 } else {
10151 decode_block_rect4(
10152 dec,
10153 cdfs,
10154 neighbours,
10155 (mi_r, mi_c),
10156 bw,
10157 bh,
10158 None,
10159 y,
10160 u,
10161 v,
10162 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
10163 allow_screen_content_tools,
10164 base_q_idx,
10165 fctx.tx_select_inter.with(std::cell::Cell::get), fctx,
10166 )
10167 .map(|_| ())
10168 };
10169 fctx.intra_in_inter_mode.with(|c| c.set(None));
10170 res?;
10171 let shape = match (bw, bh) {
10172 (64, 16) => 0,
10173 (16, 64) => 1,
10174 (32, 8) => 2,
10175 _ => 3,
10176 };
10177 hit_do! {
10178 INTRA_RECT4_IN_INTER_HITS.with(|h| {
10179 let mut v = h.get();
10180 v[shape] += 1;
10181 h.set(v);
10182 });
10183 }
10184 return Ok(());
10185 }
10186 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
10187 // lane-t900 r1: this arm read six mode symbols with no ladder rung of its
10188 // own, so a cross-decoder bisection could only see the block's first
10189 // coefficient. Same names/format as [`read_tx_size`]'s rung.
10190 let step_trace = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
10191 if step_trace {
10192 eprintln!(
10193 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}",
10194 dec.debug_state().0
10195 );
10196 }
10197 if mode >= 13 {
10198 return Err(unsupported(
10199 "an intra mode this decoder does not code (round 2)",
10200 ));
10201 }
10202 // lane-angleinter (merged on main for the square intra-in-inter arm):
10203 // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the
10204 // directional predictor; this arm refused a nonzero one before the merge.
10205 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
10206 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
10207 } else {
10208 0
10209 };
10210 if angle_delta_y != 0 {
10211 hit!(INTRA_IN_INTER_ANGLE_DELTA_Y_HITS);
10212 }
10213 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
10214 // superblock-level strip reads the no-CFL alphabet -- the same split
10215 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
10216 let cfl_allowed = cfl_allowed_px(bw, bh, fctx);
10217 let uv_mode = if cfl_allowed {
10218 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
10219 } else {
10220 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
10221 };
10222 if step_trace {
10223 eprintln!(
10224 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}",
10225 u8::from(cfl_allowed),
10226 dec.debug_state().0
10227 );
10228 }
10229 if (9..=12).contains(&uv_mode) {
10230 hit!(SMOOTH_UV_HITS);
10231 }
10232 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
10233 Some(read_cfl_alphas(dec, cdfs))
10234 } else {
10235 None
10236 };
10237 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
10238 DC_PRED
10239 } else {
10240 uv_mode
10241 };
10242 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
10243 hit!(DIRECTIONAL_UV_HITS);
10244 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
10245 } else {
10246 0
10247 };
10248 if angle_delta_uv != 0 {
10249 hit!(UV_ANGLE_DELTA_HITS);
10250 hit!(INTRA_IN_INTER_ANGLE_DELTA_UV_HITS);
10251 }
10252 // `read_palette_mode_info` (spec 5.11.13), in the position
10253 // `read_intra_block_mode_info` writes it: after the chroma mode and
10254 // before `filter_intra`. lane-t900 r21: a `--tune-content=screen` inter
10255 // frame writes `palette_y_mode`/`palette_uv_mode` for every block whose
10256 // shape [`palette_bsize_ctx_wh`] admits, intra strips included, so
10257 // skipping the syntax here desynced the tile at the strip's own symbol.
10258 // lane-t900 r22: reconstructed, not refused -- the strip's real mode
10259 // context and colour cache at its own mi position, and the two
10260 // colour-index maps decoded after `filter_intra` (`av1_visit_palette`),
10261 // exactly as [`read_intra_mode_rect`] does on the key-frame path.
10262 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi((mi_r, mi_c));
10263 let palette_uv_cache = neighbours.palette_uv_cache_mi((mi_r, mi_c));
10264 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
10265 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
10266 if allow_screen_content_tools
10267 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
10268 {
10269 hit!(INTRA_RECT_IN_INTER_SCREEN_HITS);
10270 let use_palette_y =
10271 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0;
10272 if use_palette_y {
10273 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
10274 palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx)));
10275 }
10276 // A 2:1 strip of at least 8x8 is always a chroma reference, so
10277 // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here.
10278 let use_palette_uv =
10279 uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
10280 if crate::envflags::env_flag!("EC_PALSYN") {
10281 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);
10282 }
10283 if use_palette_uv {
10284 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
10285 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);
10286 palette_uv_pending = Some((n, u_colors, v_colors));
10287 }
10288 }
10289 // lane-fiinter (merged on main for the square intra-in-inter arm):
10290 // `read_filter_intra_mode_info` is the tail of
10291 // `read_intra_block_mode_info`, after the palette syntax (refused whole
10292 // above for this shape), and `av1_filter_intra_allowed_bsize` admits the
10293 // 2:1 strips with both sides <= 32 -- their own CDF rows
10294 // ([`filter_intra_size_class_rect`]).
10295 let mut filter_intra = None;
10296 if mode == DC_PRED
10297 && fctx.enable_filter_intra_inter.with(std::cell::Cell::get)
10298 // `av1_filter_intra_allowed` excludes a palette-Y block.
10299 && palette_y_pending.is_none()
10300 && let Some(class) = filter_intra_size_class_rect(bw, bh)
10301 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
10302 {
10303 hit!(FILTER_INTRA_HITS);
10304 hit!(INTRA_IN_INTER_FILTER_INTRA_HITS);
10305 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
10306 }
10307 // `av1_visit_palette`: Y's colour-index map then the shared chroma one.
10308 let palette_y = palette_y_pending.map(|(n, colors)| {
10309 let map = decode_color_index_map_wh(dec, cdfs, n, bw, bh, false);
10310 hit!(PALETTE_HITS);
10311 hit!(PALETTE_RECT_HITS);
10312 hit!(INTRA_IN_INTER_PALETTE_Y_HITS);
10313 PaletteY { size: n, colors, map }
10314 });
10315 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
10316 let (cw, ch) = ((bw / 2).max(4), (bh / 2).max(4));
10317 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, true);
10318 hit!(PALETTE_UV_HITS);
10319 hit!(INTRA_IN_INTER_PALETTE_UV_HITS);
10320 PaletteUv { size: n, u_colors, v_colors, map }
10321 });
10322 // The intra-edge filter type is the NEIGHBOUR's mode (libaom
10323 // `get_filt_type`), luma's off the luma neighbours and chroma's off the
10324 // chroma ones -- [`decode_block_rect`]'s own pair.
10325 // lane-t900 r4: the coarse pair is keyed on the 16x16 cell's OWN top-left
10326 // mi, so both 8x16 halves of a VERT split read the neighbours of the FIRST
10327 // half. libaom's `above_mbmi`/`left_mbmi` are this block's own
10328 // (`mi[-mi_stride]` / `mi[-1]`) -- take the mi-exact pair over the coarse
10329 // one exactly as [`decode_leaf8`] already does (class
10330 // context-read-from-one-cell).
10331 let coarse_pair = neighbours.modes_above_left(r, c);
10332 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, coarse_pair);
10333 if (nb_above_mode, nb_left_mode) != coarse_pair {
10334 hit!(EDGE_FILTER_MI_FIX_HITS);
10335 }
10336 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
10337 if smooth_neighbor {
10338 hit!(SMOOTH_LUMA_HITS);
10339 }
10340 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
10341 let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) {
10342 // The INTER frame's own `TXFM_CONTEXT` bands, not the key frame's
10343 // deblock-grid approximation -- [`tx_size_context_txfm_rect`].
10344 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
10345 let d = match tx_cat {
10346 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
10347 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
10348 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
10349 };
10350 if step_trace {
10351 eprintln!(
10352 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}",
10353 dec.debug_state().0
10354 );
10355 }
10356 d
10357 } else {
10358 0
10359 };
10360 if depth != 0 || lossless(fctx) {
10361 hit!(TX_DEPTH_HITS);
10362 // lane-intrasplit r1: a split intra strip in an inter frame walks the
10363 // key frame's own per-TU path ([`decode_rect_split`] below); what was
10364 // wrong when this refusal was written was the depth SYMBOL, not the walk.
10365 hit_do! {
10366 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(|h| {
10367 let mut v = h.get();
10368 v[depth.min(2)] += 1;
10369 h.set(v);
10370 });
10371 }
10372 }
10373 // lane-intrasplit r3: print EVERY intra strip with its depth, not only the
10374 // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and
10375 // the two are indistinguishable when the diagnostic fires on splits alone.
10376 if crate::envflags::env_flag!("EC_SPLITSTRIP") {
10377 eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}");
10378 }
10379 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
10380 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,
10381 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block
10382 // of an inter frame, intra ones included -- with the skip term 0 it
10383 // memsets `above_txfm_context` to `tx_size_wide` over the block's width
10384 // and `left_txfm_context` to `tx_size_high` over its height. This strip
10385 // wrote neither, so the next block's var-tx `txfm_partition` context read
10386 // a stale band: on a 192x128 8-bit stream the 16x8 intra strip at
10387 // mi(14,0) left 8 where libaom has 16, giving ctx 13 instead of 12 at
10388 // mi(16,0) and desyncing the tile at that symbol.
10389 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
10390 let modes = RectStripModes {
10391 skip,
10392 mode,
10393 angle_delta_y,
10394 uv_predict_mode,
10395 angle_delta_uv,
10396 alpha,
10397 filter_intra,
10398 smooth_neighbor,
10399 smooth_neighbor_uv,
10400 palette_y: palette_y
10401 .as_ref()
10402 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
10403 palette_uv: palette_uv.as_ref().map(|p| {
10404 (
10405 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
10406 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
10407 )
10408 }),
10409 };
10410 decode_rect_split(
10411 dec,
10412 cdfs,
10413 neighbours,
10414 (mi_r, mi_c),
10415 bw,
10416 bh,
10417 tx_w,
10418 tx_h,
10419 &modes,
10420 y,
10421 u,
10422 v,
10423 base_q_idx,
10424 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
10425 )?;
10426 // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of
10427 // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in
10428 // both `TXFM_CONTEXT` bands -- the above row over the block's width, the
10429 // left column over its height. This arm wrote neither before lane-intrasplit
10430 // r1, so every later block in the frame read a stale `tx_size`/`txfm_split`
10431 // context across the strip's footprint.
10432 for i in 0..bw / MI {
10433 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
10434 *cell = tx_w as u8;
10435 }
10436 }
10437 for i in 0..bh / MI {
10438 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
10439 *cell = tx_h as u8;
10440 }
10441 }
10442 // The strip's own palette state into the mi-granular neighbour bands, so
10443 // the next block's colour cache and `palette_y_mode` context are libaom's.
10444 record_strip_palette(
10445 neighbours,
10446 (mi_r, mi_c),
10447 bw,
10448 bh,
10449 palette_y.as_ref().map_or(0, |p| p.size),
10450 palette_y.as_ref().map_or([0u16; 8], |p| p.colors),
10451 palette_uv.as_ref().map_or(0, |p| p.size),
10452 palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors),
10453 );
10454 let class = match bw.max(bh) {
10455 64 => 0,
10456 32 => 1,
10457 _ => 2,
10458 };
10459 hit_do! {
10460 INTRA_RECT_IN_INTER_HITS.with(|h| {
10461 let mut v = h.get();
10462 v[class] += 1;
10463 h.set(v);
10464 });
10465 }
10466 Ok(())
10467}
10468
10469/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
10470/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
10471/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
10472/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
10473/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
10474/// has no rectangular-transform coefficient reader, and a chroma plane here
10475/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
10476/// with no depth-based square-tiling escape the way luma's own resolved
10477/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
10478/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
10479#[allow(clippy::too_many_arguments)]
10480fn decode_block_rect(
10481 dec: &mut SymbolDecoder,
10482 cdfs: &mut Cdfs,
10483 neighbours: &mut Neighbours,
10484 at: (usize, usize),
10485 bw: usize,
10486 bh: usize,
10487 y: &mut PlaneBuf<'static>,
10488 u: &mut PlaneBuf<'static>,
10489 v: &mut PlaneBuf<'static>,
10490 enable_filter_intra: bool,
10491 allow_screen_content_tools: bool,
10492 base_q_idx: u8,
10493 tx_select: bool,
10494 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
10495) -> Result<()> {
10496 let (r, c) = at;
10497 let (px, py) = (c * SUB, r * SUB);
10498 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
10499 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
10500 let palette_uv_cache = neighbours.palette_uv_cache(at);
10501 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
10502 read_intra_mode_rect(
10503 dec,
10504 cdfs,
10505 nb_above_mode,
10506 nb_left_mode,
10507 true,
10508 true,
10509 bw,
10510 bh,
10511 enable_filter_intra,
10512 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
10513 allow_screen_content_tools,
10514 Some((palette_ctx, &palette_cache)),
10515 &palette_uv_cache,
10516 r * (SUB / MI),
10517 c * (SUB / MI), fctx,
10518 )?;
10519 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
10520 if smooth_neighbor {
10521 hit!(SMOOTH_LUMA_HITS);
10522 }
10523 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
10524 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
10525 // `uv_mode`, not the luma one.
10526 let smooth_neighbor_uv =
10527 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
10528 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
10529 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
10530 // rectangle just as happily), so a `use_filter_intra` strip at this level
10531 // predicts instead of refusing. The below-16x16 leaf arm
10532 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
10533 if filter_intra.is_some() {
10534 hit!(FILTER_INTRA_RECT_HITS);
10535 }
10536 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
10537 DC_PRED
10538 } else {
10539 uv_mode
10540 };
10541 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
10542 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
10543 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
10544 // one did not, so with `--enable-tx-size-search=0` -- which several gate
10545 // recipes use -- the decoder consumed a symbol the encoder never wrote and
10546 // desynced the tile from that point on. That is why both strips of the
10547 // pinned HORZ quadrant were wrong from their very first pixel, and why our
10548 // range after the read equalled the oracle's range for the whole block.
10549 let depth = if tx_select {
10550 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
10551 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
10552 // the 16x4 intra-in-inter strips already do); the key frame's
10553 // deblock-grid approximation is only right where those bands were never
10554 // written. Measured on the 10-bit 1920x792 128-superblock stream,
10555 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
10556 // `tx_size_cat2` row 1 where libaom reads row 2.
10557 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
10558 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
10559 } else {
10560 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
10561 };
10562 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
10563 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
10564 eprintln!(
10565 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
10566 dec.debug_state().0
10567 );
10568 }
10569 d
10570 } else {
10571 0
10572 };
10573 if depth != 0 || lossless(fctx) {
10574 hit!(TX_DEPTH_HITS);
10575 // lane-rectsplit r1: a split transform is predicted and reconstructed
10576 // per transform unit, each unit taking its edges from the previous
10577 // unit's reconstruction inside this same strip (spec 5.11.36) --
10578 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
10579 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
10580 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
10581 eprintln!(
10582 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
10583 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
10584 angle_y={angle_delta_y}"
10585 );
10586 }
10587 let modes = RectStripModes {
10588 skip,
10589 mode,
10590 angle_delta_y,
10591 uv_predict_mode,
10592 angle_delta_uv,
10593 alpha,
10594 filter_intra,
10595 smooth_neighbor,
10596 smooth_neighbor_uv,
10597 palette_y: palette_y
10598 .as_ref()
10599 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
10600 palette_uv: palette_uv.as_ref().map(|p| {
10601 (
10602 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
10603 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
10604 )
10605 }),
10606 };
10607 if palette_y.is_some() || palette_uv.is_some() {
10608 hit!(PALETTE_SPLIT_TX_HITS);
10609 }
10610 decode_rect_split(
10611 dec,
10612 cdfs,
10613 neighbours,
10614 (mi_r, mi_c),
10615 bw,
10616 bh,
10617 tx_w,
10618 tx_h,
10619 &modes,
10620 y,
10621 u,
10622 v,
10623 base_q_idx,
10624 reduced_tx_set, fctx,
10625 )?;
10626 // This early return skips this fn's own tail, so the palette
10627 // neighbour state has to be stamped HERE too: without it a split-tx
10628 // strip left the above/left palette arrays holding a DEAD block's
10629 // colours, and the next block's colour cache
10630 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
10631 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
10632 // and only those pixels were wrong (lane-palette2 r10).
10633 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
10634 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
10635 let (puv_size, puv_colors) =
10636 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
10637 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
10638 hit!(RECT_PARTITION_HITS);
10639 return Ok(());
10640 }
10641 let (tx_w, tx_h) = (bw, bh);
10642 let (cpx, cpy) = (px / 2, py / 2);
10643 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
10644 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
10645 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10646 let (rng, _) = dec.debug_state();
10647 eprintln!(
10648 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
10649 skip={} tx={depth} rng={rng}",
10650 skip as i32
10651 );
10652 }
10653 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
10654 // block's prediction is the reconstructed colour-index map, set fresh
10655 // right before each `reconstruct_rect` call below (lane-palette2 r4).
10656 if let Some(ref pyv) = palette_y {
10657 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
10658 set_palette_pred(buf, fctx);
10659 }
10660 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
10661 (
10662 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
10663 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
10664 )
10665 });
10666 if skip {
10667 push_intra_rect(0,
10668 px,
10669 py,
10670 bw,
10671 bh,
10672 mode,
10673 angle_delta_y,
10674 reach,
10675 &ZERO_RESIDUAL[..bw * bh],
10676 None,
10677 filter_intra,
10678 smooth_neighbor, fctx,
10679 );
10680 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
10681 if let Some((ub, _)) = &palette_uv_bufs {
10682 set_palette_pred(ub.clone(), fctx);
10683 }
10684 push_intra_rect(1,
10685 cpx,
10686 cpy,
10687 chroma_w,
10688 chroma_h,
10689 uv_predict_mode,
10690 angle_delta_uv,
10691 reach,
10692 &ZERO_RESIDUAL[..chroma_w * chroma_h],
10693 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
10694 None,
10695 smooth_neighbor_uv, fctx,
10696 );
10697 if let Some((_, vb)) = &palette_uv_bufs {
10698 set_palette_pred(vb.clone(), fctx);
10699 }
10700 push_intra_rect(2,
10701 cpx,
10702 cpy,
10703 chroma_w,
10704 chroma_h,
10705 uv_predict_mode,
10706 angle_delta_uv,
10707 reach,
10708 &ZERO_RESIDUAL[..chroma_w * chroma_h],
10709 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
10710 None,
10711 smooth_neighbor_uv, fctx,
10712 );
10713 neighbours.record_rect(
10714 at,
10715 bw,
10716 bh,
10717 mode,
10718 uv_predict_mode,
10719 &[
10720 &ZERO_RESIDUAL[..bw * bh],
10721 &ZERO_RESIDUAL[..chroma_w * chroma_h],
10722 &ZERO_RESIDUAL[..chroma_w * chroma_h],
10723 ],
10724 );
10725 } else {
10726 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
10727 // reduces both size pairs to their square-up CDF sets
10728 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
10729 // doc comments); the scan order and 2D context tables are the real
10730 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
10731 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 32 {
10732 (&SCAN_32X16, &SCAN_16X8)
10733 } else {
10734 (&SCAN_16X32, &SCAN_8X16)
10735 };
10736 // lane-rectwire r3: real coefficients desync a pixel-exact gate
10737 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
10738 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
10739 // pixel (not a subtle context-table off-by-one), while the sibling
10740 // non-rect quadrants of the same frame match. Range-ladder bisection
10741 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
10742 // but the intra key-frame path has no traced symbol between the
10743 // partition read and the first coefficient block (mode/skip/tx_depth
10744 // reads are all untraced in libaom's decodeframe.c intra path, unlike
10745 // the inter EC_TRACE_MODE this round added), so a same-length range
10746 // comparison wasn't reachable within budget -- see
10747 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
10748 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
10749 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
10750 // libaom and match). lane-rectwire r4: range-ladder against the
10751 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
10752 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
10753 // both confirmed in sync -- rng=58692 on both sides right after
10754 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
10755 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
10756 // immediately after: ours moves rng 58692 -> 43570, which cannot be
10757 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
10758 // its own tx_size read) unless oracle's tx symbol is a near-certainty
10759 // CDF that barely narrows the range -- i.e. this decoder's
10760 // `tx_size_context_rect` ctx or `cdfs.tx_size_cat2` CDF selection for
10761 // a 32x16/16x32 strip is the first diverging symbol, not the
10762 // coefficient-context math r3 already cleared. Not confirmed byte-
10763 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
10764 // `read_tx_size`'s own rng, not attempted this round -- budget), so
10765 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
10766 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
10767 // it unconditionally where both square paths gate on `tx_select`. With
10768 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
10769 // decoder consumed one that was never there.
10770 {
10771 let around = neighbours.around_rect(at, bw, bh);
10772 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
10773 let (luma_levels, luma_tx_type) = read_coeffs_rect(
10774 dec,
10775 &mut luma_coding,
10776 luma_scan,
10777 bw,
10778 bh,
10779 0,
10780 dc_sign_ctx(around[0].2),
10781 TxType::DctDct,
10782 )?;
10783 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10784 let (rng, _) = dec.debug_state();
10785 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
10786 }
10787 let luma_residual = dequant_and_inverse_typed_wh(
10788 &luma_levels,
10789 bw,
10790 bh,
10791 crate::decode::bit_depth(fctx),
10792 block_q_idx(fctx),
10793 plane_q_delta(0, fctx).0,
10794 plane_q_delta(0, fctx).1,
10795 luma_tx_type,
10796 );
10797 push_intra_rect(0,
10798 px,
10799 py,
10800 bw,
10801 bh,
10802 mode,
10803 angle_delta_y,
10804 reach,
10805 &luma_residual,
10806 None,
10807 filter_intra,
10808 smooth_neighbor, fctx,
10809 );
10810 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
10811 if let Some((ub, _)) = &palette_uv_bufs {
10812 set_palette_pred(ub.clone(), fctx);
10813 }
10814 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
10815 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
10816 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
10817 let (u_levels, u_tx_type) = read_coeffs_rect(
10818 dec,
10819 &mut u_coding,
10820 chroma_scan,
10821 chroma_w,
10822 chroma_h,
10823 u_skip_ctx,
10824 dc_sign_ctx(around[1].2),
10825 u_default_tx,
10826 )?;
10827 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10828 let (rng, _) = dec.debug_state();
10829 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
10830 }
10831 let u_residual = dequant_and_inverse_typed_wh(
10832 &u_levels,
10833 chroma_w,
10834 chroma_h,
10835 crate::decode::bit_depth(fctx),
10836 block_q_idx(fctx),
10837 plane_q_delta(1, fctx).0,
10838 plane_q_delta(1, fctx).1,
10839 u_tx_type,
10840 );
10841 push_intra_rect(1,
10842 cpx,
10843 cpy,
10844 chroma_w,
10845 chroma_h,
10846 uv_predict_mode,
10847 angle_delta_uv,
10848 reach,
10849 &u_residual,
10850 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
10851 None,
10852 smooth_neighbor_uv, fctx,
10853 );
10854 if let Some((_, vb)) = &palette_uv_bufs {
10855 set_palette_pred(vb.clone(), fctx);
10856 }
10857 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
10858 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
10859 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
10860 let (v_levels, v_tx_type) = read_coeffs_rect(
10861 dec,
10862 &mut v_coding,
10863 chroma_scan,
10864 chroma_w,
10865 chroma_h,
10866 v_skip_ctx,
10867 dc_sign_ctx(around[2].2),
10868 v_default_tx,
10869 )?;
10870 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10871 let (rng, _) = dec.debug_state();
10872 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
10873 }
10874 let v_residual = dequant_and_inverse_typed_wh(
10875 &v_levels,
10876 chroma_w,
10877 chroma_h,
10878 crate::decode::bit_depth(fctx),
10879 block_q_idx(fctx),
10880 plane_q_delta(2, fctx).0,
10881 plane_q_delta(2, fctx).1,
10882 v_tx_type,
10883 );
10884 push_intra_rect(2,
10885 cpx,
10886 cpy,
10887 chroma_w,
10888 chroma_h,
10889 uv_predict_mode,
10890 angle_delta_uv,
10891 reach,
10892 &v_residual,
10893 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
10894 None,
10895 smooth_neighbor_uv, fctx,
10896 );
10897 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
10898 hit!(RECT_COEFF_HITS);
10899 }
10900 }
10901 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
10902 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
10903 let (puv_size, puv_colors) =
10904 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
10905 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
10906 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
10907 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
10908 hit!(RECT_PARTITION_HITS);
10909 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10910 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
10911 }
10912 Ok(())
10913}
10914
10915/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
10916/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
10917/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
10918/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
10919/// the second strip of a HORZ/VERT split sits offset by half the 16x16
10920/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
10921/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
10922/// previous strip is directly above (same column, `mi_h` rows up) or
10923/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
10924/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
10925/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
10926/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
10927/// this strip's real position, never the coarse `record_rect` (which the
10928/// caller uses once, after both strips, exactly like the `VERT_B` arm next
10929/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
10930/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
10931/// chroma half (`TxbSet::ChromaRect8x4`), the two size classes one level
10932/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
10933#[allow(clippy::too_many_arguments)]
10934fn decode_leaf_rect(
10935 dec: &mut SymbolDecoder,
10936 cdfs: &mut Cdfs,
10937 neighbours: &mut Neighbours,
10938 outer_at: (usize, usize),
10939 leaf_mi: (usize, usize),
10940 bw: usize,
10941 bh: usize,
10942 prev_leaf: Option<((usize, usize), usize)>,
10943 y: &mut PlaneBuf<'static>,
10944 u: &mut PlaneBuf<'static>,
10945 v: &mut PlaneBuf<'static>,
10946 enable_filter_intra: bool,
10947 allow_screen_content_tools: bool,
10948 base_q_idx: u8,
10949 tx_select: bool,
10950 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
10951) -> Result<usize> {
10952 let _ = base_q_idx;
10953 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
10954 eprintln!(
10955 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
10956 dec.debug_state().0
10957 );
10958 }
10959 let (r, c) = outer_at;
10960 let mut above_mode = neighbours.above_mode[c];
10961 let mut left_mode = neighbours.left_mode[r];
10962 let (mi_w, mi_h) = (bw / MI, bh / MI);
10963 if let Some(((pr, pc), pmode)) = prev_leaf {
10964 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
10965 above_mode = pmode;
10966 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
10967 left_mode = pmode;
10968 }
10969 }
10970 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
10971 // cannot hold the modes a split (or a pair of strips) leaves behind, so
10972 // when the map holds the block at exactly this strip's above/left mi it
10973 // is the neighbour libaom's `above_mi`/`left_mi` reads.
10974 // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND
10975 // availability-correct -- four 16x8 strips share one coarse 16x16
10976 // `left_mode` cell too, so the fallback must not stand in for an absent
10977 // tile-edge neighbour.
10978 let (above_mode, left_mode) =
10979 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
10980 let smooth_neighbor =
10981 is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
10982 if smooth_neighbor {
10983 hit!(SMOOTH_LUMA_HITS);
10984 }
10985 // The palette-Y mode CDF row is picked by the neighbours' palette use
10986 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
10987 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
10988 // a palette narrows the wrong interval and desyncs the tile even when the
10989 // decoded bit is the same. The cell is the 16px-SUB cell containing the
10990 // leaf (the palette neighbour arrays have no finer granularity).
10991 // lane-kf900 r6: the leaf's REAL mi position -- the second leaf of a 16x8
10992 // pair sits 8 px into the 16px cell, and both the cache's superblock-top-row
10993 // exclusion and the neighbour palette lookup itself are mi-granular
10994 // (see [`Neighbours::palette_ctx_and_cache_mi`]).
10995 let pal_at = leaf_mi;
10996 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
10997 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
10998 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
10999 read_intra_mode_rect(
11000 dec,
11001 cdfs,
11002 above_mode,
11003 left_mode,
11004 true,
11005 true,
11006 bw,
11007 bh,
11008 enable_filter_intra,
11009 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
11010 allow_screen_content_tools,
11011 Some((palette_ctx, &palette_cache)),
11012 &palette_uv_cache,
11013 leaf_mi.0,
11014 leaf_mi.1, fctx,
11015 )?;
11016 // lane-kf900 r4: palette prediction on this shape, the same colour-index
11017 // map -> base colours buffer [`decode_block_rect`] hands each
11018 // `reconstruct_rect` through [`set_palette_pred`].
11019 if palette_y.is_some() || palette_uv.is_some() {
11020 hit!(RECT4_PALETTE_HITS);
11021 }
11022 let palette_y_buf: Option<Vec<u16>> = palette_y
11023 .as_ref()
11024 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
11025 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
11026 (
11027 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
11028 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
11029 )
11030 });
11031 let (pal_y_size, pal_y_colors) =
11032 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
11033 let (pal_uv_size, pal_uv_colors) =
11034 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
11035 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
11036 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
11037 }
11038 if filter_intra.is_some() {
11039 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
11040 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
11041 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
11042 // below already makes; this refusal was square-only prose.
11043 hit!(FILTER_INTRA_RECT_HITS);
11044 hit!(FILTER_INTRA_RECT_SUB16_HITS);
11045 }
11046 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
11047 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
11048 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
11049 // a constant `false`.
11050 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
11051 let depth = if tx_select {
11052 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read
11053 // every other rect reader now does -- a no-op on a key frame.
11054 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
11055 tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx)
11056 } else {
11057 tx_size_context_rect(neighbours, leaf_mi, bw, bh)
11058 };
11059 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
11060 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
11061 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
11062 // count (3), different CDF row: a wrong-table read of a real symbol,
11063 // the class that cost lane-rectsplit r1 its 64x32 depth.
11064 // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's
11065 // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and
11066 // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this
11067 // function also decodes) sit at depth 2, so they read
11068 // `tx_size_cdf[1]` -- the same table a 16x16 square block reads --
11069 // while `tx_size_cat2` belongs to the 32-level shapes
11070 // ([`decode_block_rect`]). Both tables carry three symbols, so the
11071 // wrong one decodes a plausible depth from the wrong probabilities:
11072 // the range diverges silently at the first such leaf and every later
11073 // symbol in the tile is read from the wrong place (class
11074 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
11075 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
11076 } else {
11077 0
11078 };
11079 if depth != 0 || lossless(fctx) {
11080 // The same per-transform-unit walk the bigger strips take
11081 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
11082 // depth 2), addressed at this leaf's own mi position.
11083 hit!(TX_DEPTH_HITS);
11084 hit!(SUB16_SPLIT_HITS);
11085 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
11086 let modes = RectStripModes {
11087 skip,
11088 mode,
11089 angle_delta_y,
11090 uv_predict_mode,
11091 angle_delta_uv,
11092 alpha,
11093 filter_intra,
11094 smooth_neighbor,
11095 // lane-rectsplitx r3: the split arm hard-coded `false` here while
11096 // the unsplit arm below passes the real neighbour answer -- chroma
11097 // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type.
11098 smooth_neighbor_uv,
11099 palette_y: palette_y_buf.clone(),
11100 palette_uv: palette_uv_bufs.clone(),
11101 };
11102 if palette_y.is_some() || palette_uv.is_some() {
11103 hit!(PALETTE_SPLIT_TX_HITS);
11104 }
11105 decode_rect_split(
11106 dec,
11107 cdfs,
11108 neighbours,
11109 leaf_mi,
11110 bw,
11111 bh,
11112 tx_w,
11113 tx_h,
11114 &modes,
11115 y,
11116 u,
11117 v,
11118 base_q_idx,
11119 reduced_tx_set, fctx,
11120 )?;
11121 record_strip_palette(
11122 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
11123 );
11124 return Ok(mode);
11125 }
11126 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
11127 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
11128 let (cpx, cpy) = (px / 2, py / 2);
11129 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
11130 let (luma_levels, u_levels, v_levels);
11131 if skip {
11132 luma_levels = Grid::Zero(bw * bh);
11133 u_levels = Grid::Zero(chroma_w * chroma_h);
11134 v_levels = Grid::Zero(chroma_w * chroma_h);
11135 if let Some(b) = &palette_y_buf {
11136 set_palette_pred(b.clone(), fctx);
11137 }
11138 push_intra_rect(0,
11139 px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra,
11140 smooth_neighbor, fctx,
11141 );
11142 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
11143 if let Some((ub, _)) = &palette_uv_bufs {
11144 set_palette_pred(ub.clone(), fctx);
11145 }
11146 push_intra_rect(1,
11147 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels,
11148 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx,
11149 );
11150 if let Some((_, vb)) = &palette_uv_bufs {
11151 set_palette_pred(vb.clone(), fctx);
11152 }
11153 push_intra_rect(2,
11154 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels,
11155 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx,
11156 );
11157 } else {
11158 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
11159 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
11160 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
11161 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
11162 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
11163 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
11164 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 16 {
11165 (&SCAN_16X8, &SCAN_8X4)
11166 } else {
11167 (&SCAN_8X16, &SCAN_4X8)
11168 };
11169 let around = neighbours.around_mi_rect(leaf_mi, bw, bh);
11170 let luma_set = if reduced_tx_set {
11171 TxbSet::LumaRect16x8
11172 } else {
11173 TxbSet::LumaRect16x8Set1
11174 };
11175 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
11176 let (l_levels, luma_tx_type) = read_coeffs_rect(
11177 dec, &mut luma_coding, luma_scan, bw, bh, 0, dc_sign_ctx(around[0].2), TxType::DctDct,
11178 )?;
11179 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
11180 let nz: Vec<(usize, i32)> = l_levels.iter().copied().enumerate().filter(|(_, v)| *v != 0).collect();
11181 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
11182 }
11183 luma_levels = l_levels;
11184 let luma_residual = dequant_and_inverse_typed_wh(
11185 &luma_levels, bw, bh, crate::decode::bit_depth(fctx),
11186 fctx.current_q_idx.with(|c| c.get()), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, luma_tx_type,
11187 );
11188 if let Some(b) = &palette_y_buf {
11189 set_palette_pred(b.clone(), fctx);
11190 }
11191 push_intra_rect(0,
11192 px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra,
11193 smooth_neighbor, fctx,
11194 );
11195 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
11196 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
11197 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
11198 let mut u_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
11199 let (u_l, u_tx_type) = read_coeffs_rect(
11200 dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx,
11201 dc_sign_ctx(around[1].2), u_default_tx,
11202 )?;
11203 u_levels = u_l;
11204 let u_residual = dequant_and_inverse_typed_wh(
11205 &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx),
11206 fctx.current_q_idx.with(|c| c.get()), plane_q_delta(1, fctx).0, plane_q_delta(1, fctx).1, u_tx_type,
11207 );
11208 if let Some((ub, _)) = &palette_uv_bufs {
11209 set_palette_pred(ub.clone(), fctx);
11210 }
11211 push_intra_rect(1,
11212 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual,
11213 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx,
11214 );
11215 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
11216 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
11217 let mut v_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
11218 let (v_l, v_tx_type) = read_coeffs_rect(
11219 dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx,
11220 dc_sign_ctx(around[2].2), v_default_tx,
11221 )?;
11222 v_levels = v_l;
11223 let v_residual = dequant_and_inverse_typed_wh(
11224 &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx),
11225 fctx.current_q_idx.with(|c| c.get()), plane_q_delta(2, fctx).0, plane_q_delta(2, fctx).1, v_tx_type,
11226 );
11227 if let Some((_, vb)) = &palette_uv_bufs {
11228 set_palette_pred(vb.clone(), fctx);
11229 }
11230 push_intra_rect(2,
11231 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual,
11232 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx,
11233 );
11234 hit!(RECT_LEAF_COEFF_HITS);
11235 }
11236 neighbours.record_mi_rect(leaf_mi, bw, bh, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
11237 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
11238 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
11239 // The leaf's own palette state (`0` clears, as this site always did
11240 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT
11241 // AXIS only until the pair's closing leaf: the coarse cell holds one
11242 // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the
11243 // real left neighbour leaf 1 reads (lane-kf900 r4).
11244 record_strip_palette(
11245 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
11246 );
11247 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
11248 // rows -- record the whole span, not one cell.
11249 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
11250 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
11251 Ok(mode)
11252}
11253
11254/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
11255/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
11256/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
11257/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
11258/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
11259/// strip's mode so this one's mode context sees its true above/left
11260/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
11261///
11262/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
11263/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
11264/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
11265/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
11266/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
11267/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
11268/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
11269///
11270/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
11271/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
11272/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
11273/// unexamined.
11274#[allow(clippy::too_many_arguments)]
11275fn decode_block_rect4(
11276 dec: &mut SymbolDecoder,
11277 cdfs: &mut Cdfs,
11278 neighbours: &mut Neighbours,
11279 strip_mi: (usize, usize),
11280 bw: usize,
11281 bh: usize,
11282 prev_strip: Option<((usize, usize), usize)>,
11283 y: &mut PlaneBuf<'static>,
11284 u: &mut PlaneBuf<'static>,
11285 v: &mut PlaneBuf<'static>,
11286 enable_filter_intra: bool,
11287 allow_screen_content_tools: bool,
11288 base_q_idx: u8,
11289 tx_select: bool, fctx: &crate::decode::FrameCtx,
11290) -> Result<(usize, usize)> {
11291 let _ = base_q_idx;
11292 let (mi_r, mi_c) = strip_mi;
11293 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
11294 let (mi_w, mi_h) = (bw / MI, bh / MI);
11295 let mut above_mode = neighbours.above_mode[c];
11296 let mut left_mode = neighbours.left_mode[r];
11297 if let Some(((pr, pc), pmode)) = prev_strip {
11298 if pc == mi_c && mi_r == pr + mi_h {
11299 above_mode = pmode;
11300 } else if pr == mi_r && mi_c == pc + mi_w {
11301 left_mode = pmode;
11302 }
11303 }
11304 // lane-rectsplitx r2, ROOT CAUSE of the 1:4 mismatch: mi-exact +
11305 // availability-correct neighbour modes (see
11306 // [`Neighbours::modes_above_left_mi`]). The coarse 16x16 bands alias every
11307 // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell.
11308 let (above_mode, left_mode) =
11309 neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode));
11310 // lane-kf900 r4: this strip's own palette-Y mode ctx and colour cache.
11311 // Passing `None`/`&[]` read `palette_y_mode` off CDF row 0 and every
11312 // `palette_colors_y` cache hit off an EMPTY cache -- right symbol count,
11313 // wrong interval, so a screen-content tile desynced at the first strip
11314 // whose neighbour used a palette (class [[cdf-row-held-constant]]).
11315 let pal_at = (mi_r, mi_c);
11316 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
11317 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
11318 let (
11319 skip,
11320 mode,
11321 angle_delta_y,
11322 uv_mode,
11323 angle_delta_uv,
11324 alpha,
11325 filter_intra,
11326 palette_y,
11327 palette_uv,
11328 ) = read_intra_mode_rect(
11329 dec,
11330 cdfs,
11331 above_mode,
11332 left_mode,
11333 true,
11334 true,
11335 bw,
11336 bh,
11337 enable_filter_intra,
11338 neighbours.skip_txfm_ctx(mi_r, mi_c),
11339 allow_screen_content_tools,
11340 Some((palette_ctx, &palette_cache)),
11341 &palette_uv_cache,
11342 mi_r,
11343 mi_c, fctx,
11344 )?;
11345 // lane-kf900 r4: palette prediction on this shape, exactly as
11346 // [`decode_block_rect`] does one aspect ratio up -- the colour-index map
11347 // mapped through the base colours IS the prediction (it reads no edge
11348 // pixels), handed to each `reconstruct_rect` through [`set_palette_pred`].
11349 if palette_y.is_some() || palette_uv.is_some() {
11350 hit!(RECT4_PALETTE_HITS);
11351 }
11352 let palette_y_buf: Option<Vec<u16>> = palette_y
11353 .as_ref()
11354 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
11355 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
11356 (
11357 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
11358 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
11359 )
11360 });
11361 let (pal_y_size, pal_y_colors) =
11362 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
11363 let (pal_uv_size, pal_uv_colors) =
11364 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
11365 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
11366 if smooth_neighbor {
11367 hit!(SMOOTH_LUMA_HITS);
11368 }
11369 // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's
11370 // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so
11371 // `r * (SUB / MI)` names a different mi column and the chroma
11372 // edge-filter strength was read from the wrong neighbour (measured:
11373 // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch
11374 // with luma bit-exact).
11375 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
11376 if filter_intra.is_some() {
11377 hit!(FILTER_INTRA_RECT_HITS);
11378 if bw > bh {
11379 hit!(FILTER_INTRA_RECT4_HORZ_HITS);
11380 } else {
11381 hit!(FILTER_INTRA_RECT4_VERT_HITS);
11382 }
11383 }
11384 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
11385 DC_PRED
11386 } else {
11387 uv_mode
11388 };
11389 let depth = if tx_select {
11390 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
11391 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
11392 // the 16x4 intra-in-inter strips already do); the key frame's
11393 // deblock-grid approximation is only right where those bands were never
11394 // written. Measured on the 10-bit 1920x792 128-superblock stream,
11395 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
11396 // `tx_size_cat2` row 1 where libaom reads row 2.
11397 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
11398 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
11399 } else {
11400 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
11401 };
11402 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
11403 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
11404 eprintln!(
11405 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
11406 dec.debug_state().0
11407 );
11408 }
11409 d
11410 } else {
11411 0
11412 };
11413 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
11414 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
11415 publish_txfm_bands_if_in_inter(
11416 neighbours,
11417 (mi_r, mi_c),
11418 depth_to_tx_wh(bw, bh, depth, fctx),
11419 (bw, bh), fctx,
11420 );
11421 if depth != 0 || lossless(fctx) {
11422 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
11423 // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a
11424 // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16
11425 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8;
11426 // both interleave in every real stream.
11427 hit!(TX_DEPTH_HITS);
11428 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
11429 // lane-rectsplitx r2: both depths ship together, as the r1 handoff
11430 // predicted -- depth 1 fires FIRST in every attempt that splits at
11431 // all, so a depth-2-only lift could never be gated. The r1 mismatch
11432 // was never the rect unit: it was the neighbour MODE the strip reads
11433 // (see `modes_above_left_mi`).
11434 let which = if depth == 1 {
11435 &RECT4_SPLIT_DEPTH1_HITS
11436 } else {
11437 &RECT4_SPLIT_DEPTH2_HITS
11438 };
11439 hit_do! { which.with(|c| c.set(c.get() + 1)); }
11440 let modes = RectStripModes {
11441 skip,
11442 mode,
11443 angle_delta_y,
11444 uv_predict_mode,
11445 angle_delta_uv,
11446 alpha,
11447 filter_intra,
11448 smooth_neighbor,
11449 smooth_neighbor_uv,
11450 palette_y: palette_y_buf.clone(),
11451 palette_uv: palette_uv_bufs.clone(),
11452 };
11453 if palette_y.is_some() || palette_uv.is_some() {
11454 hit!(PALETTE_SPLIT_TX_HITS);
11455 }
11456 decode_rect_split(
11457 dec,
11458 cdfs,
11459 neighbours,
11460 (mi_r, mi_c),
11461 bw,
11462 bh,
11463 tx_w,
11464 tx_h,
11465 &modes,
11466 y,
11467 u,
11468 v,
11469 base_q_idx,
11470 false, fctx,
11471 )?;
11472 record_strip_palette(
11473 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
11474 pal_uv_colors,
11475 );
11476 if bw > bh {
11477 hit!(RECT4_32_HORZ_HITS);
11478 } else {
11479 hit!(RECT4_32_VERT_HITS);
11480 }
11481 if !skip {
11482 hit!(RECT4_COEFF_HITS);
11483 }
11484 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
11485 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
11486 // frame, so this 1:4 strip -- which is also the INTER frame's reader
11487 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
11488 // transform size in both TXFM_CONTEXT bands. Without it the next block
11489 // reads the row's stale value.
11490 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
11491 return Ok((mode, uv_predict_mode));
11492 }
11493 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
11494 // that is 8 px tall, so each strip stamps every cell it touches and the
11495 // LAST strip wins -- which is the right answer for the block below/right
11496 // of the 32x32, the only reader outside it. Written after this strip's
11497 // own context read above, never before.
11498 for cell in 0..bw.div_ceil(SUB) {
11499 neighbours.above_mode[c + cell] = mode;
11500 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
11501 neighbours.above_side[c + cell] = bw;
11502 }
11503 for cell in 0..bh.div_ceil(SUB) {
11504 neighbours.left_mode[r + cell] = mode;
11505 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
11506 neighbours.left_side[r + cell] = bh;
11507 }
11508 // ...and the mi-EXACT maps the coarse cells alias away, exactly as
11509 // [`decode_leaf_rect`] does (the split arm above records these through
11510 // `record_mi_luma_rect`). Without this an unsplit 32x8 strip left
11511 // `sub8_mode_row` holding the previous block, and the next 32x32's
11512 // strips read a stale `kf_y_mode` row (measured: mi(4,8) on the band
11513 // fixture).
11514 neighbours.record_mode_mi(mi_r, mi_c, mi_w, mi_h, mode);
11515 neighbours.record_uv_mode_mi(mi_r, mi_c, mi_w, mi_h, uv_predict_mode);
11516 let (px, py) = (mi_c * MI, mi_r * MI);
11517 let (cpx, cpy) = (px / 2, py / 2);
11518 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
11519 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
11520 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw > bh {
11521 (&SCAN_32X8, &SCAN_16X4)
11522 } else {
11523 (&SCAN_8X32, &SCAN_4X16)
11524 };
11525 let (luma_levels, u_levels, v_levels) = if skip {
11526 (
11527 vec![0i32; bw * bh],
11528 vec![0i32; chroma_w * chroma_h],
11529 vec![0i32; chroma_w * chroma_h],
11530 )
11531 } else {
11532 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
11533 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
11534 let (luma_levels, luma_tx_type) = read_coeffs_rect(
11535 dec,
11536 &mut luma_coding,
11537 luma_scan,
11538 bw,
11539 bh,
11540 0,
11541 dc_sign_ctx(around[0].2),
11542 TxType::DctDct,
11543 )?;
11544 let mut planes = Vec::with_capacity(2);
11545 for plane in 1..3 {
11546 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
11547 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
11548 let mut coding = cdfs.txb(TxbSet::Chroma8, uv_predict_mode);
11549 let (levels, tx_type) = read_coeffs_rect(
11550 dec,
11551 &mut coding,
11552 chroma_scan,
11553 chroma_w,
11554 chroma_h,
11555 skip_ctx,
11556 dc_sign_ctx(around[plane].2),
11557 default_tx,
11558 )?;
11559 planes.push((levels, tx_type));
11560 }
11561 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
11562 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
11563 hit!(RECT4_COEFF_HITS);
11564 let luma_residual = dequant_and_inverse_typed_wh(
11565 &luma_levels,
11566 bw,
11567 bh,
11568 crate::decode::bit_depth(fctx),
11569 block_q_idx(fctx),
11570 plane_q_delta(0, fctx).0,
11571 plane_q_delta(0, fctx).1,
11572 luma_tx_type,
11573 );
11574 if let Some(b) = &palette_y_buf {
11575 set_palette_pred(b.clone(), fctx);
11576 }
11577 push_intra_rect(0,
11578 px,
11579 py,
11580 bw,
11581 bh,
11582 mode,
11583 angle_delta_y,
11584 reach,
11585 &luma_residual,
11586 None,
11587 filter_intra,
11588 smooth_neighbor, fctx,
11589 );
11590 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
11591 for (plane, _buf, levels, tx_type) in [
11592 (1usize, &mut *u, &u_levels, u_tx_type),
11593 (2, &mut *v, &v_levels, v_tx_type),
11594 ] {
11595 let residual = dequant_and_inverse_typed_wh(
11596 levels,
11597 chroma_w,
11598 chroma_h,
11599 crate::decode::bit_depth(fctx),
11600 block_q_idx(fctx),
11601 plane_q_delta(plane, fctx).0,
11602 plane_q_delta(plane, fctx).1,
11603 tx_type,
11604 );
11605 if let Some((ub, vb)) = &palette_uv_bufs {
11606 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
11607 }
11608 push_intra_rect(plane,
11609 cpx,
11610 cpy,
11611 chroma_w,
11612 chroma_h,
11613 uv_predict_mode,
11614 angle_delta_uv,
11615 reach,
11616 &residual,
11617 alpha
11618 .zip(ac)
11619 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
11620 None,
11621 smooth_neighbor_uv, fctx,
11622 );
11623 }
11624 neighbours.record_mi_rect(
11625 (mi_r, mi_c),
11626 bw,
11627 bh,
11628 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
11629 );
11630 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
11631 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
11632 record_strip_palette(
11633 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
11634 pal_uv_colors,
11635 );
11636 if bw > bh {
11637 hit!(RECT4_32_HORZ_HITS);
11638 } else {
11639 hit!(RECT4_32_VERT_HITS);
11640 }
11641 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
11642 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
11643 // frame, so this 1:4 strip -- which is also the INTER frame's reader
11644 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
11645 // transform size in both TXFM_CONTEXT bands. Without it the next block
11646 // reads the row's stale value.
11647 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
11648 return Ok((mode, uv_predict_mode));
11649 };
11650 if let Some(b) = &palette_y_buf {
11651 set_palette_pred(b.clone(), fctx);
11652 }
11653 push_intra_rect(0,
11654 px,
11655 py,
11656 bw,
11657 bh,
11658 mode,
11659 angle_delta_y,
11660 reach,
11661 &luma_levels,
11662 None,
11663 filter_intra,
11664 smooth_neighbor, fctx,
11665 );
11666 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
11667 if let Some((ub, _)) = &palette_uv_bufs {
11668 set_palette_pred(ub.clone(), fctx);
11669 }
11670 push_intra_rect(1,
11671 cpx,
11672 cpy,
11673 chroma_w,
11674 chroma_h,
11675 uv_predict_mode,
11676 angle_delta_uv,
11677 reach,
11678 &u_levels,
11679 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
11680 None,
11681 smooth_neighbor_uv, fctx,
11682 );
11683 if let Some((_, vb)) = &palette_uv_bufs {
11684 set_palette_pred(vb.clone(), fctx);
11685 }
11686 push_intra_rect(2,
11687 cpx,
11688 cpy,
11689 chroma_w,
11690 chroma_h,
11691 uv_predict_mode,
11692 angle_delta_uv,
11693 reach,
11694 &v_levels,
11695 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
11696 None,
11697 smooth_neighbor_uv, fctx,
11698 );
11699 neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
11700 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
11701 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
11702 record_strip_palette(
11703 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
11704 );
11705 if bw > bh {
11706 hit!(RECT4_32_HORZ_HITS);
11707 } else {
11708 hit!(RECT4_32_VERT_HITS);
11709 }
11710 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
11711 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
11712 // frame, so this 1:4 strip -- which is also the INTER frame's reader
11713 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
11714 // transform size in both TXFM_CONTEXT bands. Without it the next block
11715 // reads the row's stale value.
11716 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
11717 Ok((mode, uv_predict_mode))
11718}
11719
11720/// Decodes the four 16x4 / 4x16 strips of a 16x16-level `PARTITION_HORZ_4` /
11721/// `PARTITION_VERT_4` (lane-r14) -- [`decode_block_rect4`]'s pair one level
11722/// down, and the first shape here whose luma block is a single mi row (or
11723/// column).
11724///
11725/// What is new at this size is CHROMA. `is_chroma_reference`
11726/// (`av1_common_int.h`) is false for a 4:2:0 block one mi tall (wide) on an
11727/// EVEN mi row (column), so strips 0 and 2 read no `uv_mode`/`cfl_alpha`/
11728/// `angle_delta_uv` at all and code no chroma residual; strips 1 and 3 close
11729/// the pair and carry the chroma of the whole 16x8 (8x16) luma pair --
11730/// `setup_pred_plane`'s own `if (subsampling_y && (mi_row & 1) &&
11731/// mi_size_high[bsize] == 1) mi_row -= 1` offset, i.e. an 8x4 (4x8) chroma
11732/// transform at the PAIR's origin, with CfL averaging over the pair's luma.
11733///
11734/// Tables: LUMA `TX_16X4`/`TX_4X16` averages to the 8x8 entropy context
11735/// ((0 + 2 + 1) >> 1 = 1) with 64 coded positions, so its CDF set is
11736/// [`TxbSet::LumaRect16x4`] (`Luma8`'s tables, the `TX_4X4` `tx_type` row);
11737/// scans are [`SCAN_16X4`]/[`SCAN_4X16`]. CHROMA `TX_8X4`/`TX_4X8` is
11738/// [`TxbSet::ChromaRect8x4`] with [`SCAN_8X4`]/[`SCAN_4X8`]. Angle deltas ARE
11739/// coded (`av1_use_angle_delta` compares the BLOCK_SIZES_ALL enum index, and
11740/// BLOCK_16X4 is 17), and so is `use_filter_intra` (both sides <= 32) off this
11741/// shape's own CDF row.
11742///
11743/// A split transform (`tx_depth != 0`, `sub_tx_size_map[TX_16X4] == TX_8X4`)
11744/// refuses by name rather than guess-decode.
11745#[allow(clippy::too_many_arguments)]
11746fn decode_rect4_16(
11747 dec: &mut SymbolDecoder,
11748 cdfs: &mut Cdfs,
11749 neighbours: &mut Neighbours,
11750 at16: (usize, usize),
11751 horz: bool,
11752 y: &mut PlaneBuf<'static>,
11753 u: &mut PlaneBuf<'static>,
11754 v: &mut PlaneBuf<'static>,
11755 enable_filter_intra: bool,
11756 allow_screen_content_tools: bool,
11757 base_q_idx: u8,
11758 tx_select: bool,
11759 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
11760) -> Result<()> {
11761 let (r, c) = at16;
11762 let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI));
11763 let (bw, bh) = if horz { (16, 4) } else { (4, 16) };
11764 let (_mi_w, _mi_h) = (bw / MI, bh / MI);
11765 let _scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
11766 let _chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
11767 let mut prev: Option<((usize, usize), usize)> = None;
11768 let mut last_mode = DC_PRED;
11769 let mut last_uv_mode = DC_PRED;
11770 for i in 0..4usize {
11771 let lmi = if horz {
11772 (mi_row0 + i, mi_col0)
11773 } else {
11774 (mi_row0, mi_col0 + i)
11775 };
11776 let has_chroma = i % 2 == 1;
11777 let (mode, uv, _tx) = decode_rect4_16_strip(
11778 dec,
11779 cdfs,
11780 neighbours,
11781 lmi,
11782 horz,
11783 has_chroma,
11784 prev,
11785 y,
11786 u,
11787 v,
11788 enable_filter_intra,
11789 allow_screen_content_tools,
11790 base_q_idx,
11791 tx_select,
11792 reduced_tx_set, fctx,
11793 )?;
11794 if let Some(m) = uv {
11795 last_uv_mode = m;
11796 }
11797 last_mode = mode;
11798 prev = Some((lmi, mode));
11799 }
11800 // The coarse 16-px cell holds one entry for the whole 16x16: the last
11801 // strip is what a block below (right) sees through it, the mi-exact maps
11802 // above answering everything finer.
11803 neighbours.above_mode[c] = last_mode;
11804 neighbours.left_mode[r] = last_mode;
11805 neighbours.above_uv_mode[c] = last_uv_mode;
11806 neighbours.left_uv_mode[r] = last_uv_mode;
11807 neighbours.above_side[c] = bw;
11808 neighbours.left_side[r] = bh;
11809 Ok(())
11810}
11811
11812/// One 16x4 / 4x16 strip of a 16x16-level 1:4 partition, intra-coded --
11813/// [`decode_rect4_16`]'s per-strip body, lifted (lane-intra16x4) so the INTER
11814/// block path can decode a SINGLE intra strip of a partition whose other
11815/// strips are inter. `prev` is the previous strip's `(mi, mode)` (the
11816/// key-frame caller's coarse-cell stand-in; `None` on the inter path, where
11817/// every strip publishes its own mi-exact mode). Returns
11818/// `(y_mode, uv_predict_mode when this strip closes the 4:2:0 chroma pair)`.
11819#[allow(clippy::too_many_arguments)]
11820fn decode_rect4_16_strip(
11821 dec: &mut SymbolDecoder,
11822 cdfs: &mut Cdfs,
11823 neighbours: &mut Neighbours,
11824 lmi: (usize, usize),
11825 horz: bool,
11826 has_chroma: bool,
11827 prev: Option<((usize, usize), usize)>,
11828 y: &mut PlaneBuf<'static>,
11829 u: &mut PlaneBuf<'static>,
11830 v: &mut PlaneBuf<'static>,
11831 enable_filter_intra: bool,
11832 allow_screen_content_tools: bool,
11833 base_q_idx: u8,
11834 tx_select: bool,
11835 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
11836) -> Result<(usize, Option<usize>, (usize, usize))> {
11837 let (r, c) = (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI));
11838 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
11839 let (mi_w, mi_h) = (bw / MI, bh / MI);
11840 let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
11841 let chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
11842 let mut last_uv_mode: Option<usize> = None;
11843 // `decode_block_rect4`'s own neighbour rule: the coarse 16-px cell
11844 // aliases all four strips onto one entry, so the mi-exact map wins and
11845 // the previous strip stands in on the split axis.
11846 let mut above_mode = neighbours.above_mode[c];
11847 let mut left_mode = neighbours.left_mode[r];
11848 if let Some(((pr, pc), pmode)) = prev {
11849 if pc == lmi.1 && lmi.0 == pr + mi_h {
11850 above_mode = pmode;
11851 } else if pr == lmi.0 && lmi.1 == pc + mi_w {
11852 left_mode = pmode;
11853 }
11854 }
11855 let (above_mode, left_mode) =
11856 neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode));
11857 // lane-kf900 r4: the strip's real palette ctx + colour cache (see
11858 // [`decode_block_rect4`]); `None`/`&[]` here read `palette_y_mode`
11859 // off CDF row 0 and every cache hit off an empty cache.
11860 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(lmi);
11861 let palette_uv_cache = neighbours.palette_uv_cache_mi(lmi);
11862 let (
11863 skip,
11864 mode,
11865 angle_delta_y,
11866 uv_mode,
11867 angle_delta_uv,
11868 alpha,
11869 filter_intra,
11870 palette_y,
11871 palette_uv,
11872 ) = read_intra_mode_rect(
11873 dec,
11874 cdfs,
11875 above_mode,
11876 left_mode,
11877 true,
11878 has_chroma,
11879 bw,
11880 bh,
11881 enable_filter_intra,
11882 neighbours.skip_txfm_ctx(lmi.0, lmi.1),
11883 allow_screen_content_tools,
11884 Some((palette_ctx, &palette_cache)),
11885 &palette_uv_cache,
11886 lmi.0,
11887 lmi.1, fctx,
11888 )?;
11889 if palette_y.is_some() || palette_uv.is_some() {
11890 hit!(RECT4_PALETTE_HITS);
11891 }
11892 // The colour-index map through the base colours IS the prediction.
11893 // Chroma's map is the PAIR's 8x4 (4x8) block, matching the one
11894 // chroma transform this closing strip codes.
11895 let palette_y_buf: Option<Vec<u16>> = palette_y
11896 .as_ref()
11897 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
11898 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
11899 (
11900 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
11901 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
11902 )
11903 });
11904 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
11905 if smooth_neighbor {
11906 hit!(SMOOTH_LUMA_HITS);
11907 }
11908 if filter_intra.is_some() {
11909 hit!(FILTER_INTRA_RECT_HITS);
11910 }
11911 // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is
11912 // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the
11913 // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol
11914 // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does.
11915 let depth = if tx_select {
11916 // lane-intra16x4: on an INTER frame `get_tx_size_context` reads the
11917 // real `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what
11918 // the 2:1 intra-in-inter strip already does); the key frame's
11919 // deblock-grid approximation is only right where those bands were
11920 // never written.
11921 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
11922 tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx)
11923 } else {
11924 tx_size_context_rect(neighbours, lmi, bw, bh)
11925 };
11926 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
11927 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
11928 eprintln!(
11929 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
11930 lmi.0,
11931 lmi.1,
11932 dec.debug_state().0
11933 );
11934 }
11935 d
11936 } else {
11937 0
11938 };
11939 if depth != 0 {
11940 hit!(TX_DEPTH_HITS);
11941 hit!(RECT4_16_SPLIT_HITS);
11942 }
11943 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
11944 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
11945 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
11946 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode);
11947 if depth != 0 || lossless(fctx) {
11948 // [`decode_rect_split`]'s per-unit walk, inlined because the
11949 // CHROMA of this shape belongs to the strip's 4:2:0 pair, not to
11950 // the strip (that function codes one chroma transform per block).
11951 // depth 1 is the 2:1 rect unit TX_8X4/TX_4X8
11952 // (`sub_tx_size_map[TX_16X4]`), depth 2 the square TX_4X4; each
11953 // unit predicts off the units before it in raster order.
11954 let rect_unit = tx_w != tx_h;
11955 let zero_tu = vec![0i32; tx_w * tx_h];
11956 for tu_row in 0..bh / tx_h {
11957 for tu_col in 0..bw / tx_w {
11958 let tu_mi = (lmi.0 + tu_row * (tx_h / MI), lmi.1 + tu_col * (tx_w / MI));
11959 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
11960 let tu_reach = Reach::of_tu(
11961 bw,
11962 bh,
11963 tu_col * tx_w,
11964 tu_row * tx_h,
11965 tx_w,
11966 tx_h,
11967 reach,
11968 );
11969 if let Some(b) = &palette_y_buf {
11970 let tu_buf: Vec<u16> = (0..tx_h)
11971 .flat_map(|i| {
11972 let base = (tu_row * tx_h + i) * bw + tu_col * tx_w;
11973 b[base..base + tx_w].iter().copied()
11974 })
11975 .collect();
11976 set_palette_pred(tu_buf, fctx);
11977 }
11978 if skip {
11979 push_intra_rect(0,
11980 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &zero_tu,
11981 None, filter_intra, smooth_neighbor, fctx,
11982 );
11983 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
11984 } else if rect_unit {
11985 // `get_txsize_entropy_ctx(TX_8X4)` is the 8x8 class with
11986 // 32 coded positions and the `TX_4X4` `tx_type` row:
11987 // exactly [`TxbSet::LumaRect4x8`].
11988 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
11989 let tu_skip_ctx =
11990 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI);
11991 let set = if reduced_tx_set {
11992 TxbSet::LumaRect4x8
11993 } else {
11994 TxbSet::LumaRect4x8Set1
11995 };
11996 let tu_scan: &[u16] = if tx_w > tx_h { &SCAN_8X4 } else { &SCAN_4X8 };
11997 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
11998 let (tu_grid, tu_tx_type) = read_coeffs_rect(
11999 dec,
12000 &mut coding,
12001 tu_scan,
12002 tx_w,
12003 tx_h,
12004 tu_skip_ctx,
12005 dc_sign_ctx(tu_around.2),
12006 TxType::DctDct,
12007 )?;
12008 let residual = dequant_and_inverse_typed_wh(
12009 &tu_grid,
12010 tx_w,
12011 tx_h,
12012 crate::decode::bit_depth(fctx),
12013 block_q_idx(fctx),
12014 plane_q_delta(0, fctx).0,
12015 plane_q_delta(0, fctx).1,
12016 tu_tx_type,
12017 );
12018 push_intra_rect(0,
12019 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &residual,
12020 None, filter_intra, smooth_neighbor, fctx,
12021 );
12022 if tu_grid.iter().any(|&l| l != 0) {
12023 hit!(RECT4_16_COEFF_HITS);
12024 }
12025 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
12026 } else {
12027 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
12028 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
12029 let tu_grid = read_plane(
12030 dec,
12031 cdfs,
12032 txbset_for(tx_w, reduced_tx_set),
12033 default_scan(tx_w),
12034 0,
12035 tu_around,
12036 mode,
12037 mode,
12038 angle_delta_y,
12039 tu_reach,
12040 y,
12041 tu_px,
12042 tu_py,
12043 tx_w,
12044 tx_w,
12045 base_q_idx,
12046 None,
12047 filter_intra,
12048 Some(tu_skip_ctx),
12049 smooth_neighbor, fctx,
12050 )?;
12051 if tu_grid.iter().any(|&l| l != 0) {
12052 hit!(RECT4_16_COEFF_HITS);
12053 }
12054 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
12055 }
12056 }
12057 }
12058 } else {
12059 let levels = if skip {
12060 let zeros = Grid::Zero(bw * bh);
12061 if let Some(b) = &palette_y_buf {
12062 set_palette_pred(b.clone(), fctx);
12063 }
12064 push_intra_rect(0,
12065 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
12066 smooth_neighbor, fctx,
12067 );
12068 zeros
12069 } else {
12070 // The strip's luma TU *is* the strip (`plane_bsize ==
12071 // txsize_to_bsize[tx_size]`), so `get_txb_ctx` fixes
12072 // `txb_skip_ctx` at 0.
12073 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
12074 let set = if reduced_tx_set {
12075 TxbSet::LumaRect16x4
12076 } else {
12077 TxbSet::LumaRect16x4Set1
12078 };
12079 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
12080 let (levels, tx_type) = read_coeffs_rect(
12081 dec,
12082 &mut coding,
12083 scan,
12084 bw,
12085 bh,
12086 0,
12087 dc_sign_ctx(around.2),
12088 TxType::DctDct,
12089 )?;
12090 let residual = dequant_and_inverse_typed_wh(
12091 &levels,
12092 bw,
12093 bh,
12094 crate::decode::bit_depth(fctx),
12095 block_q_idx(fctx),
12096 plane_q_delta(0, fctx).0,
12097 plane_q_delta(0, fctx).1,
12098 tx_type,
12099 );
12100 if let Some(b) = &palette_y_buf {
12101 set_palette_pred(b.clone(), fctx);
12102 }
12103 push_intra_rect(0,
12104 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
12105 smooth_neighbor, fctx,
12106 );
12107 hit!(RECT4_16_COEFF_HITS);
12108 levels
12109 };
12110 neighbours.record_mi_luma_rect(lmi, bw, bh, &levels);
12111 }
12112 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
12113 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
12114 // `update_partition_context` writes `partition_context_lookup[
12115 // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on
12116 // the left (mirrored under VERT_4).
12117 for cell in 0..mi_w {
12118 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
12119 *slot = bw as u8;
12120 }
12121 }
12122 for cell in 0..mi_h {
12123 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
12124 *slot = bh as u8;
12125 }
12126 }
12127 if has_chroma {
12128 hit!(RECT4_16_CHROMA_HITS);
12129 let pair_mi = if horz {
12130 (lmi.0 - 1, lmi.1)
12131 } else {
12132 (lmi.0, lmi.1 - 1)
12133 };
12134 let (pw, ph) = if horz { (16, 8) } else { (8, 16) };
12135 let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI);
12136 let (cpx, cpy) = (ppx / 2, ppy / 2);
12137 let (cw, ch) = (pw / 2, ph / 2);
12138 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
12139 if (V_PRED..=D67_PRED).contains(&uv_predict_mode) {
12140 hit!(RECT4_16_CHROMA_DIR_HITS);
12141 }
12142 let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height, fctx);
12143 // lane-kf1200 r1: the chroma edge-filter type reads the neighbours
12144 // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s
12145 // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/
12146 // `chroma_left_mbmi` from `mi[-((mi_row & ss_y) * stride + (mi_col
12147 // & ss_x))]` (`set_mi_offsets`, av1/common/blockd.h ~1050), i.e.
12148 // the pair's top-left luma mi, never this leaf's odd row/column.
12149 // Reading `lmi` here named the leaf directly above (a non-chroma
12150 // -reference 4-row block, `uv_mode == UV_DC_PRED`) and so lost a
12151 // SMOOTH neighbour: filt_type 0 instead of 1 turned
12152 // `av1_use_intra_edge_upsample` on (blk_wh 12 <= 16) for a
12153 // directional chroma strip, moving 4 samples by 1.
12154 let smooth_neighbor_uv =
12155 neighbours.smooth_uv_neighbour(pair_mi.0, pair_mi.1, r, c);
12156 if smooth_neighbor_uv != neighbours.smooth_uv_neighbour_unsnapped(lmi.0, lmi.1, r, c)
12157 {
12158 hit!(RECT4_16_UV_PAIR_FILT_HITS);
12159 }
12160 let (u_levels, v_levels) = if skip {
12161 let zeros = Grid::Zero(cw * ch);
12162 // libaom `predict_and_reconstruct_intra_block` (decodeframe.c
12163 // ~1000) predicts EVERY plane and only guards the residual on
12164 // `mbmi->skip_txfm`, so a skipped `UV_CFL_PRED` block is still
12165 // DC + alpha * luma-AC. Dropping the CfL term here left a
12166 // chroma-only bounded box on ReelC's key frames.
12167 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
12168 if alpha.is_some() {
12169 hit!(CHROMA_SKIP_CFL_HITS);
12170 }
12171 for (_buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] {
12172 if let Some((ub, vb)) = &palette_uv_bufs {
12173 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
12174 }
12175 push_intra_rect(plane,
12176 cpx,
12177 cpy,
12178 cw,
12179 ch,
12180 uv_predict_mode,
12181 angle_delta_uv,
12182 pair_reach,
12183 &zeros,
12184 alpha
12185 .zip(ac)
12186 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
12187 None,
12188 smooth_neighbor_uv, fctx,
12189 );
12190 }
12191 (zeros.clone(), zeros)
12192 } else {
12193 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
12194 let mut planes = Vec::with_capacity(2);
12195 for plane in 1..3 {
12196 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
12197 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
12198 let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
12199 let (levels, tx_type) = read_coeffs_rect(
12200 dec,
12201 &mut coding,
12202 chroma_scan,
12203 cw,
12204 ch,
12205 skip_ctx,
12206 dc_sign_ctx(around[plane].2),
12207 default_tx,
12208 )?;
12209 planes.push((levels, tx_type));
12210 }
12211 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
12212 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
12213 // CfL averages the luma of the WHOLE pair, the region this one
12214 // chroma transform covers.
12215 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
12216 for (plane, _buf, levels, tx_type) in [
12217 (1usize, &mut *u, &u_levels, u_tx_type),
12218 (2, &mut *v, &v_levels, v_tx_type),
12219 ] {
12220 let residual = dequant_and_inverse_typed_wh(
12221 levels,
12222 cw,
12223 ch,
12224 crate::decode::bit_depth(fctx),
12225 block_q_idx(fctx),
12226 plane_q_delta(plane, fctx).0,
12227 plane_q_delta(plane, fctx).1,
12228 tx_type,
12229 );
12230 if let Some((ub, vb)) = &palette_uv_bufs {
12231 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
12232 }
12233 push_intra_rect(plane,
12234 cpx,
12235 cpy,
12236 cw,
12237 ch,
12238 uv_predict_mode,
12239 angle_delta_uv,
12240 pair_reach,
12241 &residual,
12242 alpha
12243 .zip(ac)
12244 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
12245 None,
12246 smooth_neighbor_uv, fctx,
12247 );
12248 }
12249 (u_levels, v_levels)
12250 };
12251 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, uv_predict_mode);
12252 // The chroma planes' coefficient context, over the PAIR's mi span
12253 // (`decode_leaf_rect8`'s own rule: a subsampled plane's bound is
12254 // the luma one rounded up to its 4x4 unit).
12255 let u_state = neighbour_state(&u_levels);
12256 let v_state = neighbour_state(&v_levels);
12257 let round_up_even = |n: usize| n.div_ceil(2) * 2;
12258 let bound_h = round_up_even(neighbours.mi_rows);
12259 let bound_w = round_up_even(neighbours.mi_cols);
12260 for cell in 0..(ph / MI) {
12261 if pair_mi.0 + cell < bound_h
12262 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
12263 {
12264 slot[1] = u_state;
12265 slot[2] = v_state;
12266 }
12267 }
12268 for cell in 0..(pw / MI) {
12269 if pair_mi.1 + cell < bound_w
12270 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
12271 {
12272 slot[1] = u_state;
12273 slot[2] = v_state;
12274 }
12275 }
12276 last_uv_mode = Some(uv_predict_mode);
12277 }
12278 if horz {
12279 hit!(RECT4_16_HORZ_HITS);
12280 } else {
12281 hit!(RECT4_16_VERT_HITS);
12282 }
12283 let (pal_y_size, pal_y_colors) =
12284 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12285 let (pal_uv_size, pal_uv_colors) =
12286 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12287 record_strip_palette(
12288 neighbours, lmi, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
12289 );
12290 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
12291 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
12292 // frame): the above row records `tx_size_wide` over the block's width and
12293 // the left column `tx_size_high` over its height. This 1:4 strip reader is
12294 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
12295 // and it published neither band -- so the block after a 64x16 strip read
12296 // the row's init value 64 as its left transform height and took
12297 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
12298 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
12299 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
12300 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
12301 Ok((mode, last_uv_mode, (tx_w, tx_h)))
12302}
12303
12304
12305/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
12306/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
12307/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
12308/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
12309/// cap, so LUMA needs the same corner truncation [`decode_block`] already
12310/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
12311/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
12312/// this function's own charter/report), so both strips read a real 32x32
12313/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
12314/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
12315/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
12316/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
12317/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
12318/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
12319/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
12320/// that function, only the single-transform-unit (`tx_depth == 0`) case is
12321/// supported: a split transform refuses by name rather than guess-decode.
12322#[allow(clippy::too_many_arguments)]
12323fn decode_block_rect64(
12324 dec: &mut SymbolDecoder,
12325 cdfs: &mut Cdfs,
12326 neighbours: &mut Neighbours,
12327 at: (usize, usize),
12328 bw: usize,
12329 bh: usize,
12330 y: &mut PlaneBuf<'static>,
12331 u: &mut PlaneBuf<'static>,
12332 v: &mut PlaneBuf<'static>,
12333 enable_filter_intra: bool,
12334 allow_screen_content_tools: bool,
12335 base_q_idx: u8,
12336 tx_select: bool,
12337 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
12338) -> Result<()> {
12339 let (r, c) = at;
12340 let (px, py) = (c * SUB, r * SUB);
12341 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
12342 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
12343 let palette_uv_cache = neighbours.palette_uv_cache(at);
12344 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
12345 read_intra_mode_rect(
12346 dec,
12347 cdfs,
12348 nb_above_mode,
12349 nb_left_mode,
12350 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
12351 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
12352 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
12353 // correct), CFL must never be offered here -- passing `true`
12354 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
12355 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
12356 // from this block's very first symbol (lane-sbpart r3 bisect).
12357 false,
12358 true,
12359 bw,
12360 bh,
12361 enable_filter_intra,
12362 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
12363 allow_screen_content_tools,
12364 Some((palette_ctx, &palette_cache)),
12365 &palette_uv_cache,
12366 r * (SUB / MI),
12367 c * (SUB / MI), fctx,
12368 )?;
12369 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
12370 // lane-t900 r34: a non-skip palette block on a superblock-level strip
12371 // -- counted so its gate cannot go vacuous (this was a refusal until
12372 // r34; see the gate `a_real_aomenc_palette_stream_with_8x8_leaves_
12373 // decodes_pixel_exact`).
12374 hit!(PALETTE_SB_STRIP_HITS);
12375 }
12376 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
12377 if smooth_neighbor {
12378 hit!(SMOOTH_LUMA_HITS);
12379 }
12380 let smooth_neighbor_uv =
12381 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
12382 if filter_intra.is_some() {
12383 // `filter_intra_size_class_rect` already returns `None` for both
12384 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
12385 // 32 on both axes), so this symbol is never read at this level --
12386 // kept only as the same defensive refusal [`decode_block_rect`] has.
12387 return Err(unsupported(
12388 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
12389 av1_filter_intra_allowed_bsize caps at 32x32)",
12390 ));
12391 }
12392 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
12393 DC_PRED
12394 } else {
12395 uv_mode
12396 };
12397 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
12398 let depth = if tx_select {
12399 // lane-t900 r2: on an INTER frame `get_tx_size_context` reads the real
12400 // `TXFM_CONTEXT` bands ([`tx_size_context_txfm_rect`], what the 2:1 and
12401 // the 16x4 intra-in-inter strips already do); the key frame's
12402 // deblock-grid approximation is only right where those bands were never
12403 // written. Measured on the 10-bit 1920x792 128-superblock stream,
12404 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
12405 // `tx_size_cat2` row 1 where libaom reads row 2.
12406 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
12407 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx)
12408 } else {
12409 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
12410 };
12411 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
12412 // counts `sub_tx_size_map` steps from the block's own max rect
12413 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
12414 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
12415 // steps, so this level's category is 3 (the same one a 64x64 square
12416 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
12417 // here was a wrong-table read of a real symbol.
12418 let d = dec.symbol(&mut cdfs.tx_size_cat3[ctx]);
12419 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
12420 eprintln!(
12421 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=3 rng={}",
12422 dec.debug_state().0
12423 );
12424 }
12425 d
12426 } else {
12427 0
12428 };
12429 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
12430 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
12431 publish_txfm_bands_if_in_inter(
12432 neighbours,
12433 (mi_r, mi_c),
12434 depth_to_tx_wh(bw, bh, depth, fctx),
12435 (bw, bh), fctx,
12436 );
12437 if depth != 0 || lossless(fctx) {
12438 hit!(TX_DEPTH_HITS);
12439 // lane-rectsplit r1/r4: the superblock-level strip splits its
12440 // transform through the very same per-unit path as its 32x32-level
12441 // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64
12442 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
12443 // measured the old square formula mis-tiling exactly that strip).
12444 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
12445 if bw.max(bh) / bw.min(bh) == 4 {
12446 let which = if depth == 1 {
12447 &RECT4_SPLIT_DEPTH1_HITS
12448 } else {
12449 &RECT4_SPLIT_DEPTH2_HITS
12450 };
12451 hit_do! { which.with(|c| c.set(c.get() + 1)); }
12452 }
12453 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
12454 eprintln!(
12455 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
12456 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
12457 angle_y={angle_delta_y}"
12458 );
12459 }
12460 let modes = RectStripModes {
12461 skip,
12462 mode,
12463 angle_delta_y,
12464 uv_predict_mode,
12465 angle_delta_uv,
12466 alpha,
12467 filter_intra,
12468 smooth_neighbor,
12469 smooth_neighbor_uv,
12470 palette_y: palette_y
12471 .as_ref()
12472 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
12473 palette_uv: palette_uv.as_ref().map(|p| {
12474 (
12475 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
12476 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
12477 )
12478 }),
12479 };
12480 if palette_y.is_some() || palette_uv.is_some() {
12481 hit!(PALETTE_SPLIT_TX_HITS);
12482 }
12483 decode_rect_split(
12484 dec,
12485 cdfs,
12486 neighbours,
12487 (mi_r, mi_c),
12488 bw,
12489 bh,
12490 tx_w,
12491 tx_h,
12492 &modes,
12493 y,
12494 u,
12495 v,
12496 base_q_idx,
12497 reduced_tx_set, fctx,
12498 )?;
12499 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
12500 // (lane-palette2 r10): this return skips the fn's own tail, so a
12501 // split-tx superblock strip would otherwise leave the above/left
12502 // palette arrays holding a dead block's colours.
12503 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12504 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
12505 let (puv_size, puv_colors) =
12506 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12507 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
12508 // lane-frame36 r2: `set_txfm_ctxs` runs for EVERY block and this early
12509 // return skips the fn's own tail, so a SPLIT superblock-level strip
12510 // published no TXFM_CONTEXT band and the next block read the row's init
12511 // value 64 as its left transform height. Measured on the 10-bit
12512 // 3840x1608 stream, decode-order frame 33: after the split 16x64 strip
12513 // at mi(192,140) (`tx_depth=1` -> TX_16X32) the 32x64 block at
12514 // mi(192,144) took `tx_size_cat3` row 2 where libaom takes row 1. The
12515 // bands carry the SPLIT unit's size, not the block's.
12516 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
12517 hit!(RECT64_SPLIT_TXFM_PUBLISH_HITS);
12518 hit!(RECT_PARTITION_HITS);
12519 return Ok(());
12520 }
12521 let (tx_w, tx_h) = (bw, bh);
12522 let (cpx, cpy) = (px / 2, py / 2);
12523 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
12524 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
12525 if let Some(ref pyv) = palette_y {
12526 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
12527 set_palette_pred(buf, fctx);
12528 }
12529 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
12530 (
12531 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
12532 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
12533 )
12534 });
12535 if skip {
12536 push_intra_rect(0,
12537 px,
12538 py,
12539 bw,
12540 bh,
12541 mode,
12542 angle_delta_y,
12543 reach,
12544 &ZERO_RESIDUAL[..bw * bh],
12545 None,
12546 filter_intra,
12547 smooth_neighbor, fctx,
12548 );
12549 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
12550 if let Some((ub, _)) = &palette_uv_bufs {
12551 set_palette_pred(ub.clone(), fctx);
12552 }
12553 push_intra_rect(1,
12554 cpx,
12555 cpy,
12556 chroma_w,
12557 chroma_h,
12558 uv_predict_mode,
12559 angle_delta_uv,
12560 reach,
12561 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12562 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
12563 None,
12564 smooth_neighbor_uv, fctx,
12565 );
12566 if let Some((_, vb)) = &palette_uv_bufs {
12567 set_palette_pred(vb.clone(), fctx);
12568 }
12569 push_intra_rect(2,
12570 cpx,
12571 cpy,
12572 chroma_w,
12573 chroma_h,
12574 uv_predict_mode,
12575 angle_delta_uv,
12576 reach,
12577 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12578 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
12579 None,
12580 smooth_neighbor_uv, fctx,
12581 );
12582 neighbours.record_rect(
12583 at,
12584 bw,
12585 bh,
12586 mode,
12587 uv_predict_mode,
12588 &[
12589 &ZERO_RESIDUAL[..bw * bh],
12590 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12591 &ZERO_RESIDUAL[..chroma_w * chroma_h],
12592 ],
12593 );
12594 } else {
12595 let around = neighbours.around_rect(at, bw, bh);
12596 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
12597 // (see this function's own doc comment). A 64-length axis codes only
12598 // its low 32 coefficients, so the corner is `min(bw, 32)` x
12599 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
12600 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
12601 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
12602 let scan32 = default_scan(TX32);
12603 if coeff_trace_on() {
12604 let (rng, _) = dec.debug_state();
12605 eprintln!("EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}");
12606 }
12607 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
12608 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
12609 read_coeffs(
12610 dec,
12611 &mut luma_coding,
12612 &scan32,
12613 0,
12614 dc_sign_ctx(around[0].2),
12615 TxType::DctDct,
12616 Some((bw, bh)),
12617 )?
12618 } else {
12619 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
12620 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
12621 // (`scan.c`) gives both the very same `default_scan_32x16` /
12622 // `default_scan_16x32` the 2:1 sizes use ("Half of the
12623 // coefficients of tx64 at higher frequencies are set to zeros. So
12624 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
12625 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
12626 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
12627 // 512-position eob group) -- BOTH identical to TX_32X16, so the
12628 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
12629 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
12630 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
12631 // what `base_ctx_rect` computes at (32, 16).
12632 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
12633 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
12634 read_coeffs_rect(
12635 dec,
12636 &mut luma_coding,
12637 luma_scan,
12638 luma_cw,
12639 luma_ch,
12640 0,
12641 dc_sign_ctx(around[0].2),
12642 TxType::DctDct,
12643 )?
12644 };
12645 if coeff_trace_on() {
12646 let (rng, _) = dec.debug_state();
12647 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
12648 }
12649 let mut luma_levels = vec![0i32; bw * bh];
12650 for row in 0..luma_ch {
12651 luma_levels[row * bw..][..luma_cw]
12652 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
12653 }
12654 {
12655 let cur = block_q_idx(fctx);
12656 if cur != i32::from(base_q_idx) {
12657 hit!(RECT64_QIDX_DRIFT_HITS);
12658 }
12659 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12660 eprintln!(
12661 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
12662 );
12663 }
12664 }
12665 let luma_residual = dequant_and_inverse_typed_wh(
12666 &luma_levels,
12667 bw,
12668 bh,
12669 crate::decode::bit_depth(fctx),
12670 block_q_idx(fctx),
12671 plane_q_delta(0, fctx).0,
12672 plane_q_delta(0, fctx).1,
12673 luma_tx_type,
12674 );
12675 push_intra_rect(0,
12676 px,
12677 py,
12678 bw,
12679 bh,
12680 mode,
12681 angle_delta_y,
12682 reach,
12683 &luma_residual,
12684 None,
12685 filter_intra,
12686 smooth_neighbor, fctx,
12687 );
12688 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
12689 let leftcol: Vec<u16> = if px > 0 {
12690 (py..py + bh).map(|row| y.data[row * y.width + px - 1]).collect()
12691 } else {
12692 vec![]
12693 };
12694 eprintln!(
12695 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
12696 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
12697 luma_corner.iter().any(|&v| v != 0),
12698 &y.data[py * y.width + px..][..bw],
12699 leftcol,
12700 );
12701 }
12702 // CHROMA: a real, untruncated chroma_w x chroma_h transform -- no
12703 // corner crop needed (see doc comment).
12704 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
12705 // The chroma plane is never truncated (both axes <= 32 after
12706 // subsampling). Under a 1:4 strip it is a true 32x8/8x32:
12707 // `get_txsize_entropy_ctx(TX_32X8)` = (TX_8X8 + TX_32X32 + 1) >> 1 =
12708 // TX_16X16 and `txsize_log2_minus4[TX_32X8]` = 4 (256 positions),
12709 // both identical to TX_16X16 -- so [`TxbSet::Chroma16`] is the exact
12710 // set, and only the scan is new (lane-tx64x16).
12711 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (bw, bh) {
12712 (64, 16) => (TxbSet::Chroma16, &SCAN_32X8),
12713 (16, 64) => (TxbSet::Chroma16, &SCAN_8X32),
12714 (64, _) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
12715 _ => (TxbSet::ChromaRect32x16, &SCAN_16X32),
12716 };
12717 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
12718 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
12719 if coeff_trace_on() {
12720 let (rng, _) = dec.debug_state();
12721 eprintln!("EC_COEFF plane=1 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
12722 }
12723 let (u_levels, u_tx_type) = read_coeffs_rect(
12724 dec,
12725 &mut u_coding,
12726 chroma_scan,
12727 chroma_w,
12728 chroma_h,
12729 u_skip_ctx,
12730 dc_sign_ctx(around[1].2),
12731 TxType::DctDct,
12732 )?;
12733 if coeff_trace_on() {
12734 let (rng, _) = dec.debug_state();
12735 eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}");
12736 }
12737 {
12738 let cur = block_q_idx(fctx);
12739 if cur != i32::from(base_q_idx) {
12740 hit!(RECT64_QIDX_DRIFT_HITS);
12741 }
12742 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12743 eprintln!(
12744 "TRACE rect64_dequant plane=1 base_q_idx={base_q_idx} current_q_idx={cur}"
12745 );
12746 }
12747 }
12748 let u_residual = dequant_and_inverse_typed_wh(
12749 &u_levels,
12750 chroma_w,
12751 chroma_h,
12752 crate::decode::bit_depth(fctx),
12753 block_q_idx(fctx),
12754 plane_q_delta(1, fctx).0,
12755 plane_q_delta(1, fctx).1,
12756 u_tx_type,
12757 );
12758 // lane-t900 r34: the UV-palette prediction override, exactly as the
12759 // `skip` arm above installs it. The [`PALETTE_PRED`] slot is a
12760 // set-then-take, so it must be filled again right before each plane's
12761 // own reconstruct; leaving this out of the non-skip arm predicted a
12762 // palette block's chroma off its block edges (measured: testsrc2
12763 // 128x128 10-bit cq55 `--tile-columns=1`, the 32x64 strip at px=96 --
12764 // luma exact, both chroma planes wrong over its whole 16x32).
12765 if let Some((ub, _)) = &palette_uv_bufs {
12766 set_palette_pred(ub.clone(), fctx);
12767 }
12768 push_intra_rect(1,
12769 cpx,
12770 cpy,
12771 chroma_w,
12772 chroma_h,
12773 uv_predict_mode,
12774 angle_delta_uv,
12775 reach,
12776 &u_residual,
12777 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
12778 None,
12779 smooth_neighbor_uv, fctx,
12780 );
12781 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
12782 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
12783 if coeff_trace_on() {
12784 let (rng, _) = dec.debug_state();
12785 eprintln!("EC_COEFF plane=2 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
12786 }
12787 let (v_levels, v_tx_type) = read_coeffs_rect(
12788 dec,
12789 &mut v_coding,
12790 chroma_scan,
12791 chroma_w,
12792 chroma_h,
12793 v_skip_ctx,
12794 dc_sign_ctx(around[2].2),
12795 TxType::DctDct,
12796 )?;
12797 if coeff_trace_on() {
12798 let (rng, _) = dec.debug_state();
12799 eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}");
12800 }
12801 {
12802 let cur = block_q_idx(fctx);
12803 if cur != i32::from(base_q_idx) {
12804 hit!(RECT64_QIDX_DRIFT_HITS);
12805 }
12806 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12807 eprintln!(
12808 "TRACE rect64_dequant plane=2 base_q_idx={base_q_idx} current_q_idx={cur}"
12809 );
12810 }
12811 }
12812 let v_residual = dequant_and_inverse_typed_wh(
12813 &v_levels,
12814 chroma_w,
12815 chroma_h,
12816 crate::decode::bit_depth(fctx),
12817 block_q_idx(fctx),
12818 plane_q_delta(2, fctx).0,
12819 plane_q_delta(2, fctx).1,
12820 v_tx_type,
12821 );
12822 if let Some((_, vb)) = &palette_uv_bufs {
12823 set_palette_pred(vb.clone(), fctx);
12824 }
12825 push_intra_rect(2,
12826 cpx,
12827 cpy,
12828 chroma_w,
12829 chroma_h,
12830 uv_predict_mode,
12831 angle_delta_uv,
12832 reach,
12833 &v_residual,
12834 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
12835 None,
12836 smooth_neighbor_uv, fctx,
12837 );
12838 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
12839 hit!(RECT_COEFF_HITS);
12840 }
12841 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12842 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
12843 let (puv_size, puv_colors) =
12844 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12845 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
12846 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
12847 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
12848 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
12849 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
12850 // frame): the above row records `tx_size_wide` over the block's width and
12851 // the left column `tx_size_high` over its height. This 1:4 strip reader is
12852 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
12853 // and it published neither band -- so the block after a 64x16 strip read
12854 // the row's init value 64 as its left transform height and took
12855 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
12856 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
12857 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
12858 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
12859 hit!(SB_RECT_HITS);
12860 match (bw, bh) {
12861 (64, 16) => hit!(SB_RECT4_HORZ_HITS),
12862 (16, 64) => hit!(SB_RECT4_VERT_HITS),
12863 _ => {}
12864 }
12865 if crate::envflags::env_flag!("EC_AV1_TRACE") {
12866 let (rng, _) = dec.debug_state();
12867 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
12868 }
12869 Ok(())
12870}
12871
12872/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
12873/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
12874/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
12875/// it lands away from zero, for gate tests to prove a real stream fired one.
12876fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
12877 let symbol = dec.symbol(cdf);
12878 if symbol != ANGLE_DELTA_ZERO {
12879 hit!(ANGLE_DELTA_HITS);
12880 }
12881 symbol as i32 - ANGLE_DELTA_ZERO as i32
12882}
12883
12884#[allow(clippy::too_many_arguments)]
12885fn read_intra_mode(
12886 dec: &mut SymbolDecoder,
12887 cdfs: &mut Cdfs,
12888 above_mode: usize,
12889 left_mode: usize,
12890 cfl: bool,
12891 side: usize,
12892 enable_filter_intra: bool,
12893 skip_ctx: usize,
12894 allow_screen_content_tools: bool,
12895 allow_intrabc: bool,
12896 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
12897 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
12898 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
12899 // `None` at the excluded call sites (the 8x8-leaf path), which still read
12900 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
12901 // decoder reads either way -- but refuse by name the moment it fires,
12902 // exactly the old behaviour.
12903 palette: Option<(usize, &[u16])>,
12904 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
12905 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
12906 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
12907 // `use_palette_y`, not a neighbour lookup).
12908 palette_uv_cache: &[u16],
12909 mi_r: usize,
12910 mi_c: usize, fctx: &crate::decode::FrameCtx,
12911) -> Result<(
12912 bool,
12913 usize,
12914 i32,
12915 usize,
12916 i32,
12917 Option<(i32, i32)>,
12918 Option<usize>,
12919 Option<PaletteY>,
12920 Option<PaletteUv>,
12921)> {
12922 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
12923 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
12924 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
12925 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
12926 // line against the instrumented aomdec, not just `tell()`.
12927 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
12928 if ec_istep {
12929 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
12930 // (decodemv.c:818), printed at the same point: before the first
12931 // mode-info symbol of the block, so a cross-decoder range ladder can
12932 // be keyed on the BLOCK, not just on the symbol sequence.
12933 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}", dec.debug_state().0);
12934 }
12935 macro_rules! istep {
12936 ($name:literal, $val:expr) => {
12937 if ec_istep {
12938 let (rng, _) = dec.debug_state();
12939 eprintln!(
12940 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
12941 $name, $val
12942 );
12943 }
12944 };
12945 }
12946 // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single
12947 // point every square caller routes through (see `read_intra_mode_rect`).
12948 let cfl = if cfl && side > 32 {
12949 hit!(NOCFL_UV_MODE_HITS);
12950 false
12951 } else {
12952 cfl
12953 };
12954 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
12955 // `skip` when `SegIdPreSkip`, and after it otherwise.
12956 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
12957 if seg_id_pre_skip(fctx) {
12958 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
12959 }
12960 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
12961 if trace {
12962 eprintln!("TRACE skip value={} rng={}", skip as i32, dec.debug_state().0);
12963 }
12964 istep!("skip", skip as i32);
12965 if !seg_id_pre_skip(fctx) {
12966 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
12967 }
12968 // spec order (see the comment below on `read_intrabc_info`): `skip`,
12969 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
12970 maybe_read_cdef_idx(dec, mi_r, mi_c, skip, fctx);
12971 istep!("cdef", 0);
12972 // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not
12973 // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole
12974 // superblock and skips `delta_q` exactly like a 64 one under a 64 root.
12975 let whole_sb = side == sb_mi_cur(fctx) as usize * 4;
12976 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
12977 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
12978 istep!("dq", 0);
12979 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
12980 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
12981 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
12982 // intra frame whose header set `allow_intrabc`. Actual intra block copy
12983 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
12984 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
12985 // draws the line at consuming this one flag symbol and refusing by name
12986 // when it fires, so the arithmetic decoder still resyncs for a stream
12987 // that merely allows (but never uses) intrabc.
12988 if allow_intrabc {
12989 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
12990 if trace {
12991 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
12992 }
12993 if use_intrabc {
12994 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, side, fctx);
12995 if trace {
12996 eprintln!("TRACE intrabc dv={dv:?}");
12997 }
12998 fctx.intrabc_dv.with(|c| c.set(Some(dv)));
12999 hit!(INTRABC_HITS);
13000 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
13001 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
13002 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
13003 // `DC_PRED` (which is also what the neighbour mode contexts and
13004 // the loop filter then see).
13005 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
13006 }
13007 }
13008 let above_ctx = INTRA_MODE_CTX[above_mode];
13009 let left_ctx = INTRA_MODE_CTX[left_mode];
13010 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
13011 if trace {
13012 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
13013 }
13014 istep!("mode", mode as i32);
13015 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
13016 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
13017 if trace {
13018 eprintln!(
13019 "TRACE angle_delta value={}",
13020 delta + ANGLE_DELTA_ZERO as i32
13021 );
13022 }
13023 delta
13024 } else {
13025 0
13026 };
13027 istep!("angle_y", angle_delta_y);
13028 // lane-sb128c r3 (class sweep): `is_cfl_allowed` on the luma bsize, decided
13029 // here so every `decode_block` caller (64x64 and 128x128 roots included)
13030 // picks the right alphabet -- see [`read_intra_mode_rect`]'s twin.
13031 let cfl = cfl && cfl_allowed_px(side, side, fctx);
13032 let uv_mode = if cfl {
13033 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
13034 } else {
13035 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
13036 };
13037 if trace {
13038 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}", dec.debug_state().0);
13039 }
13040 istep!("uv_mode", uv_mode as i32);
13041 let alpha = if cfl && uv_mode == UV_CFL_PRED {
13042 Some(read_cfl_alphas(dec, cdfs))
13043 } else {
13044 None
13045 };
13046 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
13047 // from this lane's directional chroma: a corner block with neither
13048 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
13049 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
13050 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
13051 // bug in that fallback this lane's own scope does not cover. Keep it
13052 // refused here rather than ship a silently-wrong decode.
13053 if (9..=12).contains(&uv_mode) {
13054 hit!(SMOOTH_UV_HITS);
13055 }
13056 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
13057 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
13058 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
13059 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
13060 // the `else` branch below and never reads one either way.
13061 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
13062 hit!(DIRECTIONAL_UV_HITS);
13063 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
13064 } else {
13065 0
13066 };
13067 istep!("angle_uv", angle_delta_uv);
13068 if angle_delta_uv != 0 {
13069 hit!(UV_ANGLE_DELTA_HITS);
13070 }
13071 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
13072 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
13073 // gated by `av1_allow_palette` (blockd.h -- size bound only,
13074 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
13075 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
13076 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
13077 // read the same CDF row whenever every neighbour really is non-palette).
13078 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
13079 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
13080 // neighbour lookup at all), so it is exact even at the excluded call
13081 // sites once Y decodes real syntax there too.
13082 //
13083 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
13084 // inline from `read_palette_mode_info` -- it runs later, from
13085 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
13086 // after the WHOLE mode-info read for the block, including UV palette
13087 // mode_info (`read_palette_mode_info`'s own second half, right below)
13088 // and `read_filter_intra_mode_info`. So this branch now only reads
13089 // mode/size/colours for both planes (deferring the two colour-index-map
13090 // decodes to after `filter_intra`, below) -- r6's range trace pinned
13091 // this exact ordering bug (`compare-range-not-tell`: ranges matched
13092 // bit-for-bit through the Y colours, diverged only at the old inline
13093 // `decode_color_index_map` call).
13094 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
13095 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
13096 if allow_screen_content_tools
13097 && let Some(bsize_ctx) = palette_bsize_ctx(side)
13098 {
13099 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
13100 if mode == DC_PRED {
13101 if trace {
13102 let (rng, _) = dec.debug_state();
13103 eprintln!(
13104 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
13105 );
13106 }
13107 }
13108 let use_palette_y =
13109 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
13110 if mode == DC_PRED && trace {
13111 let (rng, _) = dec.debug_state();
13112 eprintln!("TRACE palette_y_mode value={} rng={rng}", use_palette_y as i32);
13113 }
13114 if use_palette_y {
13115 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
13116 if trace {
13117 let (rng, _) = dec.debug_state();
13118 eprintln!("TRACE palette_y_size n={n} rng={rng}");
13119 }
13120 let colors = read_palette_colors_y(dec, n, cache, fctx);
13121 if trace {
13122 let (rng, _) = dec.debug_state();
13123 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
13124 }
13125 palette_y_pending = Some((n, colors));
13126 }
13127 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
13128 // unconditionally at this bit position whenever `uv_mode ==
13129 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
13130 // scope always reconstructs chroma alongside luma (`decode_block`
13131 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
13132 // is always true here and does not need threading in.
13133 let palette_uv_mode_ctx = usize::from(use_palette_y);
13134 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
13135 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
13136 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
13137 palette_uv_pending = Some((n, u_colors, v_colors));
13138 }
13139 }
13140 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
13141 // `use_filter_intra` symbol this decoder never read at all until
13142 // lane-av1real r10 -- silently skipping it left every bit past a
13143 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
13144 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
13145 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
13146 // symbol's bits were never consumed).
13147 let mut filter_intra = None;
13148 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
13149 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
13150 // `use_filter_intra` symbol for a Y-palette block, and reading one here
13151 // desynced every screen-content stream from the first palette block on
13152 // (it surfaced as a bogus "partition below 8x8" refusal further down the
13153 // tile).
13154 if mode == DC_PRED
13155 && enable_filter_intra
13156 && palette_y_pending.is_none()
13157 && let Some(class) = filter_intra_size_class(side)
13158 {
13159 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
13160 if trace {
13161 eprintln!(
13162 "TRACE use_filter_intra side={side} rng={} value={}", dec.debug_state().0,
13163 use_filter_intra as i32
13164 );
13165 }
13166 istep!("use_filter_intra", use_filter_intra as i32);
13167 if use_filter_intra {
13168 hit!(FILTER_INTRA_HITS);
13169 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
13170 if trace {
13171 eprintln!("TRACE filter_intra_mode value={fi_mode}");
13172 }
13173 istep!("filter_intra_mode", fi_mode as i32);
13174 filter_intra = Some(fi_mode);
13175 }
13176 }
13177 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
13178 // shared U/V map) -- the same order libaom's own loop visits them in.
13179 let palette_y = palette_y_pending.map(|(n, colors)| {
13180 let map = decode_color_index_map(dec, cdfs, n, side, false);
13181 hit!(PALETTE_HITS);
13182 if trace {
13183 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
13184 }
13185 PaletteY { size: n, colors, map }
13186 });
13187 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
13188 let map = decode_color_index_map(dec, cdfs, n, side / 2, true);
13189 hit!(PALETTE_UV_HITS);
13190 if trace {
13191 eprintln!(
13192 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
13193 &u_colors[..n],
13194 &v_colors[..n]
13195 );
13196 }
13197 PaletteUv { size: n, u_colors, v_colors, map }
13198 });
13199 Ok((
13200 skip,
13201 mode,
13202 angle_delta_y,
13203 uv_mode,
13204 angle_delta_uv,
13205 alpha,
13206 filter_intra,
13207 palette_y,
13208 palette_uv,
13209 ))
13210}
13211
13212/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
13213/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
13214/// intra modes.
13215const UV_CFL_PRED: usize = 13;
13216
13217/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
13218/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
13219/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
13220/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
13221/// joint sign the same way. Returns each plane's final signed `alpha_q3`
13222/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
13223fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
13224 hit!(CFL_BLOCK_HITS);
13225 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
13226 let sign_u = ((joint_sign + 1) * 11) >> 5;
13227 let sign_v = (joint_sign + 1) - 3 * sign_u;
13228 let alpha_u = if sign_u == 0 {
13229 0
13230 } else {
13231 let ctx_u = (joint_sign + 1 - 3) as usize;
13232 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
13233 if sign_u == 2 { mag } else { -mag }
13234 };
13235 let alpha_v = if sign_v == 0 {
13236 0
13237 } else {
13238 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
13239 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
13240 if sign_v == 2 { mag } else { -mag }
13241 };
13242 (alpha_u, alpha_v)
13243}
13244
13245/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
13246/// the reconstructed luma samples under a `side`-square block, subsampled
13247/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
13248/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
13249/// to give the AC values [`cfl_scaled`] scales by alpha.
13250fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec<i32> {
13251 cfl_ac_q3_at(px, py, side, side, |lx, ly| i32::from(y.data[ly * y.width + lx]))
13252}
13253
13254/// The one body [`cfl_ac_q3`] and [`cfl_ac_q3_rect`] share, reading its luma
13255/// samples through `sample(x, y)` instead of a [`PlaneBuf`] -- so the encoder
13256/// (lane-av1cfl) builds a CfL candidate's AC signal from its own `u8`
13257/// reconstruction through THIS function rather than a second transcription of
13258/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c`.
13259pub(crate) fn cfl_ac_q3_at(
13260 px: usize,
13261 py: usize,
13262 bw: usize,
13263 bh: usize,
13264 sample: impl Fn(usize, usize) -> i32,
13265) -> Vec<i32> {
13266 let (cw, ch) = (bw / 2, bh / 2);
13267 let mut ac = vec![0i32; cw * ch];
13268 let mut sum = 0i32;
13269 for cy in 0..ch {
13270 for cx in 0..cw {
13271 let (lx, ly) = (px + cx * 2, py + cy * 2);
13272 let q3 = (sample(lx, ly)
13273 + sample(lx + 1, ly)
13274 + sample(lx, ly + 1)
13275 + sample(lx + 1, ly + 1))
13276 << 1;
13277 ac[cy * cw + cx] = q3;
13278 sum += q3;
13279 }
13280 }
13281 let num_pel = (cw * ch) as i32;
13282 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
13283 ac.iter_mut().for_each(|v| *v -= avg);
13284 ac
13285}
13286
13287/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
13288/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
13289/// ties away from zero on the shifted-out sign).
13290pub(crate) fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
13291 let v = alpha_q3 * ac_q3;
13292 if v >= 0 {
13293 (v + 32) >> 6
13294 } else {
13295 -((-v + 32) >> 6)
13296 }
13297}
13298
13299/// One plane's reconstruction buffer, `width * height` samples, and the
13300/// prediction/residual reads and writes into it — the decode-side twin of
13301/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
13302/// (own-edge and reach clamps both), passing what it gathers straight to
13303/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
13304/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
13305/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
13306/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of
13307/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) --
13308/// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE).
13309/// lane-mc64 r1: the decode-order index the stage dumps below key their file
13310/// name on. `PREFILT_PICTURE_IDX` is bumped once per frame just BEFORE the
13311/// deblock/CDEF stages run, so the frame being dumped here is `idx - 1` --
13312/// without this every frame overwrote `.f0` and a per-frame bisection silently
13313/// compared the LAST decoded frame (ledger, class stale-output-faked-measurement).
13314#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
13315fn stage_dump_idx() -> usize {
13316 PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst).saturating_sub(1)
13317}
13318
13319fn dump_stage16(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>, fw: usize, fh: usize) {
13320 use std::io::Write;
13321 // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by
13322 // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed
13323 // `.f0` name kept only the LAST frame, so a mid-sequence divergence could
13324 // not be read out at all.
13325 if let Ok(path) = crate::envflags::var(var)
13326 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
13327 {
13328 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))] {
13329 for row in 0..h {
13330 let mut bytes = Vec::with_capacity(w * 2);
13331 for &s in &p.data[row * p.width..][..w] {
13332 bytes.extend_from_slice(&s.to_le_bytes());
13333 }
13334 let _ = f.write_all(&bytes);
13335 }
13336 }
13337 }
13338}
13339
13340/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a
13341/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so
13342/// every frame overwrote the previous one and only the LAST frame survived,
13343/// which silently defeats any per-frame filter-stage bisection.
13344fn dump_stage_idx(var: &str) -> usize {
13345 use std::collections::HashMap;
13346 use std::sync::{Mutex, OnceLock};
13347 static IDX: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new();
13348 let mut m = IDX.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap();
13349 let e = m.entry(var.to_string()).or_insert(0);
13350 let i = *e;
13351 *e += 1;
13352 i
13353}
13354
13355fn dump_stage(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
13356 use std::io::Write;
13357 if let Ok(path) = crate::envflags::var(var)
13358 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
13359 {
13360 for p in [y, u, v] {
13361 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
13362 let _ = f.write_all(&narrow);
13363 }
13364 }
13365}
13366
13367/// The value [`fresh_plane`] fills with under `EC_AV1_PLANE_SENTINEL`: no
13368/// legal sample can equal it (reconstruction clamps to `(1 << bit_depth) - 1`,
13369/// at most 4095), so a decode that hashes identically under the flag proves
13370/// the output does not depend on the plane buffer's initial content.
13371const PLANE_SENTINEL: u16 = 0xDEAD;
13372
13373/// A frame plane's own backing store, `n` samples, UNINITIALISED.
13374///
13375/// (lane-picalloc) The SB-padded coding surface is written sample-for-sample
13376/// by the tile walk's reconstruction before anything reads it, so the
13377/// `vec![0u16; n]` this replaces spent ~3% of the frame thread's cycles
13378/// zeroing 25 MB (at 4K) that the very next pass overwrites -- serially, at
13379/// the frame's head, on the critical path. `EC_AV1_PLANE_SENTINEL=1` swaps the
13380/// uninitialised buffer for a [`PLANE_SENTINEL`] fill; the gate hashes both
13381/// ways (see the lane report) and the two agree, which is the proof that no
13382/// unwritten sample reaches the output.
13383fn fresh_plane(n: usize) -> Vec<u16> {
13384 if crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL") {
13385 return vec![PLANE_SENTINEL; n];
13386 }
13387 let mut v: Vec<u16> = Vec::with_capacity(n);
13388 // SAFETY: `u16` has no invalid bit patterns and no `Drop`, and the
13389 // capacity was just reserved, so the vector owns `n` initialised-or-not
13390 // `u16` slots. Every one is written by reconstruction before it is read
13391 // (proven by the sentinel gate above).
13392 #[allow(unsafe_code)]
13393 unsafe {
13394 v.set_len(n);
13395 }
13396 v
13397}
13398
13399#[derive(Clone)]
13400struct PlaneBuf<'a> {
13401 data: std::borrow::Cow<'a, [u16]>,
13402 width: usize,
13403 height: usize,
13404 /// The frame's true, decodable extent in this plane's own units — past
13405 /// this, samples are the padded coding surface's invented tail, never a
13406 /// real decoder's edge or reach reads.
13407 true_width: usize,
13408 true_height: usize,
13409 /// This plane's own tile's top-left pixel origin (spec: intra prediction
13410 /// never reaches across a tile boundary even though an earlier-decoded
13411 /// tile's real pixels sit right there in the shared buffer) — set via
13412 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
13413 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
13414 /// is threaded (the two-tile column-split stage 1 fixture's tile always
13415 /// ends at the frame's own right/bottom edge); a non-last tile's own
13416 /// right/bottom reach bound is still open, tracked in the report.
13417 tile_x0: usize,
13418 tile_y0: usize,
13419 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
13420 /// (exclusive) -- a non-last tile column/row's own reach must stop at
13421 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
13422 /// full padded extent) for the single-tile/last-tile case, matching the
13423 /// old unclipped behaviour exactly.
13424 tile_x1: usize,
13425 tile_y1: usize,
13426}
13427
13428/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
13429/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
13430/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
13431/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
13432/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
13433/// `ALTREF2`/`ALTREF`).
13434
13435impl PlaneBuf<'_> {
13436 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
13437 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
13438 /// are already in this plane's own units (luma pixels for `y`, chroma
13439 /// pixels — halved — for `u`/`v`).
13440 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
13441 self.tile_x0 = x0;
13442 self.tile_y0 = y0;
13443 self.tile_x1 = x1;
13444 self.tile_y1 = y1;
13445 }
13446
13447 fn edges(
13448 &self,
13449 x: usize,
13450 y: usize,
13451 side: usize,
13452 reach: Reach,
13453 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
13454 let own_across = x + side.min(self.true_width.saturating_sub(x));
13455 let across = if reach.above_right {
13456 own_across + side.min(self.true_width.saturating_sub(own_across))
13457 } else {
13458 own_across
13459 }
13460 .min(self.width)
13461 .min(self.tile_x1);
13462 let own_down = y + side.min(self.true_height.saturating_sub(y));
13463 let down = if reach.below_left {
13464 own_down + side.min(self.true_height.saturating_sub(own_down))
13465 } else {
13466 own_down
13467 }
13468 .min(self.height)
13469 .min(self.tile_y1);
13470 let above = (y > self.tile_y0 && across > x)
13471 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
13472 let left = (x > self.tile_x0 && down > y).then(|| {
13473 (y..down)
13474 .map(|row| self.data[row * self.width + x - 1])
13475 .collect::<Vec<_>>()
13476 });
13477 let corner =
13478 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
13479 (above, left, corner)
13480 }
13481
13482 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
13483 /// the above/left reach each extend by their OWN axis (`bw` across,
13484 /// `bh` down), not one shared `side`.
13485 fn edges_rect(
13486 &self,
13487 x: usize,
13488 y: usize,
13489 bw: usize,
13490 bh: usize,
13491 reach: Reach,
13492 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
13493 let own_across = x + bw.min(self.true_width.saturating_sub(x));
13494 let across = if reach.above_right {
13495 own_across + bw.min(self.true_width.saturating_sub(own_across))
13496 } else {
13497 own_across
13498 }
13499 .min(self.width)
13500 .min(self.tile_x1);
13501 let own_down = y + bh.min(self.true_height.saturating_sub(y));
13502 let down = if reach.below_left {
13503 own_down + bh.min(self.true_height.saturating_sub(own_down))
13504 } else {
13505 own_down
13506 }
13507 .min(self.height)
13508 .min(self.tile_y1);
13509 let above = (y > self.tile_y0 && across > x)
13510 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
13511 let left = (x > self.tile_x0 && down > y).then(|| {
13512 (y..down)
13513 .map(|row| self.data[row * self.width + x - 1])
13514 .collect::<Vec<_>>()
13515 });
13516 let corner =
13517 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
13518 if matches!((bw, bh), (16, 8) | (8, 16)) {
13519 hit!(RECT_STRIP_PRED_HITS);
13520 if across > own_across || down > own_down {
13521 hit!(RECT_STRIP_REACH_HITS);
13522 }
13523 }
13524 (above, left, corner)
13525 }
13526
13527 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
13528 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
13529 /// already-rect-capable `(bw, bh)` pair.
13530 #[allow(clippy::too_many_arguments)]
13531 #[track_caller]
13532 fn reconstruct_rect(
13533 &mut self,
13534 x: usize,
13535 y: usize,
13536 bw: usize,
13537 bh: usize,
13538 mode: usize,
13539 angle_delta: i32,
13540 reach: Reach,
13541 residual: &[i32],
13542 cfl: Option<(i32, &[i32])>,
13543 filter_intra: Option<usize>,
13544 smooth_neighbor: bool,
13545 // lane-wave1 step (i): the palette/intrabc prediction override, taken
13546 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
13547 // than by this replay.
13548 pred: Option<Vec<u16>>, fctx: &crate::decode::FrameCtx,
13549 ) {
13550 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
13551 // (lane-palette2 r4): a palette block's prediction is the
13552 // reconstructed colour-index map, needing no edge pixels at all.
13553 let prediction = if let Some(buf) = pred {
13554 buf
13555 } else {
13556 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
13557 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
13558 eprintln!(
13559 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
13560 above.as_ref().map(|a| (a.len(), a[0])),
13561 left.as_ref().map(|l| l.len()),
13562 left.as_ref().map(|l| l[0]),
13563 self.tile_x0, self.tile_y0, self.true_width, self.true_height
13564 );
13565 }
13566 let mut prediction = vec![0u16; bw * bh];
13567 if let Some(fi_mode) = filter_intra {
13568 crate::intra::predict_filter_intra(
13569 fi_mode,
13570 above.as_deref(),
13571 left.as_deref(),
13572 corner,
13573 bw,
13574 bh,
13575 &mut prediction, fctx,
13576 );
13577 } else {
13578 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
13579 predict(
13580 mode as u8,
13581 angle_delta,
13582 above.as_deref(),
13583 left.as_deref(),
13584 corner,
13585 bw,
13586 bh,
13587 enable_edge_filter,
13588 smooth_neighbor,
13589 &mut prediction, fctx,
13590 );
13591 }
13592 prediction
13593 };
13594 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
13595 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
13596 if crate::envflags::env_flag!("EC_PRED") {
13597 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
13598 let row0: Vec<u16> = prediction[..bw.min(8)].to_vec();
13599 let col0: Vec<u16> = (0..bh.min(8)).map(|r| prediction[r * bw]).collect();
13600 eprintln!(
13601 "@{} 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)
13602 );
13603 }
13604 let residual = dense_residual(residual, bw * bh);
13605 for row in 0..bh {
13606 // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s
13607 // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame
13608 // whose padded width is not superblock aligned hangs past it.
13609 if y + row >= self.height {
13610 break;
13611 }
13612 for col in 0..bw {
13613 if x + col >= self.width {
13614 break;
13615 }
13616 let idx = row * bw + col;
13617 let mut base = i32::from(prediction[idx]);
13618 if let Some((alpha_q3, ac_q3)) = cfl {
13619 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
13620 }
13621 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
13622 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
13623 }
13624 }
13625 }
13626
13627 /// Predicts under `mode` then adds `residual` (side*side, raster),
13628 /// writing the clamped reconstruction back into the plane at `(x, y)`.
13629 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
13630 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
13631 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
13632 /// order (cfl.c).
13633 #[track_caller]
13634 fn reconstruct(
13635 &mut self,
13636 x: usize,
13637 y: usize,
13638 side: usize,
13639 mode: usize,
13640 angle_delta: i32,
13641 reach: Reach,
13642 residual: &[i32],
13643 cfl: Option<(i32, &[i32])>,
13644 filter_intra: Option<usize>,
13645 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
13646 // libaom `get_filt_type`): true when the block's above OR left
13647 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
13648 // Callers pass their own plane's neighbour-mode check
13649 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
13650 // callers until a smooth/paeth `uv_mode` can reach this call at all
13651 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
13652 // keeps `false` exact for chroma without this fn needing to know why.
13653 smooth_neighbor: bool,
13654 // lane-wave1 step (i): the palette/intrabc prediction override, taken
13655 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
13656 // than by this replay.
13657 pred: Option<Vec<u16>>, fctx: &crate::decode::FrameCtx,
13658 ) {
13659 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
13660 // takes priority over `predict()`/`predict_filter_intra` entirely --
13661 // palette prediction needs no edge pixels at all.
13662 let prediction = if let Some(buf) = pred {
13663 buf
13664 } else {
13665 let (above, left, corner) = self.edges(x, y, side, reach);
13666 let mut prediction = vec![0u16; side * side];
13667 if let Some(fi_mode) = filter_intra {
13668 crate::intra::predict_filter_intra(
13669 fi_mode,
13670 above.as_deref(),
13671 left.as_deref(),
13672 corner,
13673 side,
13674 side,
13675 &mut prediction, fctx,
13676 );
13677 } else {
13678 // `enable_intra_edge_filter` is the sequence header's own flag
13679 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
13680 // call, never per-block) -- threading it through every
13681 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
13682 // dozen sites for a value that never changes mid-decode, so it
13683 // rides a thread-local instead (this decoder is single-threaded
13684 // per stream).
13685 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
13686 predict(
13687 mode as u8,
13688 angle_delta,
13689 above.as_deref(),
13690 left.as_deref(),
13691 corner,
13692 side,
13693 side,
13694 enable_edge_filter,
13695 smooth_neighbor,
13696 &mut prediction, fctx,
13697 );
13698 }
13699 prediction
13700 };
13701 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
13702 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
13703 if crate::envflags::env_flag!("EC_PRED") {
13704 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
13705 let row0: Vec<u16> = prediction[..side.min(8)].to_vec();
13706 let col0: Vec<u16> = (0..side.min(8)).map(|r| prediction[r * side]).collect();
13707 eprintln!(
13708 "@{} 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)
13709 );
13710 }
13711 let residual = dense_residual(residual, side * side);
13712 for row in 0..side {
13713 // lane-sb128c r8: libaom's frame buffer is superblock
13714 // aligned; ours is padded to 32 (`block_grid`), so a 64x64
13715 // transform unit of a 128x64 block at the BOTTOM frame edge
13716 // can hang past the last padded row (1920x792: a unit at
13717 // y=768 wants 832 rows of an 800-row buffer, which panicked
13718 // the film's key frames). Those samples are outside the
13719 // frame: never output, and no block below ever references
13720 // them.
13721 if y + row >= self.height {
13722 break;
13723 }
13724 for col in 0..side {
13725 if x + col >= self.width {
13726 break;
13727 }
13728 let idx = row * side + col;
13729 let mut base = i32::from(prediction[idx]);
13730 if let Some((alpha_q3, ac_q3)) = cfl {
13731 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
13732 }
13733 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
13734 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
13735 }
13736 }
13737 }
13738}
13739
13740/// Reads one plane's transform block, reconstructs it into `plane` at
13741/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
13742#[allow(clippy::too_many_arguments)]
13743fn read_plane(
13744 dec: &mut SymbolDecoder,
13745 cdfs: &mut Cdfs,
13746 set: TxbSet,
13747 scan: &[u16],
13748 plane_idx: usize,
13749 around: (bool, bool, i32),
13750 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
13751 // it for every plane's `txb` lookup (it is what an intra transform type's
13752 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
13753 tx_mode: usize,
13754 predict_mode: usize,
13755 angle_delta: i32,
13756 reach: Reach,
13757 // lane-wave1 step (i): unread -- this reader records its write
13758 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
13759 // stays in the signature so every call site still proves the plane is
13760 // exclusively held while its coefficients are parsed.
13761 _plane: &mut PlaneBuf<'static>,
13762 x: usize,
13763 y: usize,
13764 side: usize,
13765 tx_side: usize,
13766 base_q_idx: u8,
13767 cfl: Option<(i32, CflSrc)>,
13768 filter_intra: Option<usize>,
13769 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
13770 // smaller than its own block (spec `get_txb_ctx_general`'s
13771 // `plane_bsize != tx_size` branch), carrying the already-looked-up
13772 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
13773 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
13774 // formula below.
13775 luma_skip_ctx: Option<usize>,
13776 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
13777 smooth_neighbor: bool, fctx: &crate::decode::FrameCtx,
13778) -> Result<Grid> {
13779 let skip_ctx = if plane_idx == 0 {
13780 luma_skip_ctx.unwrap_or(0)
13781 } else {
13782 // libaom `get_txb_ctx`: a chroma unit's context is
13783 // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the
13784 // plane block is bigger than the transform. Our chroma tables hold the
13785 // offset-7 rows first, so the caller adds 3 for the bigger-block case
13786 // (only a 128x128 block's TX_32X32 chroma units, lane-sb128b r3).
13787 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
13788 };
13789 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
13790 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
13791 // not by the block's ordinary `mode` (which is always DC_PRED whenever
13792 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
13793 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
13794 // filter-intra in AV1).
13795 let tx_mode = if plane_idx == 0 { fi_tx_row(tx_mode, filter_intra) } else { tx_mode };
13796 let mut coding = cdfs.txb(set, tx_mode);
13797 // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
13798 // transform type for lossless mode(qindex==0)" -- the symbol is not coded
13799 // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
13800 // plane of a lossless block (the residual then goes through the WHT, so
13801 // the type only picks the scan, which is the default one).
13802 if lossless(fctx) {
13803 coding.tx_type = None;
13804 }
13805 // Luma's `default_tx_type` is only a fallback for the sizes whose
13806 // `TxbSet` carries no symbol at all (32-point and up), which the spec
13807 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
13808 // *never* its own coded symbol (`coding.tx_type` is always `None` for
13809 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
13810 // the plane's own predicted mode (`default_intra_tx_type`) -- except
13811 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
13812 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
13813 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
13814 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
13815 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
13816 // narrows there — only `Chroma32` and up do).
13817 let default_tx_type = if plane_idx == 0 || side >= 32 {
13818 TxType::DctDct
13819 } else if let Some(inherited) = fctx.intrabc_chroma_tx.with(std::cell::Cell::get) {
13820 // See [`INTRABC_CHROMA_TX`]: an intrabc block is an inter block for
13821 // `av1_get_tx_type`, so chroma inherits luma's coded type (the
13822 // `side >= 32` arm above is already libaom's `EXT_TX_SET_DCTONLY`
13823 // clamp at `tx_size_sqr_up >= TX_32X32`, matching
13824 // [`read_inter_plane`]'s own `side < 32` guard).
13825 inherited
13826 } else {
13827 default_intra_tx_type(predict_mode as u8)
13828 };
13829 // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
13830 // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
13831 let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type };
13832 let (grid, tx_type) = read_coeffs(
13833 dec,
13834 &mut coding,
13835 scan,
13836 skip_ctx,
13837 dc_sign_ctx(around.2),
13838 default_tx_type,
13839 None,
13840 )?;
13841 note_chroma_class1(plane_idx, tx_type);
13842 if plane_idx == 0 {
13843 fctx.luma_tx_type.with(|c| c.set(tx_type));
13844 }
13845 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
13846 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
13847 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
13848 // guard also assumes.
13849 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
13850 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
13851 // keyed by that true size, not the coded corner's -- so the corner
13852 // goes into the top-left of a `side`-sized grid, not the reverse.
13853 let levels = extend_corner(grid, tx_side, tx_side, side, side);
13854 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
13855 let tx = TxParams {
13856 w: side, h: side, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta,
13857 ac_delta, tx_type, stride: 0, lossless: lossless(fctx),
13858 };
13859 if crate::envflags::env_flag!("EC_AV1_TRACE") {
13860 let residual = tx.run(&levels);
13861 eprintln!(
13862 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={:?} residual={residual:?}", &*levels,
13863 );
13864 }
13865 push_intra_tx(
13866 plane_idx,
13867 x,
13868 y,
13869 side,
13870 side,
13871 false,
13872 predict_mode,
13873 angle_delta,
13874 reach,
13875 tx,
13876 &levels,
13877 cfl,
13878 filter_intra,
13879 smooth_neighbor, fctx,
13880 );
13881 // `record`'s neighbour state only reads whether *the coded grid* (not the
13882 // residual) has nonzero entries, so the levels this function already
13883 // built are what it wants back -- both arms of the old `tx_side == side`
13884 // branch returned exactly that, one of them through a full `to_vec` copy
13885 // of the grid per intra transform unit (lane-coefbuf).
13886 Ok(levels)
13887}
13888
13889/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
13890/// three planes, reconstructing them into `y`/`u`/`v` and updating
13891/// `neighbours`.
13892#[allow(clippy::too_many_arguments)]
13893fn decode_block(
13894 dec: &mut SymbolDecoder,
13895 cdfs: &mut Cdfs,
13896 neighbours: &mut Neighbours,
13897 at: (usize, usize),
13898 side: usize,
13899 luma_set: TxbSet,
13900 chroma_set: TxbSet,
13901 luma_tx: usize,
13902 chroma_tx: usize,
13903 scans: (&[u16], &[u16]),
13904 cfl: bool,
13905 y: &mut PlaneBuf<'static>,
13906 u: &mut PlaneBuf<'static>,
13907 v: &mut PlaneBuf<'static>,
13908 base_q_idx: u8,
13909 enable_filter_intra: bool,
13910 allow_screen_content_tools: bool,
13911 allow_intrabc: bool,
13912 scan32: &[u16],
13913 scan16: &[u16],
13914 scan8: &[u16],
13915 scan4: &[u16],
13916 tx_select: bool,
13917 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
13918) -> Result<()> {
13919 // lane-lossless: a lossless frame's transform is TX_4X4 on every plane
13920 // (libaom `read_tx_size`, `decodeframe.c`), so the caller's per-size
13921 // tables/scans are replaced by the 4x4 ones and the block always takes the
13922 // multi-transform-unit path below.
13923 let (luma_set, chroma_set, luma_tx, chroma_tx, scans) = if lossless(fctx) {
13924 (TxbSet::Luma4, TxbSet::Chroma4, 4, 4, (scan4, scan4))
13925 } else {
13926 (luma_set, chroma_set, luma_tx, chroma_tx, scans)
13927 };
13928 let (r, c) = at;
13929 let (px, py) = (c * SUB, r * SUB);
13930 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
13931 let palette_uv_cache = neighbours.palette_uv_cache(at);
13932 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
13933 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
13934 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
13935 read_intra_mode(
13936 dec,
13937 cdfs,
13938 nb_above_mode,
13939 nb_left_mode,
13940 cfl,
13941 side,
13942 enable_filter_intra,
13943 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
13944 allow_screen_content_tools,
13945 allow_intrabc,
13946 Some((palette_ctx, &palette_cache)),
13947 &palette_uv_cache,
13948 r * (SUB / MI),
13949 c * (SUB / MI), fctx,
13950 )?;
13951 if at_tile_left && palette_y.is_some() {
13952 hit!(PALETTE_TILE_LEFT_HITS);
13953 }
13954 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
13955 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
13956 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
13957 // actual chroma-from-luma correlation, same as this decoder always did.
13958 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
13959 DC_PRED
13960 } else {
13961 uv_mode
13962 };
13963 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
13964 if smooth_neighbor {
13965 hit!(SMOOTH_LUMA_HITS);
13966 }
13967 let smooth_neighbor_uv =
13968 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
13969 if crate::envflags::env_flag!("EC_AV1_TRACE") {
13970 eprintln!(
13971 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
13972 angle_delta_uv={angle_delta_uv}"
13973 );
13974 }
13975 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
13976 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
13977 // block, skipped or not. `logical_tx` is what the loop filter's edge
13978 // lookup and the next block's own `tx_size_context` want (the *nominal*
13979 // transform size -- 64 even for the 64x64 corner-scanned case, spec
13980 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
13981 // which only differs from it at that one corner case.
13982 // lane-t900 r32: spec 5.11.16 `read_block_tx_size` gates the `tx_depth`
13983 // symbol on `allowSelect = !skip || !is_inter`, and libaom's
13984 // `is_inter_block` counts an INTRABC block (`blockd.h:373`). So a SKIPPED
13985 // intrabc block reads NO tx-size symbol at all -- it takes
13986 // `maxRectTxSize` -- while every ordinary skipped intra block does read
13987 // one. Reading it anyway consumed a symbol libaom never wrote and desynced
13988 // the tile from that block on (class `equal-range-means-unread`).
13989 // lane-t900 r32: and an UNSKIPPED one reads the inter var-tx partition
13990 // tree instead (`read_var_tx_size`), the same syntax the inter block path
13991 // has always read -- libaom's `parse_decode_block` dispatches on
13992 // `is_inter_block`, so both branches of `read_block_tx_size` treat an
13993 // intrabc block as inter.
13994 let intrabc_skip_tx = intrabc_dv.is_some() && skip;
13995 let intrabc_vartx = intrabc_dv.is_some() && tx_select && !skip;
13996 let intrabc_leaves = if intrabc_vartx {
13997 let max_tx = side.min(64);
13998 // `max_block_wide`/`max_block_high`: the frame's own mi grid
13999 // (`av1_calc_mi_size`, 8-px aligned), so a block hanging over the
14000 // right/bottom edge reads no split symbol for the units outside it.
14001 let mi_cols = 2 * y.true_width.div_ceil(8);
14002 let mi_rows = 2 * y.true_height.div_ceil(8);
14003 let side_mi = side / MI;
14004 let max_w_mi = side_mi.min(mi_cols.saturating_sub(mi_c));
14005 let max_h_mi = side_mi.min(mi_rows.saturating_sub(mi_r));
14006 let mut leaves = Vec::new();
14007 for row in (0..side_mi).step_by(max_tx / MI) {
14008 for col in (0..side_mi).step_by(max_tx / MI) {
14009 read_var_tx_size(
14010 dec, cdfs, neighbours, (mi_r, mi_c), side,
14011 (max_w_mi, max_h_mi), (max_tx, max_tx), 0, row, col, &mut leaves,
14012 );
14013 }
14014 }
14015 hit!(INTRABC_VARTX_HITS);
14016 // The luma reconstruct loop below is a UNIFORM grid of one square
14017 // transform (the intra `tx_depth` shape), so a tree that resolved to
14018 // mixed leaf sizes is refused by name rather than reconstructed at the
14019 // wrong stride.
14020 let uniform = leaves
14021 .first()
14022 .is_some_and(|f| leaves.iter().all(|l| (l.2, l.3) == (f.2, f.3) && l.2 == l.3));
14023 if !uniform {
14024 return Err(unsupported(
14025 "an intrabc block whose var-tx tree resolved to mixed leaf transform sizes",
14026 ));
14027 }
14028 Some(leaves[0].2)
14029 } else {
14030 None
14031 };
14032 let (logical_tx, coeff_tx_side) = if let Some(tx) = intrabc_leaves {
14033 (tx, if tx == 64 { 32 } else { tx })
14034 } else if tx_select && !intrabc_skip_tx {
14035 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, None);
14036 (resolved, if resolved == 64 { 32 } else { resolved })
14037 } else {
14038 // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is
14039 // TX_64X64, so a 128x128 block is always FOUR luma transform units
14040 // even with `tx_select` off -- the TU loop below, never the
14041 // single-unit path.
14042 (lossless_tx(side.min(64), fctx), luma_tx)
14043 };
14044 if tx_select && logical_tx < side && uv_mode != DC_PRED {
14045 hit!(SQ_CHROMA_TX_HITS);
14046 }
14047 let luma_set = if tx_select {
14048 txbset_for(logical_tx, reduced_tx_set)
14049 } else {
14050 luma_set
14051 };
14052 let luma_set = if intrabc_dv.is_some() {
14053 txbset_for_inter(logical_tx, reduced_tx_set)
14054 } else {
14055 luma_set
14056 };
14057 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
14058 let reach = Reach::of(side, px, py, y.width, y.height, fctx);
14059 let (cpx, cpy) = (px / 2, py / 2);
14060 let chroma_side = side / 2;
14061 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
14062 // frame's own pre-loop-filter reconstruction (all loop filters are off
14063 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
14064 // block vector, with the BILINEAR kernel libaom forces for intrabc --
14065 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
14066 // odd, which is exactly what the bilinear taps then interpolate.
14067 flush_recon(fctx, y, u, v);
14068 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
14069 let mut yb = vec![0u16; side * side];
14070 mc::predict_with_filter(
14071 &y.data, y.width, y.true_width, y.true_height,
14072 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
14073 side, side, mc::InterpFilterKind::Bilinear, &mut yb, fctx,
14074 );
14075 let mut ub = vec![0u16; chroma_side * chroma_side];
14076 mc::predict_with_filter(
14077 &u.data, u.width, u.true_width, u.true_height,
14078 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
14079 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut ub, fctx,
14080 );
14081 let mut vb = vec![0u16; chroma_side * chroma_side];
14082 mc::predict_with_filter(
14083 &v.data, v.width, v.true_width, v.true_height,
14084 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
14085 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut vb, fctx,
14086 );
14087 (yb, ub, vb)
14088 });
14089 // A palette-Y block's own prediction is the reconstructed colour-index
14090 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
14091 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
14092 // parameter through this function's dozen `y.reconstruct`/`read_plane`
14093 // sites. A split luma transform (`tx_select && logical_tx != side`)
14094 // would need the map sliced per-TU -- untested against a real
14095 // `--enable-palette=1` stream this round, so refuse by name rather than
14096 // guess at the slicing (charter's own named-acceptable fallback).
14097 let palette_y_buf: Option<Vec<u16>> = palette_y.as_ref().map(|py| {
14098 py.map
14099 .iter()
14100 .map(|&idx| py.colors[idx as usize])
14101 .collect()
14102 });
14103 // lane-t900 r32: the intrabc luma prediction rides the very same
14104 // whole-block override slot, so the multi-TU loop below windows it per
14105 // transform unit exactly like a palette map -- setting it once up front
14106 // handed the whole `side`x`side` buffer to the FIRST unit and left every
14107 // later one predicting off block edges (the var-tx tree above is what
14108 // first makes `logical_tx < side` reachable for an intrabc block).
14109 let palette_y_buf = match &intrabc_bufs {
14110 Some((yb, _, _)) => Some(yb.clone()),
14111 None => palette_y_buf,
14112 };
14113 // With one luma transform unit the whole `side`x`side` map is the
14114 // prediction; with several (`logical_tx != side`) each unit takes its own
14115 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
14116 // below (lane-palette2 r7) -- setting the full-block buffer here would be
14117 // taken by the FIRST unit and indexed at the wrong stride.
14118 if let Some(buf) = &palette_y_buf
14119 && logical_tx == side
14120 {
14121 set_palette_pred(buf.clone(), fctx);
14122 }
14123 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
14124 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
14125 // plane's own `reconstruct`/`read_plane` call below (never both planes at
14126 // once), since Y's own set-then-take already emptied the slot by the time
14127 // either of these run.
14128 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
14129 (
14130 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
14131 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
14132 )
14133 });
14134 // The chroma half of the intrabc prediction rides the same per-plane
14135 // override slot the UV-palette buffers do (set fresh before each plane's
14136 // own `reconstruct`/`read_plane` call below).
14137 let palette_uv_bufs = match &intrabc_bufs {
14138 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
14139 None => palette_uv_bufs,
14140 };
14141 if skip {
14142 // A skipped block codes no residual syntax at all (spec 5.11.34):
14143 // straight prediction, on every plane.
14144 //
14145 // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it
14146 // is skipped (only an INTER skip forces the largest transform), and
14147 // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts
14148 // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units
14149 // already written left/above of it inside this same block. Predicting
14150 // the whole `side`x`side` at once gives a different (uniformly off by
14151 // ~1) answer, which is exactly the residue this lane was chasing.
14152 // The palette/intrabc override path keeps the single-call shape (its
14153 // per-TU windowing is the non-skip loop's own `palette_y_buf` slice,
14154 // untested for skip and unreachable in these streams).
14155 // lane-sb128b r2: a 128x128 block's transform is TX_64X64 even with
14156 // `tx_select` off (`max_txsize_rect_lookup[BLOCK_128X128]`), so the
14157 // per-unit prediction is keyed on the transform being smaller than
14158 // the block, not on the tx-depth syntax. The counter keeps lane-hgkf's
14159 // narrower meaning (a READ split tx depth).
14160 let split_tx_skip =
14161 logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none();
14162 if split_tx_skip {
14163 if tx_select {
14164 hit!(SKIP_SPLIT_TX_HITS);
14165 }
14166 let n_axis = side / logical_tx;
14167 for tu_row in 0..n_axis {
14168 for tu_col in 0..n_axis {
14169 let tu_px = px + tu_col * logical_tx;
14170 let tu_py = py + tu_row * logical_tx;
14171 if tu_px >= y.true_width || tu_py >= y.true_height {
14172 continue;
14173 }
14174 let tu_reach = tu_reach(
14175 side,
14176 side,
14177 tu_col * logical_tx,
14178 tu_row * logical_tx,
14179 logical_tx,
14180 reach,
14181 px,
14182 py,
14183 y.width,
14184 y.height, fctx,
14185 );
14186 push_intra(0,
14187 tu_px,
14188 tu_py,
14189 logical_tx,
14190 mode,
14191 angle_delta_y,
14192 tu_reach,
14193 &ZERO_RESIDUAL[..logical_tx * logical_tx],
14194 None,
14195 filter_intra,
14196 smooth_neighbor, fctx,
14197 );
14198 }
14199 }
14200 } else {
14201 push_intra(0,
14202 px,
14203 py,
14204 side,
14205 mode,
14206 angle_delta_y,
14207 reach,
14208 &ZERO_RESIDUAL[..side * side],
14209 None,
14210 filter_intra,
14211 smooth_neighbor, fctx,
14212 );
14213 }
14214 let ac = alpha.map(|_| cfl_src(px, py, side));
14215 let cn = (chroma_side / chroma_tx).max(1);
14216 for cu_row in 0..cn {
14217 for cu_col in 0..cn {
14218 let luma_span = chroma_tx * 2;
14219 let cu_r = if cn == 1 {
14220 reach
14221 } else {
14222 tu_reach(
14223 side, side,
14224 cu_col * luma_span, cu_row * luma_span, luma_span,
14225 reach, px, py, y.width, y.height, fctx,
14226 )
14227 };
14228 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
14229 if let Some((ub, _)) = &palette_uv_bufs {
14230 set_palette_pred(ub.clone(), fctx);
14231 }
14232 push_intra(1,
14233 cu_x,
14234 cu_y,
14235 chroma_tx,
14236 uv_predict_mode,
14237 angle_delta_uv,
14238 cu_r,
14239 &ZERO_RESIDUAL[..chroma_tx * chroma_tx],
14240 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
14241 None,
14242 smooth_neighbor_uv, fctx,
14243 );
14244 if let Some((_, vb)) = &palette_uv_bufs {
14245 set_palette_pred(vb.clone(), fctx);
14246 }
14247 push_intra(2,
14248 cu_x,
14249 cu_y,
14250 chroma_tx,
14251 uv_predict_mode,
14252 angle_delta_uv,
14253 cu_r,
14254 &ZERO_RESIDUAL[..chroma_tx * chroma_tx],
14255 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
14256 None,
14257 smooth_neighbor_uv, fctx,
14258 );
14259 }
14260 }
14261 let luma_grid = vec![0i32; side * side];
14262 let u_grid = vec![0i32; chroma_side * chroma_side];
14263 let v_grid = vec![0i32; chroma_side * chroma_side];
14264 neighbours.record(at, side, mode, uv_predict_mode, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
14265 } else if logical_tx == side {
14266 // lane-sb128b r1: the test used to be `!tx_select || logical_tx == side`.
14267 // Without `tx_select` `logical_tx` IS `side` at every size <= 64, so
14268 // that arm was redundant -- and wrong at 128, where
14269 // `max_txsize_rect_lookup` caps the block's transform at 64 and the
14270 // block is four units whether or not `tx_select` is on.
14271 // A single luma transform unit -- the old path, unchanged (including
14272 // the 64x64 corner case, `logical_tx == side == 64` with
14273 // `coeff_tx_side == 32`).
14274 let around = neighbours.around(at, side);
14275 let luma_grid = read_plane(
14276 dec,
14277 cdfs,
14278 luma_set,
14279 luma_scan,
14280 0,
14281 around[0],
14282 mode,
14283 mode,
14284 angle_delta_y,
14285 reach,
14286 y,
14287 px,
14288 py,
14289 side,
14290 coeff_tx_side,
14291 base_q_idx,
14292 None,
14293 filter_intra,
14294 None,
14295 smooth_neighbor, fctx,
14296 )?;
14297 let ac = alpha.map(|_| cfl_src(px, py, side));
14298 // Armed for exactly this block's two chroma reads (see
14299 // [`INTRABC_CHROMA_TX`]); the luma call above just set
14300 // [`LUMA_TX_TYPE`] to the type it coded.
14301 if intrabc_dv.is_some() {
14302 fctx.intrabc_chroma_tx.with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
14303 }
14304 if let Some((ub, _)) = &palette_uv_bufs {
14305 set_palette_pred(ub.clone(), fctx);
14306 }
14307 let u_grid = read_plane(
14308 dec,
14309 cdfs,
14310 chroma_set,
14311 scans.1,
14312 1,
14313 around[1],
14314 mode,
14315 uv_predict_mode,
14316 angle_delta_uv,
14317 reach,
14318 u,
14319 cpx,
14320 cpy,
14321 chroma_side,
14322 chroma_tx,
14323 base_q_idx,
14324 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
14325 None,
14326 None,
14327 smooth_neighbor_uv, fctx,
14328 )?;
14329 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14330 eprintln!(
14331 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
14332 &u.data[cpy * u.width + cpx..][..chroma_side]
14333 );
14334 }
14335 if let Some((_, vb)) = &palette_uv_bufs {
14336 set_palette_pred(vb.clone(), fctx);
14337 }
14338 let v_grid = read_plane(
14339 dec,
14340 cdfs,
14341 chroma_set,
14342 scans.1,
14343 2,
14344 around[2],
14345 mode,
14346 uv_predict_mode,
14347 angle_delta_uv,
14348 reach,
14349 v,
14350 cpx,
14351 cpy,
14352 chroma_side,
14353 chroma_tx,
14354 base_q_idx,
14355 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
14356 None,
14357 None,
14358 smooth_neighbor_uv, fctx,
14359 )?;
14360 fctx.intrabc_chroma_tx.with(|c| c.set(None));
14361 neighbours.record(at, side, mode, uv_predict_mode, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
14362 } else {
14363 // Several luma transform units, raster order (spec
14364 // `transform_block`'s loop): the block's resolved transform is
14365 // genuinely smaller than its own side, so each tile of it predicts
14366 // and codes independently, its own context read fresh off whatever
14367 // the earlier tiles in this same block already wrote -- the same
14368 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
14369 let n_axis = side / logical_tx;
14370 let cn = (chroma_side / chroma_tx).max(1);
14371 // libaom's transform-block loop is over 64x64 luma "mu" chunks
14372 // (`decode_token_recon_block`: `mu_blocks_wide/high` =
14373 // `mi_size_wide[BLOCK_64X64]`), and it codes EVERY PLANE of a chunk
14374 // before moving to the next one. Below 128 a block is a single chunk,
14375 // so this is byte-for-byte the all-luma-then-all-chroma order that has
14376 // always run; at 128 the four quadrants interleave Y,U,V per quadrant
14377 // and reading all four luma units first desyncs the tile at the second
14378 // one (lane-sb128b r3, measured against aomdec's `EC_TRACE_COEFF`).
14379 let nchunk = (side / 64).max(1);
14380 // `cn > 1` means the uv plane block is larger than the uv transform,
14381 // which moves libaom's chroma `txb_skip_ctx` offset from 7 to 10.
14382 let chroma_ctx_offset = if cn > 1 { Some(3) } else { None };
14383 let tpc = (n_axis / nchunk).max(1);
14384 let cpc = (cn / nchunk).max(1);
14385 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
14386 let mut units: Vec<((usize, usize), usize, Grid, Grid)> = Vec::new();
14387 for ch_row in 0..nchunk {
14388 for ch_col in 0..nchunk {
14389 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
14390 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
14391 let tu_mi = (
14392 mi_r + tu_row * (logical_tx / MI),
14393 mi_c + tu_col * (logical_tx / MI),
14394 );
14395 let tu_px = px + tu_col * logical_tx;
14396 let tu_py = py + tu_row * logical_tx;
14397 // Same libaom clip as `decode_rect_split`'s loop above; a
14398 // square block only hangs off the frame when the frame's mi
14399 // dimensions are odd at the block's own level.
14400 if tu_px >= y.true_width || tu_py >= y.true_height {
14401 continue;
14402 }
14403 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
14404 // A transform unit inside a block is NOT a block at that
14405 // position (lane-palette2 r12): `Reach::of` granted the
14406 // top-right 8x8 unit of a 16x16 D203 block bottom-left
14407 // pixels libaom refuses outright (`col_off > 0`), which is
14408 // the diagonal wedge seed 46 reconstructed wrong.
14409 let tu_reach = tu_reach(
14410 side,
14411 side,
14412 tu_col * logical_tx,
14413 tu_row * logical_tx,
14414 logical_tx,
14415 reach,
14416 px,
14417 py,
14418 y.width,
14419 y.height, fctx,
14420 );
14421 // This transform unit's own bsize (`logical_tx`) is smaller
14422 // than the block it sits in (`side`), so `txb_skip_ctx` is
14423 // the neighbour-magnitude table, not the lone-TU 0 (spec
14424 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
14425 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
14426 if let Some(buf) = &palette_y_buf {
14427 hit!(PALETTE_SPLIT_TX_HITS);
14428 let mut window = vec![0u16; logical_tx * logical_tx];
14429 for row in 0..logical_tx {
14430 let src = (tu_row * logical_tx + row) * side + tu_col * logical_tx;
14431 window[row * logical_tx..][..logical_tx]
14432 .copy_from_slice(&buf[src..][..logical_tx]);
14433 }
14434 set_palette_pred(window, fctx);
14435 }
14436 let tu_grid = read_plane(
14437 dec,
14438 cdfs,
14439 luma_set,
14440 luma_scan,
14441 0,
14442 tu_around,
14443 mode,
14444 mode,
14445 angle_delta_y,
14446 tu_reach,
14447 y,
14448 tu_px,
14449 tu_py,
14450 logical_tx,
14451 // The unit's own COEFFICIENT grid, half its side at
14452 // TX_64X64 (a 64-point transform codes nothing past 32);
14453 // identical to `logical_tx` at every smaller size
14454 // (lane-sb128b r1).
14455 coeff_tx_side,
14456 base_q_idx,
14457 None,
14458 filter_intra,
14459 Some(tu_skip_ctx),
14460 smooth_neighbor, fctx,
14461 )?;
14462 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14463 eprintln!(
14464 "TRACE tu_bitpos mi=({},{}) tell={}",
14465 tu_mi.0,
14466 tu_mi.1,
14467 dec.debug_bitpos()
14468 );
14469 }
14470 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
14471 }
14472 }
14473 // CfL is only allowed up to 32x32, i.e. only at `nchunk == 1`, where
14474 // this still runs after every luma unit of the block.
14475 let ac = alpha.map(|_| cfl_src(px, py, side));
14476 // The block's uv plane block is `chroma_side` across but its uv
14477 // transform is `chroma_tx` (`av1_get_max_uv_txsize` =
14478 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[uv_plane_bsize])`):
14479 // identical at every size up to 64x64, but a 128x128 block's 64x64 uv
14480 // plane block adjusts TX_64X64 down to TX_32X32, so each plane is
14481 // FOUR units (lane-sb128b r2) -- one per mu chunk.
14482 // libaom `decode_token_recon_block` codes a mu chunk PLANE-MAJOR
14483 // (`for (plane..) for (blk_row..) for (blk_col..)`): every U unit of
14484 // the chunk, then every V unit. At one unit per plane per chunk --
14485 // every non-lossless case this decoder reaches -- that is the same
14486 // symbol order as the interleaved pair this loop used to read; a
14487 // lossless frame's 4x4 chroma units are the case where it differs
14488 // (lane-lossless2).
14489 let mut u_pass: Vec<Grid> = Vec::new();
14490 for plane_pass in 1..=2usize {
14491 let mut pass_idx = 0usize;
14492 for cu_row in ch_row * cpc..(ch_row + 1) * cpc {
14493 for cu_col in ch_col * cpc..(ch_col + 1) * cpc {
14494 // The chroma context arrays are indexed in LUMA mi, so this
14495 // unit's anchor is its own luma quadrant: `chroma_tx` chroma
14496 // pixels span `2 * chroma_tx` luma ones.
14497 let luma_span = chroma_tx * 2;
14498 let cu_mi = (
14499 mi_r + cu_row * (luma_span / MI),
14500 mi_c + cu_col * (luma_span / MI),
14501 );
14502 let cu_around = neighbours.around_mi(cu_mi, luma_span);
14503 let cu_reach = if cn == 1 {
14504 reach
14505 } else {
14506 tu_reach(
14507 side, side,
14508 cu_col * luma_span, cu_row * luma_span, luma_span,
14509 reach, px, py, y.width, y.height, fctx,
14510 )
14511 };
14512 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
14513 if let Some((ub, vb)) = &palette_uv_bufs {
14514 let pbuf = if plane_pass == 1 { ub } else { vb };
14515 set_palette_pred(
14516 palette_window(
14517 pbuf, chroma_side, cu_col * chroma_tx, cu_row * chroma_tx,
14518 chroma_tx, chroma_tx,
14519 ),
14520 fctx,
14521 );
14522 }
14523 let buf: &mut PlaneBuf<'static> =
14524 if plane_pass == 1 { &mut *u } else { &mut *v };
14525 let cu_grid = read_plane(
14526 dec, cdfs, chroma_set, scans.1, plane_pass, cu_around[plane_pass], mode,
14527 uv_predict_mode, angle_delta_uv, cu_reach, buf, cu_x, cu_y,
14528 chroma_tx, chroma_tx, base_q_idx,
14529 alpha.zip(ac).map(|((au, av), ac)| {
14530 (if plane_pass == 1 { au } else { av }, ac)
14531 }),
14532 None, chroma_ctx_offset, smooth_neighbor_uv, fctx,
14533 )?;
14534 if cn > 1 {
14535 hit!(CHROMA_SPLIT_TX_HITS);
14536 // Immediately, so the NEXT unit of this same block reads
14537 // this one's coefficient context (libaom's chroma
14538 // `txb_skip_ctx` for the second quadrant is 11, i.e. base
14539 // 1 from this left neighbour -- measured against aomdec).
14540 // The same writes are replayed after `record_split_luma`
14541 // below, which would otherwise clobber them whole-block.
14542 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, plane_pass, &cu_grid);
14543 }
14544 if plane_pass == 1 {
14545 u_pass.push(cu_grid);
14546 } else {
14547 let u_grid = std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0));
14548 if cn > 1 {
14549 units.push((cu_mi, luma_span, u_grid.clone(), cu_grid.clone()));
14550 }
14551 last_grids = [u_grid, cu_grid];
14552 }
14553 pass_idx += 1;
14554 }
14555 }
14556 }
14557 }
14558 }
14559 // Mode/side bookkeeping plus, at `cn == 1`, the whole-plane chroma
14560 // context write; at `cn > 1` the per-unit writes above are what the
14561 // next block reads, so they run after this (last writer wins).
14562 neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&last_grids[0], &last_grids[1]]);
14563 for (cu_mi, luma_span, u_grid, v_grid) in &units {
14564 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 1, u_grid);
14565 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 2, v_grid);
14566 }
14567 }
14568 // Unconditional, `size == 0` for a non-palette block: clears any stale
14569 // neighbour palette state the same way [`Neighbours::record`] always
14570 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
14571 // (the split-luma-TU branch above always refuses before reaching here
14572 // when `palette_y` is `Some`, so it is never live for that branch).
14573 let (py_size, py_colors) = palette_y
14574 .as_ref()
14575 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
14576 neighbours.record_palette_y(at, side, py_size, py_colors);
14577 let (puv_size, puv_colors) = palette_uv
14578 .as_ref()
14579 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
14580 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
14581 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
14582 neighbours.fill_lf_grid(
14583 (r * (SUB / MI), c * (SUB / MI)),
14584 side / MI,
14585 logical_tx as u8,
14586 0, fctx,
14587 );
14588 // lane-t900 r32: libaom runs `set_txfm_ctxs` at the end of EVERY
14589 // `decode_block`, key frames included, and the intrabc var-tx read above
14590 // (`txfm_partition_ctx`) is the only intra-path reader of those bands --
14591 // left at `TXFM_CTX_INIT` it would take the split symbol off the wrong CDF
14592 // row. Armed by the frame's own `allow_intrabc` so every other key frame
14593 // (whose readers use the deblock-grid approximation) is untouched.
14594 if allow_intrabc {
14595 set_txfm_ctxs(
14596 neighbours,
14597 (mi_r, mi_c),
14598 logical_tx,
14599 side / MI,
14600 side / MI,
14601 skip && intrabc_dv.is_some(),
14602 );
14603 }
14604 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv, fctx);
14605 Ok(())
14606}
14607
14608thread_local! {
14609 /// lane-sb128c r8: INTRA (key-frame) 128x64 blocks decoded at the 128
14610 /// root's HORZ arm, and 64x128 ones at its VERT arm.
14611 pub(crate) static INTRA_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
14612 pub(crate) static INTRA_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
14613 /// Those blocks by resolved intra `tx_depth` (0 = TX_64X64 units,
14614 /// 1 = TX_32X32, 2 = TX_16X16) -- proof the depth symbol is really read.
14615 pub(crate) static INTRA_SB128_DEPTH_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
14616 /// lane-inter128intra r1: the same shapes decoded on the INTER block path
14617 /// (an intra-coded PARTITION_HORZ/VERT half of a 128 superblock inside an
14618 /// inter frame) -- (128x64, 64x128).
14619 pub(crate) static INTRA128_IN_INTER_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
14620 /// lane-t900 r17: skipped INTER blocks whose `read_block_tx_size` still
14621 /// handed back var-tx leaves, so the per-transform-unit luma publication
14622 /// loop never ran and the block has to clear its own luma coefficient
14623 /// contexts (libaom `av1_reset_entropy_context`). Every 128 root under
14624 /// `TX_MODE_LARGEST` is one; the counter is what keeps that reset's gate
14625 /// non-vacuous.
14626 pub(crate) static SKIP_VARTX_LUMA_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
14627}
14628
14629/// [`SKIP_VARTX_LUMA_RESET_HITS`], for a gate's own before/after delta.
14630pub fn skip_vartx_luma_reset_hits() -> usize {
14631 SKIP_VARTX_LUMA_RESET_HITS.with(std::cell::Cell::get)
14632}
14633
14634/// [`INTRA128_IN_INTER_HITS`], for a gate's own before/after delta.
14635pub(crate) fn intra128_in_inter_hits() -> [usize; 2] {
14636 INTRA128_IN_INTER_HITS.with(std::cell::Cell::get)
14637}
14638
14639/// [`INTRA_SB128_HORZ_HITS`] / [`INTRA_SB128_VERT_HITS`] /
14640/// [`INTRA_SB128_DEPTH_HITS`], for a gate's own before/after delta.
14641pub(crate) fn intra_sb128_hits() -> (usize, usize, [usize; 3]) {
14642 (
14643 INTRA_SB128_HORZ_HITS.with(std::cell::Cell::get),
14644 INTRA_SB128_VERT_HITS.with(std::cell::Cell::get),
14645 INTRA_SB128_DEPTH_HITS.with(std::cell::Cell::get),
14646 )
14647}
14648
14649/// The 128 root's HORZ/VERT arm on an INTRA frame: ONE 128x64 (HORZ) or
14650/// 64x128 (VERT) intra block (lane-sb128c r8; the inter twin is
14651/// `decode_inter_block`'s own rect path).
14652///
14653/// libaom `decode_block` -> `predict_and_reconstruct_intra_block` per
14654/// transform unit, with the 128-specific geometry:
14655/// * `max_txsize_rect_lookup[BLOCK_128X64]` is TX_64X64, so every luma unit
14656/// is SQUARE and there are at least two of them -- depth 0: 64x64 x2,
14657/// depth 1: 32x32 x8, depth 2: 16x16 x32 (`bsize_to_tx_size_cat` counts
14658/// the `sub_tx_size_map` chain TX_64X64->32->16->8->4, i.e. cat 3, the
14659/// same CDF a 64x64 square block reads).
14660/// * `av1_get_max_uv_txsize` = `av1_get_adjusted_tx_size(
14661/// max_txsize_rect_lookup[BLOCK_64X32])` caps at TX_32X32, so the block's
14662/// 64x32 uv plane block is TWO 32x32 chroma units per plane -- one per
14663/// 64x64 luma "mu" chunk, and `decode_token_recon_block` codes Y, U, V of
14664/// a chunk before moving to the next (the interleave lane-sb128b r3
14665/// measured at the 128x128 NONE root).
14666/// * `get_txb_ctx`: the uv plane block is bigger than the uv transform, so
14667/// chroma `txb_skip_ctx` takes the offset-10 rows (7 + 3).
14668/// No CfL, no filter intra (both cap at 32x32) and no palette
14669/// (`av1_allow_palette` caps at 64x64) exist at this size -- the mode
14670/// reader's own size gates already say so, and the guard below is defensive.
14671#[allow(clippy::too_many_arguments)]
14672fn decode_block_128rect(
14673 dec: &mut SymbolDecoder,
14674 cdfs: &mut Cdfs,
14675 neighbours: &mut Neighbours,
14676 at: (usize, usize),
14677 bw: usize,
14678 bh: usize,
14679 y: &mut PlaneBuf<'static>,
14680 u: &mut PlaneBuf<'static>,
14681 v: &mut PlaneBuf<'static>,
14682 base_q_idx: u8,
14683 enable_filter_intra: bool,
14684 allow_screen_content_tools: bool,
14685 tx_select: bool,
14686 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
14687) -> Result<()> {
14688 let (r, c) = at;
14689 let (px, py) = (c * SUB, r * SUB);
14690 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
14691 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
14692 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
14693 let palette_uv_cache = neighbours.palette_uv_cache(at);
14694 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
14695 read_intra_mode_rect(
14696 dec,
14697 cdfs,
14698 nb_above_mode,
14699 nb_left_mode,
14700 // `is_cfl_allowed` caps CFL at 32x32: `uv_mode` comes off the
14701 // 13-symbol no-CFL CDF here, never the 14-symbol one.
14702 false,
14703 true,
14704 bw,
14705 bh,
14706 enable_filter_intra,
14707 neighbours.skip_txfm_ctx(mi_r, mi_c),
14708 allow_screen_content_tools,
14709 Some((palette_ctx, &palette_cache)),
14710 &palette_uv_cache,
14711 mi_r,
14712 mi_c, fctx,
14713 )?;
14714 if alpha.is_some() || filter_intra.is_some() || palette_y.is_some() || palette_uv.is_some() {
14715 return Err(unsupported(
14716 "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of \
14717 their size gates caps at 64x64 or below, so none of these symbols exists there)",
14718 ));
14719 }
14720 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
14721 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
14722 if smooth_neighbor {
14723 hit!(SMOOTH_LUMA_HITS);
14724 }
14725 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
14726 // spec 5.11.16 `read_tx_size`: read for every intra block, skipped or
14727 // not. `bsize_to_tx_size_cat(BLOCK_128X64)` is 3 (see this fn's doc).
14728 let in_inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some();
14729 let depth = if tx_select {
14730 // lane-inter128intra r1: on an INTER frame `get_tx_size_context` reads
14731 // the real `TXFM_CONTEXT` bands, and compares them against
14732 // `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` -- TX_64X64 for
14733 // every 128-axis block, hence the `min(64)`.
14734 let ctx = if in_inter {
14735 tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx)
14736 } else {
14737 tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh)
14738 };
14739 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
14740 } else {
14741 0
14742 };
14743 if depth != 0 {
14744 hit!(TX_DEPTH_HITS);
14745 }
14746 hit_do! {
14747 INTRA_SB128_DEPTH_HITS.with(|c| {
14748 let mut h = c.get();
14749 h[depth.min(2)] += 1;
14750 c.set(h);
14751 });
14752 }
14753 let logical_tx = 64 >> depth;
14754 // A 64-point transform codes nothing past its low 32 coefficients.
14755 let coeff_tx_side = logical_tx.min(32);
14756 let luma_set = txbset_for(logical_tx, reduced_tx_set);
14757 let luma_scan = default_scan(coeff_tx_side);
14758 let chroma_tx = 32;
14759 let chroma_scan = default_scan(chroma_tx);
14760 let (cpx, cpy) = (px / 2, py / 2);
14761 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
14762 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
14763 let (nch_x, nch_y) = (bw / 64, bh / 64);
14764 // One 32x32 chroma unit per mu chunk, per plane.
14765 debug_assert_eq!((chroma_w / chroma_tx, chroma_h / chroma_tx), (nch_x, nch_y));
14766 let tpc = 64 / logical_tx;
14767 let zero_tu = vec![0i32; logical_tx * logical_tx];
14768 let zero_cu = vec![0i32; chroma_tx * chroma_tx];
14769 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
14770 let mut units: Vec<((usize, usize), Grid, Grid)> = Vec::new();
14771 for ch_row in 0..nch_y {
14772 for ch_col in 0..nch_x {
14773 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
14774 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
14775 let tu_mi = (
14776 mi_r + tu_row * (logical_tx / MI),
14777 mi_c + tu_col * (logical_tx / MI),
14778 );
14779 let (tu_px, tu_py) = (px + tu_col * logical_tx, py + tu_row * logical_tx);
14780 // libaom clips the transform loop to
14781 // `max_blocks_wide/high`: a unit whose top-left sample is
14782 // outside the frame is never coded.
14783 if tu_px >= y.true_width || tu_py >= y.true_height {
14784 continue;
14785 }
14786 // Edge availability of a unit INSIDE a block, with the
14787 // 128 geometry -- `has_top_right` is false for a block
14788 // whose largest side is > 64, which [`Reach::of_rect`]
14789 // already answered for the block and [`tu_reach`] carries
14790 // down to the units on its own top row.
14791 let tu_r = tu_reach(
14792 bw,
14793 bh,
14794 tu_col * logical_tx,
14795 tu_row * logical_tx,
14796 logical_tx,
14797 reach,
14798 px,
14799 py,
14800 y.width,
14801 y.height, fctx,
14802 );
14803 if skip {
14804 push_intra(0,
14805 tu_px, tu_py, logical_tx, mode, angle_delta_y, tu_r, &zero_tu, None,
14806 None, smooth_neighbor, fctx,
14807 );
14808 neighbours.record_mi_luma(tu_mi, logical_tx, &zero_tu);
14809 continue;
14810 }
14811 // The unit is smaller than its block, so `txb_skip_ctx`
14812 // is the neighbour-magnitude table, never the lone-TU 0.
14813 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
14814 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
14815 let tu_grid = read_plane(
14816 dec,
14817 cdfs,
14818 luma_set,
14819 &luma_scan,
14820 0,
14821 tu_around,
14822 mode,
14823 mode,
14824 angle_delta_y,
14825 tu_r,
14826 y,
14827 tu_px,
14828 tu_py,
14829 logical_tx,
14830 coeff_tx_side,
14831 base_q_idx,
14832 None,
14833 None,
14834 Some(tu_skip_ctx),
14835 smooth_neighbor, fctx,
14836 )?;
14837 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
14838 }
14839 }
14840 // The chroma context arrays are indexed in LUMA mi, so this
14841 // unit's anchor is its own 64x64 mu chunk.
14842 let luma_span = chroma_tx * 2;
14843 let cu_mi = (
14844 mi_r + ch_row * (luma_span / MI),
14845 mi_c + ch_col * (luma_span / MI),
14846 );
14847 let cu_r = tu_reach(
14848 bw,
14849 bh,
14850 ch_col * luma_span,
14851 ch_row * luma_span,
14852 luma_span,
14853 reach,
14854 px,
14855 py,
14856 y.width,
14857 y.height, fctx,
14858 );
14859 let (cu_x, cu_y) = (cpx + ch_col * chroma_tx, cpy + ch_row * chroma_tx);
14860 if skip {
14861 push_intra(1,
14862 cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r, &zero_cu, None,
14863 None, smooth_neighbor_uv, fctx,
14864 );
14865 push_intra(2,
14866 cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r, &zero_cu, None,
14867 None, smooth_neighbor_uv, fctx,
14868 );
14869 continue;
14870 }
14871 let cu_around = neighbours.around_mi(cu_mi, luma_span);
14872 let u_grid = read_plane(
14873 dec, cdfs, TxbSet::Chroma32, &chroma_scan, 1, cu_around[1], mode, uv_predict_mode,
14874 angle_delta_uv, cu_r, u, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, None, None,
14875 Some(3), smooth_neighbor_uv, fctx,
14876 )?;
14877 let v_grid = read_plane(
14878 dec, cdfs, TxbSet::Chroma32, &chroma_scan, 2, cu_around[2], mode, uv_predict_mode,
14879 angle_delta_uv, cu_r, v, cu_x, cu_y, chroma_tx, chroma_tx, base_q_idx, None, None,
14880 Some(3), smooth_neighbor_uv, fctx,
14881 )?;
14882 hit!(CHROMA_SPLIT_TX_HITS);
14883 // Immediately, so the NEXT unit of this same block reads this
14884 // one's coefficient context; replayed after `record_split_luma_rect`
14885 // below, which would otherwise clobber them whole-block.
14886 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 1, &u_grid);
14887 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, 2, &v_grid);
14888 units.push((cu_mi, u_grid.clone(), v_grid.clone()));
14889 last_grids = [u_grid, v_grid];
14890 }
14891 }
14892 if skip {
14893 neighbours.record_rect(
14894 at,
14895 bw,
14896 bh,
14897 mode,
14898 uv_predict_mode,
14899 &[
14900 &ZERO_RESIDUAL[..bw * bh],
14901 &ZERO_RESIDUAL[..chroma_w * chroma_h],
14902 &ZERO_RESIDUAL[..chroma_w * chroma_h],
14903 ],
14904 );
14905 } else {
14906 neighbours.record_split_luma_rect(
14907 at,
14908 bw,
14909 bh,
14910 mode,
14911 uv_predict_mode,
14912 [&last_grids[0], &last_grids[1]],
14913 );
14914 for (cu_mi, u_grid, v_grid) in &units {
14915 neighbours.record_mi_chroma(*cu_mi, 64, 64, 1, u_grid);
14916 neighbours.record_mi_chroma(*cu_mi, 64, 64, 2, v_grid);
14917 }
14918 }
14919 // No palette exists at this size; the unconditional stamp clears any
14920 // stale neighbour palette state, as every other block path does.
14921 neighbours.record_palette_y_rect(at, bw, bh, 0, [0u16; 8]);
14922 neighbours.record_palette_uv_rect(at, bw, bh, 0, [0u16; 8]);
14923 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
14924 neighbours.fill_lf_grid_rect(
14925 (mi_r, mi_c),
14926 bw / MI,
14927 bh / MI,
14928 logical_tx as u8,
14929 logical_tx as u8,
14930 0, fctx,
14931 );
14932 if in_inter {
14933 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)`
14934 // (libaom `decodeframe.c` `decode_block`) runs for EVERY block of an
14935 // inter frame, intra ones included: an intra block stamps its
14936 // TRANSFORM size over its own footprint in both TXFM_CONTEXT bands.
14937 // A key frame has no var-tx tree and its readers use the deblock grid,
14938 // so this is the inter path's alone.
14939 txfm_partition_update_rect(
14940 neighbours,
14941 (mi_r, mi_c),
14942 (logical_tx, logical_tx),
14943 (bw, bh),
14944 );
14945 hit_do! {
14946 INTRA128_IN_INTER_HITS.with(|c| {
14947 let mut h = c.get();
14948 h[usize::from(bw < bh)] += 1;
14949 c.set(h);
14950 });
14951 }
14952 } else if bw > bh {
14953 hit!(INTRA_SB128_HORZ_HITS);
14954 } else {
14955 hit!(INTRA_SB128_VERT_HITS);
14956 }
14957 Ok(())
14958}
14959
14960
14961/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
14962/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
14963/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
14964/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
14965/// just-decoded mode, not the enclosing slot's stale one, is the true
14966/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
14967/// units, which is what its coefficient context (finer than [`SUB`]) is read
14968/// at. Returns the mode this leaf decoded, for the caller's own
14969/// `prev_leaf`/final mode-writeback bookkeeping.
14970#[allow(clippy::too_many_arguments)]
14971/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
14972/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
14973/// `above_mode[col]`, and its true above neighbour is the mi directly above
14974/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
14975/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
14976/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
14977/// (bottom-right) into both, as this path did, is right only when all four
14978/// leaves happen to share a mode. `done` may be short at the true frame edge
14979/// (the straddle caller filters positions off the frame), so each side falls
14980/// back to the last leaf actually decoded.
14981fn write_back_split_modes(
14982 neighbours: &mut Neighbours,
14983 done: &[((usize, usize), usize)],
14984 parent_mi: (usize, usize),
14985 slot: (usize, usize),
14986) {
14987 let (sr, sc) = slot;
14988 let Some(&(_, last)) = done.last() else {
14989 return;
14990 };
14991 let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m);
14992 neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last);
14993 neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last);
14994}
14995
14996fn decode_leaf8(
14997 dec: &mut SymbolDecoder,
14998 cdfs: &mut Cdfs,
14999 neighbours: &mut Neighbours,
15000 outer_at: (usize, usize),
15001 leaf_mi: (usize, usize),
15002 scans: (&[u16], &[u16]),
15003 prev_leaf: Option<((usize, usize), usize)>,
15004 y: &mut PlaneBuf<'static>,
15005 u: &mut PlaneBuf<'static>,
15006 v: &mut PlaneBuf<'static>,
15007 base_q_idx: u8,
15008 enable_filter_intra: bool,
15009 allow_screen_content_tools: bool,
15010 allow_intrabc: bool,
15011 tx_select: bool,
15012 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
15013) -> Result<usize> {
15014 let (r, c) = outer_at;
15015 // lane-modectx r1: the group's own availability-correct fallback pair, not
15016 // the raw coarse bands (which leak across a tile edge -- see
15017 // `modes_above_left`).
15018 let (mut above_mode, mut left_mode) = neighbours.modes_above_left(r, c);
15019 if let Some(((pr, pc), pmode)) = prev_leaf {
15020 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
15021 above_mode = pmode;
15022 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
15023 left_mode = pmode;
15024 }
15025 }
15026 // The mi-exact neighbour wins over both the coarse 16x16 slot and
15027 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
15028 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
15029 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
15030 // lane-rectsplitx r2 swept this arm into
15031 // [`Neighbours::modes_above_left_mi`]: the mi-exact map ALSO has to answer
15032 // "no neighbour" at a tile edge, where the coarse cell holds the block
15033 // above/left of it inside the same 16x16.
15034 let (above_mode, left_mode) =
15035 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
15036 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
15037 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
15038 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
15039 // this leaf's `smooth_neighbor` is built from -- passing `false` here
15040 // filtered a directional chroma block's edge at the wrong strength
15041 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
15042 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
15043 // with the coarse [`SUB`] slot as the fallback when no block recorded
15044 // that exact mi cell.
15045 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
15046 if smooth_neighbor {
15047 hit!(SMOOTH_LUMA_HITS);
15048 }
15049 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
15050 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
15051 // `decode_block` caller at 16x16 and up.
15052 // lane-pal8 r1: this leaf's own palette-Y mode ctx and colour cache
15053 // (`av1_get_palette_mode_ctx` / `av1_get_palette_cache`, decodemv.c:567,
15054 // `read_palette_mode_info`), at its REAL mi position -- passing
15055 // `None`/`&[]` read `palette_y_mode` off CDF row 0 and refused by name the
15056 // moment a real 8x8 palette block fired, which is where every 8-bit
15057 // `--tune-content=screen --min-partition-size=8` stream stopped.
15058 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(leaf_mi);
15059 let palette_uv_cache = neighbours.palette_uv_cache_mi(leaf_mi);
15060 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
15061 read_intra_mode(
15062 dec,
15063 cdfs,
15064 above_mode,
15065 left_mode,
15066 true,
15067 8,
15068 enable_filter_intra,
15069 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
15070 allow_screen_content_tools,
15071 allow_intrabc,
15072 Some((palette_ctx, &palette_cache)),
15073 &palette_uv_cache,
15074 leaf_mi.0,
15075 leaf_mi.1, fctx,
15076 )?;
15077 // lane-kf900 r7: an 8x8 leaf consumed `use_intrabc` (and its DV) through
15078 // `read_intra_mode` and then decoded the block as if it were ordinary
15079 // intra. libaom's `is_inter_block` counts an intrabc block
15080 // (`blockd.h:373`), so its luma `tx_type` comes off the INTER ext-tx set
15081 // (`av1_get_ext_tx_set_type(TX_8X8, is_inter=1, 0)` = `EXT_TX_SET_ALL16`,
15082 // a 16-symbol CDF) while we read the 7-symbol `TX_SET_INTRA_1` row: the
15083 // same value with a different interval, so the tile desynced at the very
15084 // next symbol (class `wrong-alphabet-same-value`). Everything below
15085 // mirrors `decode_block`'s own intrabc handling at 16x16 and up.
15086 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
15087 if intrabc_dv.is_some() {
15088 hit!(LEAF8_INTRABC_HITS);
15089 }
15090 // `av1_visit_palette`'s reconstruction (decodeframe.c:1135): the colour
15091 // index map, mapped through the base colours, IS the block's prediction --
15092 // carried to the next `reconstruct`/`read_plane` through the same
15093 // [`PALETTE_PRED`] slot [`decode_block`] uses at 16x16 and up.
15094 let palette_y_buf: Option<Vec<u16>> = palette_y
15095 .as_ref()
15096 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
15097 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
15098 (
15099 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
15100 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
15101 )
15102 });
15103 let (pal_y_size, pal_y_colors) =
15104 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
15105 let (pal_uv_size, pal_uv_colors) =
15106 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
15107 if palette_y.is_some() || palette_uv.is_some() {
15108 hit!(PALETTE_LEAF8_HITS);
15109 }
15110 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
15111 DC_PRED
15112 } else {
15113 uv_mode
15114 };
15115 neighbours.above_uv_mode[c] = uv_predict_mode;
15116 neighbours.left_uv_mode[r] = uv_predict_mode;
15117 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
15118 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
15119 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
15120 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
15121 // transform units, same raster-order per-TU pattern `decode_block`'s
15122 // multi-TU branch runs).
15123 // ... and an intrabc leaf reads no intra `tx_depth` symbol at all: libaom
15124 // dispatches `read_block_tx_size` on `is_inter_block`, which counts an
15125 // intrabc block, so a SKIPPED one takes the largest transform and an
15126 // UNSKIPPED one reads the inter var-tx tree (lane-t900 r32). At 8x8 that
15127 // tree is one `txfm_split` symbol: TX_8X8, or TX_4X4 over all four mi
15128 // cells (`read_var_tx_size`'s `sub_txs == TX_4X4` early return).
15129 let resolved = if tx_select && intrabc_dv.is_some() && !skip {
15130 let mut leaves = Vec::new();
15131 let mi_cols = 2 * y.true_width.div_ceil(8);
15132 let mi_rows = 2 * y.true_height.div_ceil(8);
15133 read_var_tx_size(
15134 dec,
15135 cdfs,
15136 neighbours,
15137 leaf_mi,
15138 8,
15139 (
15140 2usize.min(mi_cols.saturating_sub(leaf_mi.1)),
15141 2usize.min(mi_rows.saturating_sub(leaf_mi.0)),
15142 ),
15143 (8, 8),
15144 0,
15145 0,
15146 0,
15147 &mut leaves,
15148 );
15149 hit!(INTRABC_VARTX_HITS);
15150 leaves.first().map_or(8, |l| l.2)
15151 } else if tx_select && intrabc_dv.is_none() {
15152 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8, None)
15153 } else {
15154 // lane-lossless: TX_4X4 on a lossless frame, no symbol
15155 // (libaom `read_tx_size`).
15156 lossless_tx(8, fctx)
15157 };
15158 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
15159 let reach = Reach::of(8, px, py, y.width, y.height, fctx);
15160 let (cpx, cpy) = (px / 2, py / 2);
15161 // spec 7.11.3.4 with `use_intrabc`, same as `decode_block`: predict from
15162 // the CURRENT frame's own pre-loop-filter reconstruction (every loop
15163 // filter is off whenever `allow_intrabc`, frame.rs:194/210/252/272) at
15164 // the full-pel block vector, with the BILINEAR kernel libaom forces.
15165 flush_recon(fctx, y, u, v);
15166 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
15167 let mut yb = vec![0u16; 8 * 8];
15168 mc::predict_with_filter(
15169 &y.data, y.width, y.true_width, y.true_height,
15170 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
15171 8, 8, mc::InterpFilterKind::Bilinear, &mut yb, fctx,
15172 );
15173 let mut ub = vec![0u16; 4 * 4];
15174 mc::predict_with_filter(
15175 &u.data, u.width, u.true_width, u.true_height,
15176 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
15177 4, 4, mc::InterpFilterKind::Bilinear, &mut ub, fctx,
15178 );
15179 let mut vb = vec![0u16; 4 * 4];
15180 mc::predict_with_filter(
15181 &v.data, v.width, v.true_width, v.true_height,
15182 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
15183 4, 4, mc::InterpFilterKind::Bilinear, &mut vb, fctx,
15184 );
15185 (yb, ub, vb)
15186 });
15187 // The per-plane prediction override rides the same [`PALETTE_PRED`] slot
15188 // `decode_block` uses: set fresh right before each plane's own
15189 // `reconstruct`/`read_plane` call (the slot is taken, not copied).
15190 // lane-t900 r32: through `palette_y_buf`, so the 4x4 TU loop below windows
15191 // it per unit (an intrabc leaf whose var-tx tree split to TX_4X4 is the
15192 // first shape that reaches that loop with an override set).
15193 let palette_y_buf = match &intrabc_bufs {
15194 Some((yb, _, _)) => Some(yb.clone()),
15195 None => palette_y_buf,
15196 };
15197 let (luma_grid, u_grid, v_grid);
15198 if skip {
15199 // lane-hgkf r2 (same shape as `decode_block`'s own skip branch): an
15200 // 8x8 leaf whose `tx_depth` resolved to TX_4X4 predicts FOUR 4x4
15201 // transform units, each off the units already written left/above of
15202 // it inside this same leaf -- an intra block's transform size is read
15203 // whether or not it is skipped, and spec 7.11.2 predicts per unit.
15204 // A palette block's prediction is the whole-block index map, never
15205 // per-transform-unit edges ([`decode_block`]'s own `split_tx_skip`
15206 // rule) -- so a palette leaf takes the single 8x8 reconstruct below
15207 // even when `tx_depth` resolved to TX_4X4.
15208 if resolved == 4 && palette_y_buf.is_none() {
15209 hit!(SKIP_SPLIT_TX_HITS);
15210 for tu_row in 0..2 {
15211 for tu_col in 0..2 {
15212 let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4);
15213 if tu_px >= y.true_width || tu_py >= y.true_height {
15214 continue;
15215 }
15216 let tu_reach = tu_reach(
15217 8,
15218 8,
15219 tu_col * 4,
15220 tu_row * 4,
15221 4,
15222 reach,
15223 px,
15224 py,
15225 y.width,
15226 y.height, fctx,
15227 );
15228 push_intra(0,
15229 tu_px,
15230 tu_py,
15231 4,
15232 mode,
15233 angle_delta_y,
15234 tu_reach,
15235 &ZERO_RESIDUAL[..16],
15236 None,
15237 filter_intra,
15238 smooth_neighbor, fctx,
15239 );
15240 }
15241 }
15242 } else {
15243 if let Some(buf) = &palette_y_buf {
15244 set_palette_pred(buf.clone(), fctx);
15245 }
15246 push_intra(0,
15247 px,
15248 py,
15249 8,
15250 mode,
15251 angle_delta_y,
15252 reach,
15253 &ZERO_RESIDUAL[..64],
15254 None,
15255 filter_intra,
15256 smooth_neighbor, fctx,
15257 );
15258 }
15259 let ac = alpha.map(|_| cfl_src(px, py, 8));
15260 if let Some((_, ub, _)) = &intrabc_bufs {
15261 set_palette_pred(ub.clone(), fctx);
15262 } else if let Some((ub, _)) = &palette_uv_bufs {
15263 set_palette_pred(ub.clone(), fctx);
15264 }
15265 push_intra(1,
15266 cpx,
15267 cpy,
15268 4,
15269 uv_predict_mode,
15270 angle_delta_uv,
15271 reach,
15272 &ZERO_RESIDUAL[..16],
15273 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15274 None,
15275 smooth_neighbor_uv, fctx,
15276 );
15277 if let Some((_, _, vb)) = &intrabc_bufs {
15278 set_palette_pred(vb.clone(), fctx);
15279 } else if let Some((_, vb)) = &palette_uv_bufs {
15280 set_palette_pred(vb.clone(), fctx);
15281 }
15282 push_intra(2,
15283 cpx,
15284 cpy,
15285 4,
15286 uv_predict_mode,
15287 angle_delta_uv,
15288 reach,
15289 &ZERO_RESIDUAL[..16],
15290 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15291 None,
15292 smooth_neighbor_uv, fctx,
15293 );
15294 luma_grid = Grid::Zero(64);
15295 u_grid = Grid::Zero(16);
15296 v_grid = Grid::Zero(16);
15297 } else if resolved != 4 {
15298 let around = neighbours.around_mi(leaf_mi, 8);
15299 if let Some(buf) = &palette_y_buf {
15300 set_palette_pred(buf.clone(), fctx);
15301 }
15302 luma_grid = read_plane(
15303 dec,
15304 cdfs,
15305 if intrabc_dv.is_some() {
15306 txbset_for_inter(8, reduced_tx_set)
15307 } else if reduced_tx_set {
15308 TxbSet::Luma8
15309 } else {
15310 TxbSet::Luma8Set1
15311 },
15312 scans.0,
15313 0,
15314 around[0],
15315 mode,
15316 mode,
15317 angle_delta_y,
15318 reach,
15319 y,
15320 px,
15321 py,
15322 8,
15323 TX8,
15324 base_q_idx,
15325 None,
15326 filter_intra,
15327 None,
15328 smooth_neighbor, fctx,
15329 )?;
15330 // `av1_get_tx_type` branches `PLANE_TYPE_UV` on `is_inter_block`, so
15331 // an intrabc block's chroma tx_type is the colocated LUMA transform's
15332 // coded type (lane-kf900 r6's own fix, `decode_block`'s line).
15333 if intrabc_dv.is_some() {
15334 fctx.intrabc_chroma_tx.with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
15335 }
15336 let ac = alpha.map(|_| cfl_src(px, py, 8));
15337 if let Some((_, ub, _)) = &intrabc_bufs {
15338 set_palette_pred(ub.clone(), fctx);
15339 } else if let Some((ub, _)) = &palette_uv_bufs {
15340 set_palette_pred(ub.clone(), fctx);
15341 }
15342 u_grid = read_plane(
15343 dec,
15344 cdfs,
15345 TxbSet::Chroma4,
15346 scans.1,
15347 1,
15348 around[1],
15349 mode,
15350 uv_predict_mode,
15351 angle_delta_uv,
15352 reach,
15353 u,
15354 cpx,
15355 cpy,
15356 4,
15357 TX4,
15358 base_q_idx,
15359 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15360 None,
15361 None,
15362 smooth_neighbor_uv, fctx,
15363 )?;
15364 if let Some((_, _, vb)) = &intrabc_bufs {
15365 set_palette_pred(vb.clone(), fctx);
15366 } else if let Some((_, vb)) = &palette_uv_bufs {
15367 set_palette_pred(vb.clone(), fctx);
15368 }
15369 v_grid = read_plane(
15370 dec,
15371 cdfs,
15372 TxbSet::Chroma4,
15373 scans.1,
15374 2,
15375 around[2],
15376 mode,
15377 uv_predict_mode,
15378 angle_delta_uv,
15379 reach,
15380 v,
15381 cpx,
15382 cpy,
15383 4,
15384 TX4,
15385 base_q_idx,
15386 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15387 None,
15388 None,
15389 smooth_neighbor_uv, fctx,
15390 )?;
15391 // Disarm: `INTRABC_CHROMA_TX` is `Some` across exactly this block's
15392 // two chroma reads (`decode_block`'s own tail does the same) -- left
15393 // set, every later chroma block would inherit this luma tx_type,
15394 // which picks the scan and the inverse transform.
15395 fctx.intrabc_chroma_tx.with(|c| c.set(None));
15396 } else {
15397 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
15398 // grid of 4x4 transform units, each predicted from the leaf's own
15399 // 8x8 `mode` and reading its own fresh context off the earlier
15400 // units in this same leaf (the same per-TU pattern `decode_block`'s
15401 // multi-TU branch runs at bigger blocks).
15402 for tu_row in 0..2 {
15403 for tu_col in 0..2 {
15404 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
15405 let tu_px = px + tu_col * 4;
15406 let tu_py = py + tu_row * 4;
15407 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
15408 if crate::encode::Reach::in_vert_ab() {
15409 hit!(VERT_AB_TX4_HITS);
15410 }
15411 let tu_reach = tu_reach(
15412 8,
15413 8,
15414 tu_col * 4,
15415 tu_row * 4,
15416 4,
15417 reach,
15418 px,
15419 py,
15420 y.width,
15421 y.height, fctx,
15422 );
15423 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
15424 // Each 4x4 unit predicts from its own window of the block's
15425 // 8x8 colour-index map ([`decode_block`]'s per-TU slice at
15426 // 16x16 and up) -- the whole-block buffer would be taken by
15427 // the FIRST unit and indexed at the wrong stride.
15428 if let Some(buf) = &palette_y_buf {
15429 hit!(PALETTE_SPLIT_TX_HITS);
15430 let mut window = vec![0u16; 16];
15431 for row in 0..4 {
15432 let src = (tu_row * 4 + row) * 8 + tu_col * 4;
15433 window[row * 4..][..4].copy_from_slice(&buf[src..][..4]);
15434 }
15435 set_palette_pred(window, fctx);
15436 }
15437 let tu_grid = read_plane(
15438 dec,
15439 cdfs,
15440 if intrabc_dv.is_some() {
15441 txbset_for_inter(4, reduced_tx_set)
15442 } else if reduced_tx_set {
15443 TxbSet::Luma4
15444 } else {
15445 TxbSet::Luma4Set1
15446 },
15447 scans.1,
15448 0,
15449 tu_around,
15450 mode,
15451 mode,
15452 angle_delta_y,
15453 tu_reach,
15454 y,
15455 tu_px,
15456 tu_py,
15457 4,
15458 4,
15459 base_q_idx,
15460 None,
15461 filter_intra,
15462 Some(tu_skip_ctx),
15463 smooth_neighbor, fctx,
15464 )?;
15465 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15466 eprintln!(
15467 "TRACE tu_bitpos mi=({},{}) tell={}",
15468 tu_mi.0,
15469 tu_mi.1,
15470 dec.debug_bitpos()
15471 );
15472 }
15473 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
15474 }
15475 }
15476 let ac = alpha.map(|_| cfl_src(px, py, 8));
15477 let chroma_around = neighbours.around_mi(leaf_mi, 8);
15478 if let Some((ub, _)) = &palette_uv_bufs {
15479 set_palette_pred(ub.clone(), fctx);
15480 }
15481 u_grid = read_plane(
15482 dec,
15483 cdfs,
15484 TxbSet::Chroma4,
15485 scans.1,
15486 1,
15487 chroma_around[1],
15488 mode,
15489 uv_predict_mode,
15490 angle_delta_uv,
15491 reach,
15492 u,
15493 cpx,
15494 cpy,
15495 4,
15496 TX4,
15497 base_q_idx,
15498 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15499 None,
15500 None,
15501 smooth_neighbor_uv, fctx,
15502 )?;
15503 if let Some((_, vb)) = &palette_uv_bufs {
15504 set_palette_pred(vb.clone(), fctx);
15505 }
15506 v_grid = read_plane(
15507 dec,
15508 cdfs,
15509 TxbSet::Chroma4,
15510 scans.1,
15511 2,
15512 chroma_around[2],
15513 mode,
15514 uv_predict_mode,
15515 angle_delta_uv,
15516 reach,
15517 v,
15518 cpx,
15519 cpy,
15520 4,
15521 TX4,
15522 base_q_idx,
15523 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15524 None,
15525 None,
15526 smooth_neighbor_uv, fctx,
15527 )?;
15528 // `record_split_luma` expects a `record`-style `(r, c)` position in
15529 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
15530 // already in mi units, so calling it here double-scaled the
15531 // position. Plane 0 is already correct per-TU from the
15532 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
15533 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
15534 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
15535 // leaf's own 8x8 side over `MI`).
15536 let side_mi = 2;
15537 for cell in 0..side_mi {
15538 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
15539 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
15540 }
15541 let round_up_even = |n: usize| n.div_ceil(2) * 2;
15542 let bound_h = round_up_even(neighbours.mi_rows);
15543 let bound_w = round_up_even(neighbours.mi_cols);
15544 let u_state = neighbour_state(&u_grid);
15545 let v_state = neighbour_state(&v_grid);
15546 for cell in 0..side_mi {
15547 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
15548 neighbours.left[leaf_mi.0 + cell][1] = u_state;
15549 neighbours.left[leaf_mi.0 + cell][2] = v_state;
15550 }
15551 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
15552 neighbours.above[leaf_mi.1 + cell][1] = u_state;
15553 neighbours.above[leaf_mi.1 + cell][2] = v_state;
15554 }
15555 }
15556 // This leaf's own palette state into the mi-granular above/left bands
15557 // (sizes 0 when it used none, which is what clears a previous block's
15558 // palette out of the next block's ctx and colour cache).
15559 {
15560 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
15561 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
15562 }
15563 neighbours.fill_skip_grid(leaf_mi, 2, skip);
15564 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0, fctx);
15565 // lane-t900 r32: `set_txfm_ctxs` for an 8x8 leaf -- see `decode_block`'s
15566 // own copy; only an intrabc var-tx read consumes these bands on the intra
15567 // path, so the write is armed by `allow_intrabc`.
15568 if allow_intrabc {
15569 set_txfm_ctxs(neighbours, leaf_mi, 4, 2, 2, skip && intrabc_dv.is_some());
15570 }
15571 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
15572 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, fctx);
15573 return Ok(mode);
15574 }
15575 neighbours.record_mi(leaf_mi, 8, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
15576 // This leaf's own palette state into the mi-granular above/left bands
15577 // (sizes 0 when it used none, which is what clears a previous block's
15578 // palette out of the next block's ctx and colour cache).
15579 {
15580 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
15581 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
15582 }
15583 hit!(INTER8_SKIP_BAND_HITS);
15584 neighbours.fill_skip_grid(leaf_mi, 2, skip);
15585 // lane-kf900 r1: the leaf's own RESOLVED transform size, never the literal
15586 // block side. libaom calls `set_txfm_ctxs(mbmi->tx_size, ..., skip_txfm &&
15587 // is_inter_block(mbmi), xd)` (decodemv.c) -- for an INTRA block that skip
15588 // term is always 0, so a skipped 8x8 leaf whose `tx_depth` resolved to
15589 // TX_4X4 still publishes 4 to the next block's `get_tx_size_context`
15590 // (pred_common.h:342). Writing 8 here made the 8x16 strip below the leaf
15591 // read `tx_size_cat1` row 2 where libaom reads row 1 -- same alphabet,
15592 // wrong CDF row, so the msac range diverged mid-frame with no refusal
15593 // (class `wrong-alphabet-same-value`; the ReelB key frame at
15594 // -ss 900, first bad luma sample row 186 col 1803).
15595 neighbours.fill_lf_grid(leaf_mi, 2, resolved as u8, 0, fctx);
15596 // lane-t900 r32: `set_txfm_ctxs` for an 8x8 leaf -- see `decode_block`'s
15597 // own copy; only an intrabc var-tx read consumes these bands on the intra
15598 // path, so the write is armed by `allow_intrabc`.
15599 if allow_intrabc {
15600 set_txfm_ctxs(neighbours, leaf_mi, resolved, 2, 2, skip && intrabc_dv.is_some());
15601 }
15602 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
15603 // The DV predictor of a LATER intrabc block is the ordinary `INTRA_FRAME`
15604 // MV stack over this grid (`av1_find_mv_refs`), so an 8x8 leaf has to
15605 // publish its own cells exactly like `decode_block` does.
15606 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, fctx);
15607 Ok(mode)
15608}
15609
15610/// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf
15611/// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8`
15612/// bottom, where no partition symbol is read at all -- `decode_block` runs
15613/// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec
15614/// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always
15615/// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference`
15616/// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf
15617/// of the 2x2 4x4 group carries chroma syntax at all.
15618#[allow(clippy::too_many_arguments)]
15619fn read_intra_mode_sub8(
15620 dec: &mut SymbolDecoder,
15621 cdfs: &mut Cdfs,
15622 above_mode: usize,
15623 left_mode: usize,
15624 has_chroma: bool,
15625 enable_filter_intra: bool,
15626 // [`filter_intra_size_class_rect`] for the LEAF's own shape: 0 for a
15627 // `BLOCK_4X4` split leaf, 8/9 for a 4x8/8x4 rect leaf. Reading the flag
15628 // from the wrong row is the same VALUE with a different interval, so it
15629 // desyncs a block or two later, not here (class `wrong-alphabet-same-value`).
15630 fi_class: usize,
15631 skip_ctx: usize,
15632 allow_intrabc: bool,
15633 mi_r: usize,
15634 mi_c: usize, fctx: &crate::decode::FrameCtx,
15635) -> Result<(bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option<usize>)> {
15636 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
15637 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
15638 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sub8 rng={}", dec.debug_state().0);
15639 }
15640 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
15641 if trace {
15642 eprintln!("TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}", skip as i32, dec.debug_state().0);
15643 }
15644 maybe_read_cdef_idx(dec, mi_r, mi_c, skip, fctx);
15645 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
15646 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
15647 if allow_intrabc {
15648 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
15649 if use_intrabc {
15650 return Err(unsupported(
15651 "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)",
15652 ));
15653 }
15654 }
15655 let above_ctx = INTRA_MODE_CTX[above_mode];
15656 let left_ctx = INTRA_MODE_CTX[left_mode];
15657 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
15658 if trace {
15659 eprintln!("TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
15660 }
15661 // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/
15662 // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`,
15663 // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta
15664 // symbol. Reading one consumed a symbol the encoder never wrote and
15665 // desynced the tile at the very next element.
15666 let angle_delta_y = 0;
15667 let chroma = if has_chroma {
15668 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
15669 if trace {
15670 eprintln!("TRACE sub8 uv_mode value={uv_mode} rng={}", dec.debug_state().0);
15671 }
15672 if (9..=12).contains(&uv_mode) {
15673 hit!(SMOOTH_UV_HITS);
15674 }
15675 let alpha = if uv_mode == UV_CFL_PRED {
15676 Some(read_cfl_alphas(dec, cdfs))
15677 } else {
15678 None
15679 };
15680 if (V_PRED..=D67_PRED).contains(&uv_mode) {
15681 hit!(DIRECTIONAL_UV_HITS);
15682 }
15683 // See the luma comment above: no angle delta below 8x8.
15684 let angle_delta_uv = 0;
15685 Some((uv_mode, angle_delta_uv, alpha))
15686 } else {
15687 None
15688 };
15689 let mut filter_intra = None;
15690 if mode == DC_PRED && enable_filter_intra {
15691 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0;
15692 if trace {
15693 eprintln!("TRACE sub8 use_filter_intra value={}", use_filter_intra as i32);
15694 }
15695 if use_filter_intra {
15696 hit!(FILTER_INTRA_HITS);
15697 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
15698 filter_intra = Some(fi_mode);
15699 }
15700 }
15701 Ok((skip, mode, angle_delta_y, chroma, filter_intra))
15702}
15703
15704/// Decodes a `PARTITION_SPLIT` of one 8x8 block into four `BLOCK_4X4` leaves
15705/// (spec `decode_partition`'s recursion bottom), sharing [`decode_leaf8`]'s
15706/// own signature so its caller's `prev_leaf`/`above_mode`/`left_mode`
15707/// bookkeeping needs no change. Each leaf reads its own luma mode info,
15708/// neighboured off the *previously decoded leaf in this same group* on
15709/// whichever axis is adjacent (mirroring [`decode_leaf8`]'s own `prev_leaf`
15710/// pattern, one level deeper); chroma is read and reconstructed exactly
15711/// once, on the last (bottom-right) leaf, at the whole 8x8 group's own 4x4
15712/// chroma unit -- [`read_intra_mode_sub8`]'s doc has the `is_chroma_reference`
15713/// derivation.
15714#[allow(clippy::too_many_arguments)]
15715fn decode_leaf_split4(
15716 dec: &mut SymbolDecoder,
15717 cdfs: &mut Cdfs,
15718 neighbours: &mut Neighbours,
15719 outer_at: (usize, usize),
15720 leaf_mi: (usize, usize),
15721 scan4: &[u16],
15722 prev_leaf: Option<((usize, usize), usize)>,
15723 y: &mut PlaneBuf<'static>,
15724 u: &mut PlaneBuf<'static>,
15725 v: &mut PlaneBuf<'static>,
15726 base_q_idx: u8,
15727 enable_filter_intra: bool,
15728 allow_intrabc: bool,
15729 reduced_tx_set: bool,
15730 // Returns `(below_mode, right_mode)`: the mode a neighbour BELOW this 8x8
15731 // group sees (its bottom-left 4x4, libaom reads mi(row-1, col)) and the
15732 // one a neighbour to its RIGHT sees (its top-right 4x4, mi(row, col-1))., fctx: &crate::decode::FrameCtx
15733 fctx: &crate::decode::FrameCtx,
15734) -> Result<(usize, usize)> {
15735 hit!(SUB8_SPLIT_HITS);
15736 let (r, c) = outer_at;
15737 let mut above_mode = neighbours.above_mode[c];
15738 let mut left_mode = neighbours.left_mode[r];
15739 if let Some(((pr, pc), pmode)) = prev_leaf {
15740 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
15741 above_mode = pmode;
15742 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
15743 left_mode = pmode;
15744 }
15745 }
15746 // See `decode_leaf8`'s own `smooth_neighbor_uv`: the chroma edge-filter
15747 // type is the chroma neighbours' `uv_mode`, mi-exact where recorded.
15748 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
15749 let mut leaf_modes = [0usize; 4];
15750 let mut leaf_skips = [false; 4];
15751 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
15752 for i in 0..4usize {
15753 let (dr, dc) = (i / 2, i % 2);
15754 let lmi = (leaf_mi.0 + dr, leaf_mi.1 + dc);
15755 // Neighbour modes at real mi granularity: inside the group the
15756 // sibling leaf, outside it the split-leaf map when the adjacent mi
15757 // was itself a 4x4 leaf, else the coarse 16x16 slot (see
15758 // `sub8_mode_col`'s doc).
15759 let leaf_above = if dr == 0 {
15760 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
15761 } else {
15762 leaf_modes[i - 2]
15763 };
15764 let leaf_left = if dc == 0 {
15765 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
15766 } else {
15767 leaf_modes[i - 1]
15768 };
15769 let has_chroma = i == 3;
15770 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
15771 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
15772 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
15773 filter_intra_size_class(4).expect("BLOCK_4X4 has its own filter_intra row"),
15774 skip_ctx, allow_intrabc, lmi.0, lmi.1, fctx,
15775 )?;
15776 leaf_modes[i] = mode;
15777 leaf_skips[i] = skip;
15778 neighbours.record_mode_mi(lmi.0, lmi.1, 1, 1, mode);
15779 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
15780 if smooth_neighbor {
15781 hit!(SMOOTH_LUMA_HITS);
15782 }
15783 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
15784 let reach = Reach::of(4, px, py, y.width, y.height, fctx);
15785 if skip {
15786 push_intra(0, px, py, 4, mode, angle_delta_y, reach, &ZERO_RESIDUAL[..16], None, filter_intra, smooth_neighbor, fctx);
15787 neighbours.record_mi_luma(lmi, 4, &ZERO_RESIDUAL[..16]);
15788 } else {
15789 let tu_around = neighbours.around_mi(lmi, 4)[0];
15790 // A `BLOCK_4X4` leaf's luma TU *is* the whole block, so libaom's
15791 // `get_txb_ctx` takes its `plane_bsize == txsize_to_bsize[tx_size]`
15792 // branch: `txb_skip_ctx = 0`, never the neighbour-magnitude table
15793 // (`txb_common.h:400`). Reading the table here decoded `all_zero`
15794 // off the wrong CDF on the very first leaf and desynced the tile.
15795 let tu_grid = read_plane(
15796 dec,
15797 cdfs,
15798 if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 },
15799 scan4,
15800 0,
15801 tu_around,
15802 mode,
15803 mode,
15804 angle_delta_y,
15805 reach,
15806 y,
15807 px,
15808 py,
15809 4,
15810 4,
15811 base_q_idx,
15812 None,
15813 filter_intra,
15814 None,
15815 smooth_neighbor, fctx,
15816 )?;
15817 neighbours.record_mi_luma(lmi, 4, &tu_grid);
15818 }
15819 neighbours.fill_skip_grid(lmi, 1, skip);
15820 neighbours.fill_lf_grid(lmi, 1, 4, 0, fctx);
15821 if has_chroma {
15822 last_uv = chroma;
15823 }
15824 }
15825 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
15826 let (cpx, cpy) = (gpx / 2, gpy / 2);
15827 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx);
15828 let (uv_mode, angle_delta_uv, alpha) =
15829 last_uv.expect("i==3 always sets has_chroma, so chroma is always Some");
15830 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
15831 neighbours.above_uv_mode[c] = uv_predict_mode;
15832 neighbours.left_uv_mode[r] = uv_predict_mode;
15833 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
15834 let (u_grid, v_grid): (Grid, Grid) = if leaf_skips[3] {
15835 // A skipped chroma block still gets its CfL contribution: libaom's
15836 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
15837 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
15838 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
15839 // added -- `skip_txfm` only drops the residual, never the alpha.
15840 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
15841 // merge keeps one fix and feeds both lanes' counters so neither of
15842 // their gates goes vacuous.
15843 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
15844 if alpha.is_some() {
15845 hit!(CHROMA_SKIP_CFL_HITS);
15846 hit!(SKIP_CFL_HITS);
15847 }
15848 push_intra(1, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx);
15849 push_intra(2, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx);
15850 (Grid::Zero(16), Grid::Zero(16))
15851 } else {
15852 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
15853 let chroma_around = neighbours.around_mi(leaf_mi, 8);
15854 let ug = read_plane(
15855 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
15856 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
15857 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx,
15858 )?;
15859 let vg = read_plane(
15860 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
15861 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
15862 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx,
15863 )?;
15864 (ug, vg)
15865 };
15866 // Chroma neighbour bookkeeping for the whole 8x8 group -- mirrors
15867 // [`decode_leaf8`]'s own tx4-chroma section (`record_split_luma`'s
15868 // rescaling is wrong for an already-mi-unit position, so this inlines
15869 // its tail directly at `leaf_mi`, side_mi=2), EXCEPT for the partition
15870 // context value itself. Unlike `decode_leaf8`'s TX4 branch (still one
15871 // `BLOCK_8X8`, `PARTITION_NONE`, transform depth only), this group is
15872 // genuinely four `BLOCK_4X4` blocks (`PARTITION_SPLIT` at the 8x8
15873 // level, libaom `decode_partition`'s `bsize2`/`subsize` recursion
15874 // bottom). libaom's `update_ext_partition_context` writes
15875 // `partition_context_lookup[subsize]` at the 8x8 slot -- `{30,30}` for
15876 // `BLOCK_8X8` (bit0=0, what `decode_leaf8` already reproduces via
15877 // side_mi=8) but `{31,31}` for `BLOCK_4X4` (bit0=1) here, and
15878 // `partition_ctx_mi`'s `left_side_mi[mi_r]*2 <= side` needs
15879 // `left_side_mi <= 4` to read that bit as 1. Leaving this at 8 (this
15880 // round's bug) makes the very next sibling 8x8's `partition_w8` read
15881 // with the wrong context and desync immediately.
15882 let side_mi = 2;
15883 for cell in 0..side_mi {
15884 neighbours.left_side_mi[leaf_mi.0 + cell] = 4;
15885 neighbours.above_side_mi[leaf_mi.1 + cell] = 4;
15886 }
15887 let round_up_even = |n: usize| n.div_ceil(2) * 2;
15888 let bound_h = round_up_even(neighbours.mi_rows);
15889 let bound_w = round_up_even(neighbours.mi_cols);
15890 let u_state = neighbour_state(&u_grid);
15891 let v_state = neighbour_state(&v_grid);
15892 for cell in 0..side_mi {
15893 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
15894 neighbours.left[leaf_mi.0 + cell][1] = u_state;
15895 neighbours.left[leaf_mi.0 + cell][2] = v_state;
15896 }
15897 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
15898 neighbours.above[leaf_mi.1 + cell][1] = u_state;
15899 neighbours.above[leaf_mi.1 + cell][2] = v_state;
15900 }
15901 }
15902 // lane-dkey: a sub-8x8 leaf can never use palette (`av1_allow_palette`
15903 // needs BLOCK_8X8 and up), and libaom's mi grid says so -- its
15904 // `palette_size` is 0 in every one of these mi cells, so the NEXT block's
15905 // `av1_get_palette_mode_ctx` and colour cache read 0 here. This decoder
15906 // only ever WROTE palette state from the >=8x8 readers, so an 8x8 palette
15907 // block above a 4x4 group left its size/colours standing in the mi-granular
15908 // bands: the block below the group read `palette_y_mode` off CDF row 1
15909 // where libaom reads row 0 (class [[cdf-row-held-constant]]), decoded a
15910 // palette libaom never coded, and then skipped the `use_filter_intra`
15911 // symbol that a palette block has none of -- one symbol short, tile
15912 // desynced. Publishing the group's own zeros is the clear.
15913 neighbours.record_palette_y_rect(leaf_mi, 8, 8, 0, [0u16; 8]);
15914 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, 0, [0u16; 8]);
15915 Ok((leaf_modes[2], leaf_modes[1]))
15916}
15917
15918/// Decodes a `PARTITION_VERT`/`PARTITION_HORZ` of one 8x8 block into two
15919/// `BLOCK_4X8`/`BLOCK_8X4` leaves (lane-tx4x8), the last partition shape
15920/// below 8x8 this decoder refused. Mirrors [`decode_leaf_split4`] element for
15921/// element -- same mode reads ([`read_intra_mode_sub8`]: no angle delta, no
15922/// tx-depth symbol below 8x8), same "chroma once, on the last sub-block, at
15923/// the whole 8x8 group's 4x4 unit" rule (`is_chroma_reference` is false for
15924/// every sub-block one mi wide or high but the last) -- differing only where
15925/// the shape does:
15926///
15927/// * the transform is a true `TX_4X8`/`TX_8X4`
15928/// ([`dequant_and_inverse_typed_wh`], whose `abs(rect_type) == 1` scale and
15929/// `av1_inv_txfm_shift_ls` row already cover this size pair);
15930/// * the CDF set is [`TxbSet::LumaRect4x8`] (`get_txsize_entropy_ctx` squares
15931/// up to `TX_8X8`) with a 32-position `eob_pt` and the `TX_4X4` `tx_type`
15932/// row -- see that variant's doc comment;
15933/// * the scan is [`SCAN_4X8`]/[`SCAN_8X4`], or their `mrow`/`mcol` siblings
15934/// ([`class_scan_table_wh`]) when the coded `tx_type` is `V_DCT`/`H_DCT`;
15935/// * `Reach` comes from libaom's own `has_tr_4x8`/`has_bl_8x4` rows
15936/// ([`Reach::of_rect`]);
15937/// * `update_partition_context` writes `partition_context_lookup[BLOCK_4X8]`
15938/// = `{31, 30}` (width 4 above, height 8 left), not the `{31, 31}` a
15939/// `BLOCK_4X4` split writes.
15940///
15941/// Filter intra on one of these leaves is decoded (lane-fi8 r1): the flag is
15942/// read from `BLOCK_4X8`/`BLOCK_8X4`'s own `cdf::FILTER_INTRA` row (classes
15943/// 8/9, NOT `BLOCK_4X4`'s), the predictor is [`crate::intra::predict_filter_intra`]
15944/// over the leaf's true `bw`x`bh` -- per 4x4 transform unit, with that unit's
15945/// own edge, when `tx_depth` splits it -- and the coded `tx_type` row is
15946/// [`fi_tx_row`]'s `fimode_to_intradir`, not the block's raw `DC_PRED`.
15947#[allow(clippy::too_many_arguments)]
15948fn decode_leaf_rect8(
15949 dec: &mut SymbolDecoder,
15950 cdfs: &mut Cdfs,
15951 neighbours: &mut Neighbours,
15952 outer_at: (usize, usize),
15953 leaf_mi: (usize, usize),
15954 vert: bool,
15955 scan4: &[u16],
15956 y: &mut PlaneBuf<'static>,
15957 u: &mut PlaneBuf<'static>,
15958 v: &mut PlaneBuf<'static>,
15959 base_q_idx: u8,
15960 enable_filter_intra: bool,
15961 allow_intrabc: bool,
15962 tx_select: bool,
15963 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
15964) -> Result<(usize, usize)> {
15965 let (r, c) = outer_at;
15966 // lane-modectx r1: availability-correct fallback pair (see
15967 // `modes_above_left`), not the raw coarse bands.
15968 let (above_mode, left_mode) = neighbours.modes_above_left(r, c);
15969 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
15970 let (bw, bh) = if vert { (4, 8) } else { (8, 4) };
15971 let (w_mi, h_mi) = (bw / MI, bh / MI);
15972 let scan: &[u16] = if vert { &SCAN_4X8 } else { &SCAN_8X4 };
15973 let mut leaf_modes = [0usize; 2];
15974 let mut leaf_skips = [false; 2];
15975 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
15976 for i in 0..2usize {
15977 let lmi = if vert {
15978 (leaf_mi.0, leaf_mi.1 + i)
15979 } else {
15980 (leaf_mi.0 + i, leaf_mi.1)
15981 };
15982 // Inside the pair the sibling is the neighbour on the split axis;
15983 // outside it the mi-granular map, else the coarse 16x16 slot.
15984 let leaf_above = if !vert && i == 1 {
15985 leaf_modes[0]
15986 } else {
15987 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
15988 };
15989 let leaf_left = if vert && i == 1 {
15990 leaf_modes[0]
15991 } else {
15992 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
15993 };
15994 let has_chroma = i == 1;
15995 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
15996 let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8(
15997 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
15998 filter_intra_size_class_rect(bw, bh)
15999 .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize"),
16000 skip_ctx, allow_intrabc, lmi.0, lmi.1, fctx,
16001 )?;
16002 if filter_intra.is_some() {
16003 // lane-fi8 r1: `predict_filter_intra` walks its 4x2 patches over
16004 // a true `bw`x`bh` block, so a 4x8/8x4 leaf predicts through the
16005 // same `reconstruct_rect`/`reconstruct` calls below -- and under
16006 // a split transform, per 4x4 unit with that unit's own edge,
16007 // which is exactly what the depth-1 loop already does.
16008 hit!(FILTER_INTRA_RECT_HITS);
16009 hit!(FILTER_INTRA_RECT_SUB8_HITS);
16010 }
16011 // `TxMode::Select`'s `tx_depth` (spec 5.11.16) exists at a 4x8/8x4
16012 // leaf too, and is read for every intra block, skipped or not. Its
16013 // category is libaom's `bsize_to_tx_size_cat(BLOCK_4X8) == 0` --
16014 // `sub_tx_size_map[TX_4X8] == TX_4X4` is a single step, so it is the
16015 // same 2-symbol `tx_size_cat0` an 8x8 uses, not the 3-symbol
16016 // `tx_size_cat2` the 32x16 strips read -- with the rect context
16017 // (`get_tx_size_context`'s `max_tx_wide`/`max_tx_high` = bw/bh).
16018 // Missing this read consumed one symbol fewer than the encoder wrote
16019 // and desynced the tile at the very first rect leaf (class
16020 // `symbol-consumption-gap`).
16021 let depth = if tx_select {
16022 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band
16023 // read every other rect reader now does -- a no-op on a key frame.
16024 let ctx = if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
16025 tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx)
16026 } else {
16027 tx_size_context_rect(neighbours, lmi, bw, bh)
16028 };
16029 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
16030 } else {
16031 0
16032 };
16033 if depth != 0 {
16034 hit!(TX_DEPTH_HITS);
16035 hit!(RECT8_SPLIT_TX_HITS);
16036 }
16037 leaf_modes[i] = mode;
16038 leaf_skips[i] = skip;
16039 neighbours.record_mode_mi(lmi.0, lmi.1, w_mi, h_mi, mode);
16040 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
16041 if smooth_neighbor {
16042 hit!(SMOOTH_LUMA_HITS);
16043 }
16044 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
16045 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
16046 // `sub_tx_size_map[TX_4X8] == TX_4X4`: depth 1 splits the leaf into
16047 // two 4x4 transform units along its long axis, each predicted from
16048 // the previous unit's reconstruction and reading its own `txb_skip`
16049 // context -- `decode_leaf8`'s own depth-1 loop, two units instead of
16050 // four. The per-TU path writes its own neighbour state, so the
16051 // block-level write below is skipped for it.
16052 let split = depth != 0 || lossless(fctx);
16053 if split {
16054 let mut done = 0usize;
16055 for tu in 0..2usize {
16056 let tu_mi = if vert {
16057 (lmi.0 + tu, lmi.1)
16058 } else {
16059 (lmi.0, lmi.1 + tu)
16060 };
16061 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);
16062 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
16063 // Same per-TU rule as every other split-transform site
16064 // (lane-palette2 r12): a transform unit inside a block is not
16065 // a block at that position, so its reach comes from the
16066 // block's own row, offset by the unit's position.
16067 let tu_reach = tu_reach(
16068 bw,
16069 bh,
16070 tu_px - px,
16071 tu_py - py,
16072 4,
16073 reach,
16074 px,
16075 py,
16076 y.width,
16077 y.height, fctx,
16078 );
16079 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
16080 if skip {
16081 // A skipped leaf still predicts per transform unit: the
16082 // second 4x4 takes its above/left edge from the first
16083 // one's reconstruction, which is NOT what a single 4x8
16084 // prediction of the same mode produces.
16085 let zeros = vec![0i32; 16];
16086 push_intra(0,
16087 tu_px, tu_py, 4, mode, angle_delta_y, tu_reach, &zeros, None,
16088 filter_intra, smooth_neighbor, fctx,
16089 );
16090 neighbours.record_mi_luma(tu_mi, 4, &zeros);
16091 continue;
16092 }
16093 let tu_grid = read_plane(
16094 dec,
16095 cdfs,
16096 if reduced_tx_set {
16097 TxbSet::Luma4
16098 } else {
16099 TxbSet::Luma4Set1
16100 },
16101 scan4,
16102 0,
16103 tu_around,
16104 mode,
16105 mode,
16106 angle_delta_y,
16107 tu_reach,
16108 y,
16109 tu_px,
16110 tu_py,
16111 4,
16112 TX4,
16113 base_q_idx,
16114 None,
16115 filter_intra,
16116 Some(tu_skip_ctx),
16117 smooth_neighbor, fctx,
16118 )?;
16119 if tu_grid.iter().any(|&l| l != 0) {
16120 done += 1;
16121 }
16122 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
16123 }
16124 if done > 0 {
16125 if vert {
16126 hit!(TX4X8_CODED_HITS);
16127 } else {
16128 hit!(TX8X4_CODED_HITS);
16129 }
16130 }
16131 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
16132 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, 4, 4, 0, fctx);
16133 if has_chroma {
16134 last_uv = chroma;
16135 }
16136 continue;
16137 }
16138 let grid = if skip {
16139 let zeros = Grid::Zero(bw * bh);
16140 push_intra_rect(0,
16141 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
16142 smooth_neighbor, fctx,
16143 );
16144 zeros
16145 } else {
16146 // `plane_bsize == txsize_to_bsize[tx_size]` here too (the leaf's
16147 // luma TU *is* the leaf), so `get_txb_ctx` fixes `txb_skip_ctx`
16148 // at 0 -- see `decode_leaf_split4`'s own note.
16149 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
16150 let set = if reduced_tx_set {
16151 TxbSet::LumaRect4x8
16152 } else {
16153 TxbSet::LumaRect4x8Set1
16154 };
16155 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
16156 let (levels, tx_type) = read_coeffs_rect(
16157 dec,
16158 &mut coding,
16159 scan,
16160 bw,
16161 bh,
16162 0,
16163 dc_sign_ctx(around.2),
16164 TxType::DctDct,
16165 )?;
16166 if levels.iter().any(|&l| l != 0) {
16167 if vert {
16168 hit!(TX4X8_CODED_HITS);
16169 } else {
16170 hit!(TX8X4_CODED_HITS);
16171 }
16172 }
16173 let residual = dequant_and_inverse_typed_wh(
16174 &levels,
16175 bw,
16176 bh,
16177 crate::decode::bit_depth(fctx),
16178 fctx.current_q_idx.with(|q| q.get()),
16179 plane_q_delta(0, fctx).0,
16180 plane_q_delta(0, fctx).1,
16181 tx_type,
16182 );
16183 push_intra_rect(0,
16184 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
16185 smooth_neighbor, fctx,
16186 );
16187 levels
16188 };
16189 // Plane 0's per-TU coefficient context over this leaf's own mi span
16190 // (`record_mi_luma`'s rect twin -- the chroma planes are written once
16191 // for the whole 8x8 group below).
16192 let state = neighbour_state(&grid);
16193 for cell in 0..h_mi {
16194 if lmi.0 + cell < neighbours.mi_rows {
16195 neighbours.left[lmi.0 + cell][0] = state;
16196 }
16197 }
16198 for cell in 0..w_mi {
16199 if lmi.1 + cell < neighbours.mi_cols {
16200 neighbours.above[lmi.1 + cell][0] = state;
16201 }
16202 }
16203 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
16204 let (tx_w, tx_h) = if split { (4, 4) } else { (bw as u8, bh as u8) };
16205 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, tx_w, tx_h, 0, fctx);
16206 if has_chroma {
16207 last_uv = chroma;
16208 }
16209 }
16210 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
16211 let (cpx, cpy) = (gpx / 2, gpy / 2);
16212 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx);
16213 let (uv_mode, angle_delta_uv, alpha) =
16214 last_uv.expect("i==1 always sets has_chroma, so chroma is always Some");
16215 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
16216 neighbours.above_uv_mode[c] = uv_predict_mode;
16217 neighbours.left_uv_mode[r] = uv_predict_mode;
16218 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
16219 let (u_grid, v_grid): (Grid, Grid) = if leaf_skips[1] {
16220 // A skipped chroma block still gets its CfL contribution: libaom's
16221 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
16222 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
16223 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
16224 // added -- `skip_txfm` only drops the residual, never the alpha.
16225 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
16226 // merge keeps one fix and feeds both lanes' counters so neither of
16227 // their gates goes vacuous.
16228 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
16229 if alpha.is_some() {
16230 hit!(CHROMA_SKIP_CFL_HITS);
16231 hit!(SKIP_CFL_HITS);
16232 }
16233 push_intra(1, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx);
16234 push_intra(2, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx);
16235 (Grid::Zero(16), Grid::Zero(16))
16236 } else {
16237 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
16238 let chroma_around = neighbours.around_mi(leaf_mi, 8);
16239 let ug = read_plane(
16240 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
16241 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
16242 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx,
16243 )?;
16244 let vg = read_plane(
16245 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
16246 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
16247 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx,
16248 )?;
16249 (ug, vg)
16250 };
16251 // `update_partition_context` at the 8x8 level writes
16252 // `partition_context_lookup[subsize]` over the whole 8x8 span: BLOCK_4X8
16253 // is `{31, 30}` (bit0 set on the above half only), BLOCK_8X4 `{30, 31}`
16254 // -- the mirror of `decode_leaf_split4`'s `{31, 31}`, which
16255 // `partition_ctx_mi` reads back off these side values.
16256 for cell in 0..2 {
16257 neighbours.above_side_mi[leaf_mi.1 + cell] = bw as u8;
16258 neighbours.left_side_mi[leaf_mi.0 + cell] = bh as u8;
16259 }
16260 let round_up_even = |n: usize| n.div_ceil(2) * 2;
16261 let bound_h = round_up_even(neighbours.mi_rows);
16262 let bound_w = round_up_even(neighbours.mi_cols);
16263 let u_state = neighbour_state(&u_grid);
16264 let v_state = neighbour_state(&v_grid);
16265 for cell in 0..2usize {
16266 if cell < 2usize.min(bound_h.saturating_sub(leaf_mi.0)) {
16267 neighbours.left[leaf_mi.0 + cell][1] = u_state;
16268 neighbours.left[leaf_mi.0 + cell][2] = v_state;
16269 }
16270 if cell < 2usize.min(bound_w.saturating_sub(leaf_mi.1)) {
16271 neighbours.above[leaf_mi.1 + cell][1] = u_state;
16272 neighbours.above[leaf_mi.1 + cell][2] = v_state;
16273 }
16274 }
16275 // lane-dkey (same clear as `decode_leaf_split4`): a sub-8x8 leaf can never use palette (`av1_allow_palette`
16276 // needs BLOCK_8X8 and up), and libaom's mi grid says so -- its
16277 // `palette_size` is 0 in every one of these mi cells, so the NEXT block's
16278 // `av1_get_palette_mode_ctx` and colour cache read 0 here. This decoder
16279 // only ever WROTE palette state from the >=8x8 readers, so an 8x8 palette
16280 // block above a 4x4 group left its size/colours standing in the mi-granular
16281 // bands: the block below the group read `palette_y_mode` off CDF row 1
16282 // where libaom reads row 0 (class [[cdf-row-held-constant]]), decoded a
16283 // palette libaom never coded, and then skipped the `use_filter_intra`
16284 // symbol that a palette block has none of -- one symbol short, tile
16285 // desynced. Publishing the group's own zeros is the clear.
16286 neighbours.record_palette_y_rect(leaf_mi, 8, 8, 0, [0u16; 8]);
16287 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, 0, [0u16; 8]);
16288 // `(below_mode, right_mode)`: the sub-block a neighbour below sees is the
16289 // bottom one (the second under HORZ, the left one under VERT), the one a
16290 // neighbour to the right sees is the top-right (the second under VERT).
16291 Ok(if vert {
16292 (leaf_modes[0], leaf_modes[1])
16293 } else {
16294 (leaf_modes[1], leaf_modes[0])
16295 })
16296}
16297
16298/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
16299/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
16300/// (mod 8) reuse the same table.
16301const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
16302 [(-1, 1), (-2, 2)],
16303 [(0, 1), (-1, 2)],
16304 [(0, 1), (0, 2)],
16305 [(0, 1), (1, 2)],
16306 [(1, 1), (2, 2)],
16307 [(1, 0), (2, 1)],
16308 [(1, 0), (2, 0)],
16309 [(1, 0), (2, -1)],
16310];
16311/// A neighbour tap outside the frame's true extent -- `constrain` reads this
16312/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
16313const CDEF_VERY_LARGE: i32 = 0x4000;
16314const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
16315const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
16316
16317fn cdef_msb(x: i32) -> i32 {
16318 31 - x.leading_zeros() as i32
16319}
16320
16321/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
16322/// centre sample a filter tap is allowed to contribute.
16323#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
16324fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
16325 if threshold == 0 {
16326 return 0;
16327 }
16328 cdef_constrain_shifted(diff, threshold, cdef_constrain_shift(threshold, damping))
16329}
16330
16331/// `constrain`'s damping shift: a function of the block's threshold and
16332/// damping alone, so the filter loop computes it once per block instead of
16333/// the `leading_zeros` + branch it used to do twice per tap read.
16334fn cdef_constrain_shift(threshold: i32, damping: i32) -> i32 {
16335 (damping - cdef_msb(threshold)).max(0)
16336}
16337
16338/// [`cdef_constrain`]'s body with the shift already resolved; `threshold` is
16339/// non-zero on every call (the caller only filters when its strength is).
16340fn cdef_constrain_shifted(diff: i32, threshold: i32, shift: i32) -> i32 {
16341 let a = diff.abs();
16342 diff.signum() * (threshold - (a >> shift)).clamp(0, a)
16343}
16344
16345/// The widest `CDEF_DIRECTIONS` offset in either axis: every tap a block reads
16346/// lies inside its own samples grown by this much.
16347const CDEF_BORDER: usize = 2;
16348
16349/// Copies one block's whole CDEF footprint -- its `bh` x `bw` samples plus the
16350/// [`CDEF_BORDER`] tap ring -- out of the *unfiltered* plane into `buf` (row
16351/// stride `bw + 2 * CDEF_BORDER`), so the direction search and the tap loops
16352/// index a small contiguous window instead of re-deriving the frame-bounds
16353/// test on every one of a pixel's ~17 tap reads. Out-of-frame positions get
16354/// `CDEF_VERY_LARGE`, exactly as the per-sample closure did.
16355fn cdef_gather(
16356 src: &[u16],
16357 stride: usize,
16358 true_w: usize,
16359 true_h: usize,
16360 ox: usize,
16361 oy: usize,
16362 bw: usize,
16363 bh: usize,
16364 buf: &mut [i16],
16365) {
16366 let bstride = bw + 2 * CDEF_BORDER;
16367 let rows = bh + 2 * CDEF_BORDER;
16368 if oy >= CDEF_BORDER
16369 && ox >= CDEF_BORDER
16370 && oy + bh + CDEF_BORDER <= true_h
16371 && ox + bw + CDEF_BORDER <= true_w
16372 {
16373 // Interior block: every tap is inside the frame, so the whole window
16374 // is `rows` contiguous runs.
16375 for r in 0..rows {
16376 let s0 = (oy - CDEF_BORDER + r) * stride + (ox - CDEF_BORDER);
16377 let src_row = &src[s0..s0 + bstride];
16378 let dst_row = &mut buf[r * bstride..r * bstride + bstride];
16379 for (d, &v) in dst_row.iter_mut().zip(src_row) {
16380 *d = v as i16;
16381 }
16382 }
16383 return;
16384 }
16385 for r in 0..rows {
16386 let ny = oy as isize + r as isize - CDEF_BORDER as isize;
16387 for c in 0..bstride {
16388 let nx = ox as isize + c as isize - CDEF_BORDER as isize;
16389 buf[r * bstride + c] =
16390 if ny < 0 || nx < 0 || ny as usize >= true_h || nx as usize >= true_w {
16391 CDEF_VERY_LARGE as i16
16392 } else {
16393 src[ny as usize * stride + nx as usize] as i16
16394 };
16395 }
16396 }
16397}
16398
16399/// libaom `cdef_find_dir_c`'s eight partial-sum arrays, row at a time: each
16400/// array takes the row, its reverse, its pairwise sums or its total added
16401/// into consecutive slots, so the 512 scalar read-modify-writes on i64 the
16402/// per-sample form did become a handful of lane-wide adds per row. i32 is
16403/// exact here: every partial is a sum of at most eight values in -128..127,
16404/// and slot 15 exists only so an eight-lane store at offset 7 fits.
16405fn cdef_find_dir_partials(win: &[i16], bstride: usize, coeff_shift: i32) -> [[i32; 16]; 8] {
16406 fn add_at<const N: usize>(dst: &mut [i32; 16], off: usize, src: &[i32; N]) {
16407 for (d, &x) in dst[off..off + N].iter_mut().zip(src.iter()) {
16408 *d += x;
16409 }
16410 }
16411 let mut partial = [[0i32; 16]; 8];
16412 for i in 0..8usize {
16413 let base = (i + CDEF_BORDER) * bstride + CDEF_BORDER;
16414 // libaom `cdef_find_dir_c`: normalise to an 8-bit sample before
16415 // accumulating, same as `constrain`'s threshold shift.
16416 let row: [i32; 8] = core::array::from_fn(|j| (i32::from(win[base + j]) >> coeff_shift) - 128);
16417 let rev: [i32; 8] = core::array::from_fn(|j| row[7 - j]);
16418 let pair: [i32; 4] = core::array::from_fn(|k| row[2 * k] + row[2 * k + 1]);
16419 let rpair: [i32; 4] = core::array::from_fn(|k| pair[3 - k]);
16420 let (p, rest) = partial.split_at_mut(1);
16421 add_at(&mut p[0], i, &row); // partial[0][i + j]
16422 add_at(&mut rest[0], i, &pair); // partial[1][i + j / 2]
16423 rest[1][i] = row.iter().sum(); // partial[2][i]
16424 add_at(&mut rest[2], i, &rpair); // partial[3][3 + i - j / 2]
16425 add_at(&mut rest[3], i, &rev); // partial[4][7 + i - j]
16426 add_at(&mut rest[4], 3 - i / 2, &row); // partial[5][3 - i / 2 + j]
16427 add_at(&mut rest[5], 0, &row); // partial[6][j]
16428 add_at(&mut rest[6], i / 2, &row); // partial[7][i / 2 + j]
16429 }
16430 partial
16431}
16432
16433/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
16434/// direction of an 8x8 luma window and the variance gap between it and its
16435/// orthogonal, reading [`cdef_gather`]'s window (row stride `bstride`, the
16436/// block's own samples starting at `CDEF_BORDER, CDEF_BORDER`).
16437fn cdef_find_dir(win: &[i16], bstride: usize, coeff_shift: i32) -> (usize, i32) {
16438 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
16439 #[cfg(target_arch = "x86_64")]
16440 let partial = if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 {
16441 // SAFETY: reached only when the CPU reports avx2; the kernel reads
16442 // the same eight rows of eight samples the scalar form does.
16443 #[allow(unsafe_code)]
16444 unsafe {
16445 cdef_simd::find_dir_partials_avx2(win, bstride, coeff_shift)
16446 }
16447 } else {
16448 cdef_find_dir_partials(win, bstride, coeff_shift)
16449 };
16450 #[cfg(not(target_arch = "x86_64"))]
16451 let partial = cdef_find_dir_partials(win, bstride, coeff_shift);
16452 let sq = |a: i32| -> i64 { i64::from(a) * i64::from(a) };
16453 let mut cost = [0i64; 8];
16454 for i in 0..8usize {
16455 cost[2] += sq(partial[2][i]);
16456 cost[6] += sq(partial[6][i]);
16457 }
16458 cost[2] *= DIV_TABLE[8];
16459 cost[6] *= DIV_TABLE[8];
16460 for i in 0..7usize {
16461 cost[0] += (sq(partial[0][i]) + sq(partial[0][14 - i])) * DIV_TABLE[i + 1];
16462 cost[4] += (sq(partial[4][i]) + sq(partial[4][14 - i])) * DIV_TABLE[i + 1];
16463 }
16464 cost[0] += sq(partial[0][7]) * DIV_TABLE[8];
16465 cost[4] += sq(partial[4][7]) * DIV_TABLE[8];
16466 for i in (1..8).step_by(2) {
16467 for j in 0..5usize {
16468 cost[i] += sq(partial[i][3 + j]);
16469 }
16470 cost[i] *= DIV_TABLE[8];
16471 for j in 0..3usize {
16472 cost[i] += (sq(partial[i][j]) + sq(partial[i][10 - j])) * DIV_TABLE[2 * j + 2];
16473 }
16474 }
16475 let mut best_cost = 0i64;
16476 let mut best_dir = 0usize;
16477 for (i, &c) in cost.iter().enumerate() {
16478 if c > best_cost {
16479 best_cost = c;
16480 best_dir = i;
16481 }
16482 }
16483 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
16484 (best_dir, var as i32)
16485}
16486
16487/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
16488/// (high variance gap) gets more deringing than a flat or non-directional
16489/// one, only ever applied to the luma primary strength.
16490fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
16491 if var == 0 {
16492 return 0;
16493 }
16494 let i = if var >> 6 != 0 {
16495 cdef_msb(var >> 6).min(12)
16496 } else {
16497 0
16498 };
16499 (strength * (4 + i) + 8) >> 4
16500}
16501
16502/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
16503/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
16504/// previously-filtered neighbour must never feed this block's own sum).
16505#[allow(clippy::too_many_arguments)]
16506#[allow(unsafe_code)]
16507fn cdef_filter_block(
16508 src: &[i16],
16509 dst: &mut PlaneBuf<'static>,
16510 ox: usize,
16511 oy: usize,
16512 bw: usize,
16513 bh: usize,
16514 pri_strength: i32,
16515 sec_strength: i32,
16516 dir: usize,
16517 pri_damping: i32,
16518 sec_damping: i32,
16519 enable_primary: bool,
16520 enable_secondary: bool,
16521 coeff_shift: i32, fctx: &crate::decode::FrameCtx,
16522) {
16523 let (stride, smax) = (dst.width, sample_max(fctx));
16524 #[cfg(target_arch = "x86_64")]
16525 if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 && (bw == 4 || bw == 8) && bh % 2 == 0
16526 {
16527 // SAFETY: reached only when the CPU reports avx2; the kernel reads
16528 // `src`'s whole (bw + 4) x (bh + 4) window and writes exactly the
16529 // `bh` runs of `bw` samples the scalar form writes.
16530 unsafe {
16531 cdef_simd::filter_block_avx2(
16532 src,
16533 dst.data.to_mut(),
16534 stride,
16535 ox,
16536 oy,
16537 bw,
16538 bh,
16539 pri_strength,
16540 sec_strength,
16541 dir,
16542 pri_damping,
16543 sec_damping,
16544 enable_primary,
16545 enable_secondary,
16546 coeff_shift,
16547 smax,
16548 )
16549 };
16550 return;
16551 }
16552 cdef_filter_block_scalar(
16553 src,
16554 dst.data.to_mut(),
16555 stride,
16556 ox,
16557 oy,
16558 bw,
16559 bh,
16560 pri_strength,
16561 sec_strength,
16562 dir,
16563 pri_damping,
16564 sec_damping,
16565 enable_primary,
16566 enable_secondary,
16567 coeff_shift,
16568 smax,
16569 );
16570}
16571
16572/// [`cdef_filter_block`]'s scalar reference: spec 7.15.3 sample by sample,
16573/// the form every non-AVX2 build decodes through and the one
16574/// `cdef_simd_kernel_matches_the_scalar_filter` checks the kernel against.
16575#[allow(clippy::too_many_arguments)]
16576fn cdef_filter_block_scalar(
16577 src: &[i16],
16578 dst: &mut [u16],
16579 stride: usize,
16580 ox: usize,
16581 oy: usize,
16582 bw: usize,
16583 bh: usize,
16584 pri_strength: i32,
16585 sec_strength: i32,
16586 dir: usize,
16587 pri_damping: i32,
16588 sec_damping: i32,
16589 enable_primary: bool,
16590 enable_secondary: bool,
16591 coeff_shift: i32,
16592 smax: i32,
16593) {
16594 let clipping_required = enable_primary && enable_secondary;
16595 // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >>
16596 // coeff_shift) & 1]` -- `pri_strength` (and its `adjust_strength`
16597 // derivative) carries the bit-depth shift, so the tap-set parity bit
16598 // must be read back above that shift, not off the raw low bit.
16599 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
16600 // Both damping shifts depend only on this block's strengths (spec 7.15.3's
16601 // `constrain`), so they are resolved here rather than per tap read.
16602 let pri_shift = cdef_constrain_shift(pri_strength.max(1), pri_damping);
16603 let sec_shift = cdef_constrain_shift(sec_strength.max(1), sec_damping);
16604 let bstride = bw + 2 * CDEF_BORDER;
16605 // `src` is [`cdef_gather`]'s window: (i, j) in block coordinates, taps
16606 // reaching +-CDEF_BORDER, so every index below is in range by construction.
16607 let at = |i: i32, j: i32| -> i32 {
16608 i32::from(src[(i + CDEF_BORDER as i32) as usize * bstride + (j + CDEF_BORDER as i32) as usize])
16609 };
16610 let (pri_dir, sec_dir0, sec_dir1) =
16611 (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]);
16612 for i in 0..bh {
16613 for j in 0..bw {
16614 let (i32i, i32j) = (i as i32, j as i32);
16615 let x = at(i32i, i32j);
16616 let mut sum = 0i32;
16617 let mut max = x;
16618 let mut min = x;
16619 for k in 0..2usize {
16620 if enable_primary {
16621 let (tr, tc) = pri_dir[k];
16622 let p0 = at(i32i + tr, i32j + tc);
16623 let p1 = at(i32i - tr, i32j - tc);
16624 sum += pri_taps[k] * cdef_constrain_shifted(p0 - x, pri_strength, pri_shift);
16625 sum += pri_taps[k] * cdef_constrain_shifted(p1 - x, pri_strength, pri_shift);
16626 if clipping_required {
16627 if p0 != CDEF_VERY_LARGE {
16628 max = max.max(p0);
16629 }
16630 if p1 != CDEF_VERY_LARGE {
16631 max = max.max(p1);
16632 }
16633 min = min.min(p0).min(p1);
16634 }
16635 }
16636 if enable_secondary {
16637 let (tr0, tc0) = sec_dir0[k];
16638 let (tr1, tc1) = sec_dir1[k];
16639 let s0 = at(i32i + tr0, i32j + tc0);
16640 let s1 = at(i32i - tr0, i32j - tc0);
16641 let s2 = at(i32i + tr1, i32j + tc1);
16642 let s3 = at(i32i - tr1, i32j - tc1);
16643 if clipping_required {
16644 for s in [s0, s1, s2, s3] {
16645 if s != CDEF_VERY_LARGE {
16646 max = max.max(s);
16647 }
16648 }
16649 min = min.min(s0).min(s1).min(s2).min(s3);
16650 }
16651 sum += CDEF_SEC_TAPS[k]
16652 * (cdef_constrain_shifted(s0 - x, sec_strength, sec_shift)
16653 + cdef_constrain_shifted(s1 - x, sec_strength, sec_shift)
16654 + cdef_constrain_shifted(s2 - x, sec_strength, sec_shift)
16655 + cdef_constrain_shifted(s3 - x, sec_strength, sec_shift));
16656 }
16657 }
16658 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
16659 if clipping_required {
16660 y = y.clamp(min, max);
16661 }
16662 dst[(oy + i) * stride + (ox + j)] = y.clamp(0, smax) as u16;
16663 }
16664 }
16665}
16666
16667/// lane-perf7 step 1: [`cdef_filter_block`]'s AVX2 kernel -- the scalar
16668/// filter was 13.1% of a 4K decode's self time. Nothing here is spec logic:
16669/// the same taps, the same `constrain`, the same `min`/`max` clamp with the
16670/// `CDEF_VERY_LARGE` sentinel excluded from the max, the same
16671/// `y + ((8 + sum - (sum < 0)) >> 4)` rounding, done 16 samples (two rows) at
16672/// a time in 16-bit lanes.
16673///
16674/// 16-bit lanes are exact for every value this filter sees: window samples
16675/// are in `[0, CDEF_VERY_LARGE]` (0x4000), so a tap difference fits in
16676/// `i16`, a `constrain` result is bounded by the threshold (at most
16677/// `15 << 4`), and the tap-weighted sum by `24 *` that.
16678#[cfg(target_arch = "x86_64")]
16679#[allow(unsafe_code)]
16680#[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract
16681mod cdef_simd {
16682 use super::{
16683 cdef_constrain_shift, CDEF_BORDER, CDEF_DIRECTIONS, CDEF_PRI_TAPS, CDEF_SEC_TAPS,
16684 CDEF_VERY_LARGE,
16685 };
16686 use std::arch::x86_64::*;
16687
16688 /// The window's rows `i` and `i + 1` at one tap offset, as one 256-bit
16689 /// register (low half = row `i`).
16690 ///
16691 /// # Safety
16692 /// Requires AVX2; `off + bstride + 8` must be inside `w`.
16693 #[target_feature(enable = "avx2")]
16694 #[inline]
16695 unsafe fn ld2(w: *const i16, off: isize, bstride: isize) -> __m256i {
16696 let lo = _mm_loadu_si128(w.offset(off).cast());
16697 let hi = _mm_loadu_si128(w.offset(off + bstride).cast());
16698 _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1)
16699 }
16700
16701 /// Spec 7.15.3's `constrain`, lane-parallel:
16702 /// `sign(diff) * clamp(threshold - (|diff| >> shift), 0, |diff|)`.
16703 /// `_mm256_sign_epi16` reproduces `signum` exactly, zero included (the
16704 /// clamped magnitude is already 0 where `diff` is).
16705 ///
16706 /// # Safety
16707 /// Requires AVX2.
16708 #[target_feature(enable = "avx2")]
16709 #[inline]
16710 unsafe fn constrain(p: __m256i, x: __m256i, thr: __m256i, shift: __m128i) -> __m256i {
16711 let diff = _mm256_sub_epi16(p, x);
16712 let a = _mm256_abs_epi16(diff);
16713 let t = _mm256_sub_epi16(thr, _mm256_sra_epi16(a, shift));
16714 let t = _mm256_min_epi16(_mm256_max_epi16(t, _mm256_setzero_si256()), a);
16715 _mm256_sign_epi16(t, diff)
16716 }
16717
16718 /// [`super::cdef_find_dir_partials`] in AVX2 (libaom
16719 /// `cdef_find_dir_avx2`'s shape): eight i32 lanes per row instead of the
16720 /// four the auto-vectorised scalar form gets without the feature.
16721 ///
16722 /// # Safety
16723 /// Requires AVX2. `win` must hold [`super::cdef_gather`]'s 8x8 window
16724 /// grown by `CDEF_BORDER` at row stride `bstride`.
16725 #[target_feature(enable = "avx2")]
16726 pub unsafe fn find_dir_partials_avx2(
16727 win: &[i16],
16728 bstride: usize,
16729 coeff_shift: i32,
16730 ) -> [[i32; 16]; 8] {
16731 #[target_feature(enable = "avx2")]
16732 unsafe fn add8(dst: &mut [i32; 16], off: usize, v: __m256i) {
16733 let p = dst.as_mut_ptr().add(off) as *mut __m256i;
16734 _mm256_storeu_si256(p, _mm256_add_epi32(_mm256_loadu_si256(p), v));
16735 }
16736 #[target_feature(enable = "avx2")]
16737 unsafe fn add4(dst: &mut [i32; 16], off: usize, v: __m128i) {
16738 let p = dst.as_mut_ptr().add(off) as *mut __m128i;
16739 _mm_storeu_si128(p, _mm_add_epi32(_mm_loadu_si128(p), v));
16740 }
16741 let mut partial = [[0i32; 16]; 8];
16742 let shift = _mm_cvtsi32_si128(coeff_shift);
16743 let c128 = _mm256_set1_epi32(128);
16744 let revidx = _mm256_setr_epi32(7, 6, 5, 4, 3, 2, 1, 0);
16745 let mut p6 = _mm256_setzero_si256();
16746 for i in 0..8usize {
16747 let base = (i + CDEF_BORDER) * bstride + CDEF_BORDER;
16748 let raw = _mm_loadu_si128(win.as_ptr().add(base) as *const __m128i);
16749 let row = _mm256_sub_epi32(_mm256_sra_epi32(_mm256_cvtepi16_epi32(raw), shift), c128);
16750 let rev = _mm256_permutevar8x32_epi32(row, revidx);
16751 // `hadd(row, row)` is [p0, p1, p0, p1 | p2, p3, p2, p3], so the
16752 // four pairwise sums are the two lanes' low halves joined.
16753 let h = _mm256_hadd_epi32(row, row);
16754 let pair =
16755 _mm_unpacklo_epi64(_mm256_castsi256_si128(h), _mm256_extracti128_si256(h, 1));
16756 let rpair = _mm_shuffle_epi32(pair, 0b00_01_10_11);
16757 let hs = _mm_hadd_epi32(pair, pair);
16758 let total = _mm_cvtsi128_si32(_mm_hadd_epi32(hs, hs));
16759 add8(&mut partial[0], i, row);
16760 add4(&mut partial[1], i, pair);
16761 partial[2][i] = total;
16762 add4(&mut partial[3], i, rpair);
16763 add8(&mut partial[4], i, rev);
16764 add8(&mut partial[5], 3 - i / 2, row);
16765 p6 = _mm256_add_epi32(p6, row);
16766 add8(&mut partial[7], i / 2, row);
16767 }
16768 _mm256_storeu_si256(partial[6].as_mut_ptr() as *mut __m256i, p6);
16769 partial
16770 }
16771
16772 /// [`super::cdef_filter_block_scalar`]'s arithmetic, two rows per
16773 /// iteration. `bw` is 8 (luma) or 4 (4:2:0 chroma) and `bh` matches; for
16774 /// `bw == 4` the upper four lanes of each half are window samples read
16775 /// past the row (never past the buffer -- `w` is padded to 256 entries),
16776 /// computed and then dropped by the 64-bit store.
16777 ///
16778 /// # Safety
16779 /// Requires AVX2. `src` must be [`super::cdef_gather`]'s 256-entry window
16780 /// buffer (the tap loads read up to 152 entries past its start, i.e. past
16781 /// the `(bw + 4) x (bh + 4)` samples themselves) and `dst` the `bh` rows
16782 /// of `bw` samples at `(ox, oy)`.
16783 #[target_feature(enable = "avx2")]
16784 #[allow(clippy::too_many_arguments)]
16785 pub unsafe fn filter_block_avx2(
16786 src: &[i16],
16787 dst: &mut [u16],
16788 stride: usize,
16789 ox: usize,
16790 oy: usize,
16791 bw: usize,
16792 bh: usize,
16793 pri_strength: i32,
16794 sec_strength: i32,
16795 dir: usize,
16796 pri_damping: i32,
16797 sec_damping: i32,
16798 enable_primary: bool,
16799 enable_secondary: bool,
16800 coeff_shift: i32,
16801 smax: i32,
16802 ) {
16803 let bstride = bw + 2 * CDEF_BORDER;
16804 // The caller's window is already `i16` and 256 entries long, so the
16805 // kernel taps it in place: the largest two-row load is
16806 // (bh + 3) * bstride + 8 <= 152 for the 8x8 luma block, 72 for the
16807 // 4x4 chroma one, both inside the buffer's zeroed tail.
16808 let w = src;
16809 let clipping_required = enable_primary && enable_secondary;
16810 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
16811 let pri_shift = _mm_cvtsi32_si128(cdef_constrain_shift(pri_strength.max(1), pri_damping));
16812 let sec_shift = _mm_cvtsi32_si128(cdef_constrain_shift(sec_strength.max(1), sec_damping));
16813 let pri_thr = _mm256_set1_epi16(pri_strength as i16);
16814 let sec_thr = _mm256_set1_epi16(sec_strength as i16);
16815 let very_large = _mm256_set1_epi16(CDEF_VERY_LARGE as i16);
16816 let zero = _mm256_setzero_si256();
16817 let eight = _mm256_set1_epi16(8);
16818 let smaxv = _mm256_set1_epi16(smax as i16);
16819 let (pri_dir, sec_dir0, sec_dir1) =
16820 (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]);
16821 let wp = w.as_ptr();
16822 let bs = bstride as isize;
16823 let dp = dst.as_mut_ptr();
16824 let mut i = 0usize;
16825 while i < bh {
16826 let base = (i + CDEF_BORDER) as isize * bs + CDEF_BORDER as isize;
16827 let x = ld2(wp, base, bs);
16828 let mut sum = zero;
16829 let mut max = x;
16830 let mut min = x;
16831 for k in 0..2usize {
16832 if enable_primary {
16833 let (tr, tc) = pri_dir[k];
16834 let off = tr as isize * bs + tc as isize;
16835 let p0 = ld2(wp, base + off, bs);
16836 let p1 = ld2(wp, base - off, bs);
16837 let tap = _mm256_set1_epi16(pri_taps[k] as i16);
16838 sum = _mm256_add_epi16(
16839 sum,
16840 _mm256_mullo_epi16(tap, constrain(p0, x, pri_thr, pri_shift)),
16841 );
16842 sum = _mm256_add_epi16(
16843 sum,
16844 _mm256_mullo_epi16(tap, constrain(p1, x, pri_thr, pri_shift)),
16845 );
16846 if clipping_required {
16847 // The sentinel is excluded from the max exactly as the
16848 // scalar `if p != CDEF_VERY_LARGE` does: masking it to
16849 // 0 cannot win a max whose seed `x` is non-negative.
16850 max = _mm256_max_epi16(
16851 max,
16852 _mm256_andnot_si256(_mm256_cmpeq_epi16(p0, very_large), p0),
16853 );
16854 max = _mm256_max_epi16(
16855 max,
16856 _mm256_andnot_si256(_mm256_cmpeq_epi16(p1, very_large), p1),
16857 );
16858 min = _mm256_min_epi16(min, _mm256_min_epi16(p0, p1));
16859 }
16860 }
16861 if enable_secondary {
16862 let (tr0, tc0) = sec_dir0[k];
16863 let (tr1, tc1) = sec_dir1[k];
16864 let off0 = tr0 as isize * bs + tc0 as isize;
16865 let off1 = tr1 as isize * bs + tc1 as isize;
16866 let s0 = ld2(wp, base + off0, bs);
16867 let s1 = ld2(wp, base - off0, bs);
16868 let s2 = ld2(wp, base + off1, bs);
16869 let s3 = ld2(wp, base - off1, bs);
16870 if clipping_required {
16871 for s in [s0, s1, s2, s3] {
16872 max = _mm256_max_epi16(
16873 max,
16874 _mm256_andnot_si256(_mm256_cmpeq_epi16(s, very_large), s),
16875 );
16876 }
16877 min = _mm256_min_epi16(
16878 min,
16879 _mm256_min_epi16(
16880 _mm256_min_epi16(s0, s1),
16881 _mm256_min_epi16(s2, s3),
16882 ),
16883 );
16884 }
16885 let c = _mm256_add_epi16(
16886 _mm256_add_epi16(
16887 constrain(s0, x, sec_thr, sec_shift),
16888 constrain(s1, x, sec_thr, sec_shift),
16889 ),
16890 _mm256_add_epi16(
16891 constrain(s2, x, sec_thr, sec_shift),
16892 constrain(s3, x, sec_thr, sec_shift),
16893 ),
16894 );
16895 sum = _mm256_add_epi16(
16896 sum,
16897 _mm256_mullo_epi16(_mm256_set1_epi16(CDEF_SEC_TAPS[k] as i16), c),
16898 );
16899 }
16900 }
16901 // `-1` where `sum < 0`, i.e. the scalar `- i32::from(sum < 0)`.
16902 let neg = _mm256_cmpgt_epi16(zero, sum);
16903 let mut y = _mm256_add_epi16(
16904 x,
16905 _mm256_srai_epi16(_mm256_add_epi16(_mm256_add_epi16(eight, sum), neg), 4),
16906 );
16907 if clipping_required {
16908 y = _mm256_min_epi16(_mm256_max_epi16(y, min), max);
16909 }
16910 y = _mm256_min_epi16(_mm256_max_epi16(y, zero), smaxv);
16911 let (lo, hi) = (_mm256_castsi256_si128(y), _mm256_extracti128_si256(y, 1));
16912 let o0 = ((oy + i) * stride + ox) as isize;
16913 let o1 = o0 + stride as isize;
16914 if bw == 8 {
16915 _mm_storeu_si128(dp.offset(o0).cast(), lo);
16916 _mm_storeu_si128(dp.offset(o1).cast(), hi);
16917 } else {
16918 _mm_storel_epi64(dp.offset(o0).cast(), lo);
16919 _mm_storel_epi64(dp.offset(o1).cast(), hi);
16920 }
16921 i += 2;
16922 }
16923 }
16924}
16925
16926/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
16927/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
16928/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
16929/// every block's level comes from [`LoopFilterParams::level`] plus the
16930/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
16931/// `get_filter_level`, precomputed per-block here rather than cached in a
16932/// table the way libaom's `av1_loop_filter_frame_init` does).
16933///
16934/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
16935/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
16936fn apply_deblock(
16937 y: &mut PlaneBuf<'static>,
16938 u: &mut PlaneBuf<'static>,
16939 v: &mut PlaneBuf<'static>,
16940 lf: &LoopFilterParams,
16941 n: &Neighbours,
16942 frame_width: usize,
16943 frame_height: usize, fctx: &crate::decode::FrameCtx,
16944) {
16945 // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel
16946 // mismatch between the raw reconstruction and post-filter output.
16947 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_DEBLOCK") {
16948 return;
16949 }
16950 if lf.level[0] != 0 || lf.level[1] != 0 {
16951 deblock_plane(y, 0, lf, n, frame_width, frame_height, fctx);
16952 }
16953 if lf.level[2] != 0 {
16954 deblock_plane(u, 1, lf, n, frame_width, frame_height, fctx);
16955 }
16956 if lf.level[3] != 0 {
16957 deblock_plane(v, 2, lf, n, frame_width, frame_height, fctx);
16958 }
16959}
16960
16961/// [`apply_deblock`] for ONE pass over ONE band of luma rows
16962/// (`y_lo..y_hi`), the form [`pipe_run`] calls it in. Running the three
16963/// planes' vertical passes and then their three horizontal ones is the same
16964/// output as `apply_deblock`'s plane-at-a-time order: the planes are
16965/// separate buffers and neither pass reads another plane.
16966#[allow(clippy::too_many_arguments)]
16967fn deblock_span(
16968 y: &mut PlaneBuf<'static>,
16969 u: &mut PlaneBuf<'static>,
16970 v: &mut PlaneBuf<'static>,
16971 lf: &LoopFilterParams,
16972 n: &Neighbours,
16973 frame_width: usize,
16974 frame_height: usize,
16975 y_lo: usize,
16976 y_hi: usize,
16977 horz: bool,
16978 fctx: &crate::decode::FrameCtx,
16979) {
16980 if lf.level[0] != 0 || lf.level[1] != 0 {
16981 deblock_plane_span(y, 0, lf, n, frame_width, frame_height, y_lo, y_hi, horz, fctx);
16982 }
16983 if lf.level[2] != 0 {
16984 deblock_plane_span(u, 1, lf, n, frame_width, frame_height, y_lo / 2, y_hi / 2, horz, fctx);
16985 }
16986 if lf.level[3] != 0 {
16987 deblock_plane_span(v, 2, lf, n, frame_width, frame_height, y_lo / 2, y_hi / 2, horz, fctx);
16988 }
16989}
16990
16991/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
16992/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
16993/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
16994/// mi unit under this decoder's assumed 4:2:0 subsampling).
16995///
16996/// lane-t900 r30b: the chroma arm ORs in the subsampling, exactly as
16997/// `set_lpf_parameters` does (`av1_loopfilter.c:245`, `mi_col = scale_horz |
16998/// ((x << scale_horz) >> MI_SIZE_LOG2)`) -- "for sub8x8 block, chroma
16999/// prediction mode is obtained from the bottom/right mi structure of the
17000/// co-located 8x8 luma block, so for chroma plane both mi_row and mi_col
17001/// should be odd". Dropping that `| 1` read the group's TOP-LEFT mi, which
17002/// is the same cell for every block 8x8 and larger and a DIFFERENT coded
17003/// block (different tx size, ref frame, skip flag and delta_lf) as soon as
17004/// the group is split into 4x4 luma blocks (class
17005/// `context-read-from-one-cell`).
17006fn plane_to_mi(chroma: bool, coord: usize) -> usize {
17007 if chroma { (coord / 2) | 1 } else { coord / 4 }
17008}
17009
17010/// This plane's own transform width in pixels at the covering block, spec
17011/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
17012/// width directly; chroma halves it (this decoder's UV transform is always
17013/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
17014/// under 4:2:0 and a block that never splits its own transform).
17015fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
17016 let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid };
17017 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
17018}
17019
17020/// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
17021/// edges step and gate by transform height, which differs from width only
17022/// on rect partition strips.
17023fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
17024 let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid };
17025 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
17026}
17027
17028/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
17029/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
17030/// present only when its neighbour exists inside the true frame -- whether
17031/// the block immediately above (at this block's own leftmost mi column) or
17032/// to the left (at its own topmost mi row) coded a transform at least as wide
17033/// as `own_side`.
17034fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
17035 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side;
17036 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side;
17037 usize::from(above) + usize::from(left)
17038}
17039
17040/// `get_tx_size_context` as libaom actually writes it (`pred_common.h:342`),
17041/// for a block inside an INTER frame: the two `TXFM_CONTEXT` arrays
17042/// ([`Neighbours::above_txfm`]/[`Neighbours::left_txfm`], which only the
17043/// inter path maintains), except that an *inter* neighbour contributes its
17044/// own BLOCK size rather than its transform size -- the two differ the moment
17045/// a neighbour's var-tx tree splits. [`tx_size_context`]'s deblock-grid
17046/// approximation coincides with this only while every neighbour codes one
17047/// whole-block transform, which is exactly what `TxMode::Select` ends.
17048/// [`tx_size_context_txfm`] with the block's own width and height (lane-intrasplit
17049/// r1): `get_tx_size_context` compares the neighbour ABOVE against
17050/// `tx_size_wide[max_txsize_rect_lookup[bsize]]` and the neighbour to the LEFT
17051/// against `tx_size_high[...]` (libaom `pred_common.h:342`), which for a 2:1
17052/// strip are two different numbers. The intra strip inside an inter frame read
17053/// this through [`tx_size_context_rect`] -- the key frame's deblock-grid
17054/// approximation -- so once `TxMode::Select` made the depth symbol exist, it was
17055/// read off the wrong CDF row whenever a neighbour's var-tx tree had split.
17056fn tx_size_context_txfm_rect(
17057 n: &Neighbours,
17058 (mi_r, mi_c): (usize, usize),
17059 own_w: usize,
17060 own_h: usize, fctx: &crate::decode::FrameCtx,
17061) -> usize {
17062 hit!(INTRA_IN_INTER_TXCTX_HITS);
17063 let has_above = mi_r > n.tile_row0_mi;
17064 let has_left = mi_c > n.tile_col0_mi;
17065 let mut above = usize::from(n.above_txfm[mi_c]) >= own_w;
17066 let mut left = usize::from(n.left_txfm[mi_r]) >= own_h;
17067 if has_above && n.above_inter[mi_c] {
17068 above = usize::from(n.above_side_mi[mi_c]) >= own_w;
17069 }
17070 if has_left && n.left_inter[mi_r] {
17071 left = usize::from(n.left_side_mi[mi_r]) >= own_h;
17072 }
17073 if crate::envflags::env_flag!("EC_TXCTX") {
17074 eprintln!(
17075 "EC_TXCTX mi={mi_r},{mi_c} own={own_w}x{own_h} ha={has_above} hl={has_left} \
17076 above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \
17077 above={above} left={left}",
17078 n.above_txfm[mi_c],
17079 n.left_txfm[mi_r],
17080 n.above_inter[mi_c],
17081 n.left_inter[mi_r],
17082 n.above_side_mi[mi_c],
17083 n.left_side_mi[mi_r],
17084 );
17085 }
17086 let ctx = match (has_above, has_left) {
17087 (true, true) => usize::from(above) + usize::from(left),
17088 (true, false) => usize::from(above),
17089 (false, true) => usize::from(left),
17090 (false, false) => 0,
17091 };
17092 // lane-midcut r3: count only the blocks the KEY FRAME deblock-grid
17093 // approximation ([`tx_size_context_rect`]) would have read off a DIFFERENT
17094 // CDF row, i.e. exactly the blocks this band read fixes -- a plain "rect
17095 // intra in an inter frame" tally is green on the buggy code too (class
17096 // gate-blind-to-feature).
17097 if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some() {
17098 let (cw, ch) = (own_w.min(64), own_h.min(64));
17099 let stale = usize::from(has_above && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= cw)
17100 + usize::from(has_left && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= ch);
17101 if ctx != stale {
17102 hit!(INTRA_RECT_IN_INTER_TXCTX_OVERRIDE_HITS);
17103 }
17104 }
17105 ctx
17106}
17107
17108/// lane-intrasplit r3: `above_inter`/`left_inter` are mi-granular bands (they
17109/// are written and read everywhere else with a raw mi index); the SUB-cell
17110/// division this pair used read a cell four blocks away, so the inter-neighbour
17111/// override above fired on the wrong neighbour -- the first divergence of the
17112/// 10-bit gate's stream was exactly this (`tx_depth` ctx 0 where libaom has 1,
17113/// at the intra block right of an inter one).
17114fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
17115 let has_above = mi_r > n.tile_row0_mi;
17116 let has_left = mi_c > n.tile_col0_mi;
17117 let mut above = usize::from(n.above_txfm[mi_c]) >= side;
17118 let mut left = usize::from(n.left_txfm[mi_r]) >= side;
17119 // lane-angledelta r1 (class [[context-read-from-one-cell]]): both
17120 // `above_inter`/`left_inter` bands are written per MI unit
17121 // (`record_inter_rect_mi`), so they are read per MI too -- the `/ (SUB /
17122 // MI)` here read the 16-px cell's FIRST mi instead, i.e. a different
17123 // block whenever the neighbour column/row is not the cell's first. A
17124 // 16x16 intra block whose left neighbour is an inter block at mi row 4
17125 // then missed libaom's "an inter neighbour contributes its BLOCK size"
17126 // override and read `tx_size_cat1` row 1 where aomdec reads row 2.
17127 if has_above && n.above_inter[mi_c] {
17128 above = usize::from(n.above_side_mi[mi_c]) >= side;
17129 }
17130 if has_left && n.left_inter[mi_r] {
17131 left = usize::from(n.left_side_mi[mi_r]) >= side;
17132 }
17133 if crate::envflags::env_flag!("EC_TXCTX") {
17134 eprintln!(
17135 "EC_TXCTX mi={mi_r},{mi_c} own={side} ha={has_above} hl={has_left} \
17136 above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \
17137 above={above} left={left}",
17138 n.above_txfm[mi_c],
17139 n.left_txfm[mi_r],
17140 n.above_inter[mi_c],
17141 n.left_inter[mi_r],
17142 n.above_side_mi[mi_c],
17143 n.left_side_mi[mi_r],
17144 );
17145 }
17146 match (has_above, has_left) {
17147 (true, true) => usize::from(above) + usize::from(left),
17148 (true, false) => usize::from(above),
17149 (false, true) => usize::from(left),
17150 (false, false) => 0,
17151 }
17152}
17153
17154/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
17155/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
17156/// the transform's own side in pixels (`side >> depth`) -- this decoder's
17157/// four square categories (8/16/32/64) each halve at most twice, matching
17158/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
17159fn read_tx_size(
17160 dec: &mut SymbolDecoder,
17161 cdfs: &mut Cdfs,
17162 n: &Neighbours,
17163 at_mi: (usize, usize),
17164 side: usize,
17165 // lane-txselect: `get_tx_size_context`'s real context, for the callers
17166 // that have one -- see [`tx_size_context_txfm`]. `None` keeps the
17167 // key-frame path's own deblock-grid approximation.
17168 ctx_override: Option<usize>,
17169) -> usize {
17170 // `max_txsize_rect_lookup[bsize]` (libaom `read_selected_tx_size` /
17171 // `get_tx_size_context`): a block wider than 64 still tops out at
17172 // TX_64X64, so BLOCK_128X128 reads BLOCK_64X64's own category (its depth
17173 // chain 64->32->16->8->4 is the same four steps) and resolves against 64,
17174 // never against its own 128 side (lane-sb128b r1).
17175 let max_tx = side.min(64);
17176 let ctx = ctx_override.unwrap_or_else(|| tx_size_context(n, at_mi, max_tx));
17177 let depth = match max_tx {
17178 8 => {
17179 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
17180 }
17181 16 => {
17182 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
17183 }
17184 32 => {
17185 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
17186 }
17187 64 => {
17188 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
17189 }
17190 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64/128"),
17191 };
17192 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
17193 let (rng, _) = dec.debug_state();
17194 let (mi_r, mi_c) = at_mi;
17195 eprintln!(
17196 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={depth} ctx={ctx} rng={rng}"
17197 );
17198 }
17199 if depth != 0 {
17200 hit!(TX_DEPTH_HITS);
17201 }
17202 max_tx >> depth
17203}
17204
17205/// `txfm_partition_context` (libaom `av1_common_int.h`): an inter block's
17206/// `txfm_split` context -- a category from the block's own largest square
17207/// transform and whether this unit already sits below it, times three, plus
17208/// the two neighbour terms (whether the transform last written above/left of
17209/// this unit is narrower/shorter than the unit itself).
17210#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
17211fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize {
17212 txfm_partition_ctx_rect(above_px, left_px, blk_max_px, tx_px, tx_px)
17213}
17214
17215/// [`txfm_partition_ctx`] for a *rectangular* transform (lane-inter4 r2):
17216/// libaom's `txfm_partition_context` compares the above context against
17217/// `tx_size_wide` and the left one against `tx_size_high`, and takes its
17218/// category from `txsize_sqr_up_map[tx_size]` -- all three collapse to one
17219/// side for a square transform, which is why the square form above is a
17220/// special case of this one.
17221pub(crate) fn txfm_partition_ctx_rect(
17222 above_px: u8,
17223 left_px: u8,
17224 blk_max_px: usize,
17225 tx_w: usize,
17226 tx_h: usize,
17227) -> usize {
17228 let above = usize::from(usize::from(above_px) < tx_w);
17229 let left = usize::from(usize::from(left_px) < tx_h);
17230 let tx_px = tx_w.max(tx_h);
17231 // `get_sqr_tx_size(max(block_size_wide, block_size_high))`, capped at the
17232 // largest transform (`TX_64X64`); `TX_4X4`..`TX_64X64` index as
17233 // `log2(px) - 2`.
17234 let max_tx = blk_max_px.min(64);
17235 let max_idx = max_tx.trailing_zeros() as usize - 2;
17236 let category = usize::from(tx_px != max_tx && max_tx > 8) + (4 - max_idx) * 2;
17237 category * 3 + above + left
17238}
17239
17240/// `txfm_partition_update` (libaom `av1_common_int.h`): once a var-tx unit
17241/// resolves, every mi cell its *parent* unit (`txb_px`) spans records the
17242/// resolved transform's own size.
17243#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
17244fn txfm_partition_update(
17245 n: &mut Neighbours,
17246 at_mi: (usize, usize),
17247 tx_px: usize,
17248 txb_px: usize,
17249) {
17250 txfm_partition_update_rect(n, at_mi, (tx_px, tx_px), (txb_px, txb_px));
17251}
17252
17253/// [`txfm_partition_update`] for a rectangular transform (lane-inter4 r2):
17254/// the left column records `tx_size_high` over the parent's own height and
17255/// the above row records `tx_size_wide` over its width.
17256/// libaom `set_txfm_ctxs` + `txfm_partition_update` (`decodeframe.c`, end of
17257/// `decode_token_recon_block`): EVERY block of an inter frame publishes its
17258/// TRANSFORM size into both `TXFM_CONTEXT` bands, intra blocks included. The
17259/// key frame writes neither (its readers use the deblock grid), so the
17260/// key-frame bodies reused by [`decode_intra_rect_in_inter`] have to do it
17261/// themselves when they run inside an inter frame. The 2:1 and 16x4 arms do it
17262/// at the call site (the transform size comes back to them); the 1:4 arms
17263/// ([`decode_block_rect4`] / [`decode_block_rect64`]) keep their size inside,
17264/// so they call this where their own depth resolves. A no-op on a key frame
17265/// ([`INTRA_IN_INTER_MODE`] unset), where those bands are not read at all.
17266///
17267/// lane-t900 r1 root cause: the HORZ_4 32x8 intra strip at mi(0,312) of an
17268/// inter frame left `left_txfm[0]` at a stale 32 where libaom's own
17269/// `set_txfm_ctxs` writes 8, so the intra 8x16 block at mi(0,320) read
17270/// `tx_size_cat1` row 1 instead of row 0 -- same depth VALUE, different CDF,
17271/// range 39156 where the reference has 54736 (class tx-grid-published-block-side
17272/// / early-return-skips-tail).
17273fn publish_txfm_bands_if_in_inter(
17274 n: &mut Neighbours,
17275 at_mi: (usize, usize),
17276 (tx_w, tx_h): (usize, usize),
17277 (bw, bh): (usize, usize), fctx: &crate::decode::FrameCtx,
17278) {
17279 if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_none() {
17280 return;
17281 }
17282 let (mi_r, mi_c) = at_mi;
17283 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
17284 for i in 0..bw / MI {
17285 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
17286 *cell = tx_w as u8;
17287 }
17288 }
17289 for i in 0..bh / MI {
17290 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
17291 *cell = tx_h as u8;
17292 }
17293 }
17294}
17295
17296fn txfm_partition_update_rect(
17297 n: &mut Neighbours,
17298 (mi_r, mi_c): (usize, usize),
17299 (tx_w, tx_h): (usize, usize),
17300 (txb_w, txb_h): (usize, usize),
17301) {
17302 if crate::envflags::env_flag!("EC_TXUPD") {
17303 eprintln!("EC_TXUPD rect mi=({},{}) tx=({tx_w},{tx_h}) txb=({txb_w},{txb_h})", mi_r, mi_c);
17304 }
17305 for i in 0..txb_h / MI {
17306 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
17307 *cell = tx_h as u8;
17308 }
17309 }
17310 for i in 0..txb_w / MI {
17311 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
17312 *cell = tx_w as u8;
17313 }
17314 }
17315}
17316
17317/// `set_txfm_ctxs` (libaom `av1_common_int.h`): the non-var-tx write of the
17318/// same contexts -- a skipped *inter* block records its own block size rather
17319/// than its transform size.
17320fn set_txfm_ctxs(
17321 n: &mut Neighbours,
17322 (mi_r, mi_c): (usize, usize),
17323 tx_px: usize,
17324 w_mi: usize,
17325 h_mi: usize,
17326 skip_inter: bool,
17327) {
17328 if crate::envflags::env_flag!("EC_TXUPD") {
17329 eprintln!("EC_TXUPD ctxs mi=({mi_r},{mi_c}) tx={tx_px} wh=({w_mi},{h_mi}) skip_inter={skip_inter}");
17330 }
17331 let bw = if skip_inter { w_mi * MI } else { tx_px };
17332 let bh = if skip_inter { h_mi * MI } else { tx_px };
17333 for i in 0..w_mi {
17334 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
17335 *cell = bw as u8;
17336 }
17337 }
17338 for i in 0..h_mi {
17339 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
17340 *cell = bh as u8;
17341 }
17342 }
17343}
17344
17345/// The value libaom initialises both transform contexts to -- NOT zero:
17346/// `av1_zero_above_context` memsets the txfm row to
17347/// `tx_size_wide[TX_SIZES_LARGEST]` and `av1_zero_left_context` does the same
17348/// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64
17349/// pixels, so an unwritten neighbour reads as the *widest* possible
17350/// transform, not the narrowest.
17351pub(crate) const TXFM_CTX_INIT: u8 = 64;
17352
17353/// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most
17354/// twice below its own largest transform.
17355const MAX_VARTX_DEPTH: usize = 2;
17356
17357/// libaom `sub_tx_size_map[TX_SIZES_ALL]` (`common_data.c`): the transform
17358/// one `txfm_split` step below `tx_size`. RECTANGULAR for the 1:4 shapes
17359/// (`[TX_64X16] == TX_32X16`, `[TX_16X64] == TX_16X32`) and for the 4:1
17360/// small ones, square everywhere else.
17361fn sub_tx_size_map(tx_w: usize, tx_h: usize) -> (usize, usize) {
17362 match (tx_w, tx_h) {
17363 (4, 4) => (4, 4),
17364 (8, 8) => (4, 4),
17365 (16, 16) => (8, 8),
17366 (32, 32) => (16, 16),
17367 (64, 64) => (32, 32),
17368 (4, 8) | (8, 4) => (4, 4),
17369 (8, 16) | (16, 8) => (8, 8),
17370 (16, 32) | (32, 16) => (16, 16),
17371 (32, 64) | (64, 32) => (32, 32),
17372 (4, 16) => (4, 8),
17373 (16, 4) => (8, 4),
17374 (8, 32) => (8, 16),
17375 (32, 8) => (16, 8),
17376 (16, 64) => (16, 32),
17377 (64, 16) => (32, 16),
17378 _ => unreachable!("not a TX_SIZES_ALL shape: {tx_w}x{tx_h}"),
17379 }
17380}
17381
17382#[test]
17383fn sub_tx_size_map_matches_libaom() {
17384 // libaom `common_data.c` `sub_tx_size_map`, in TX_SIZES_ALL order.
17385 const TABLE: [((usize, usize), (usize, usize)); 19] = [
17386 ((4, 4), (4, 4)), ((8, 8), (4, 4)), ((16, 16), (8, 8)), ((32, 32), (16, 16)),
17387 ((64, 64), (32, 32)), ((4, 8), (4, 4)), ((8, 4), (4, 4)), ((8, 16), (8, 8)),
17388 ((16, 8), (8, 8)), ((16, 32), (16, 16)), ((32, 16), (16, 16)), ((32, 64), (32, 32)),
17389 ((64, 32), (32, 32)), ((4, 16), (4, 8)), ((16, 4), (8, 4)), ((8, 32), (8, 16)),
17390 ((32, 8), (16, 8)), ((16, 64), (16, 32)), ((64, 16), (32, 16)),
17391 ];
17392 for (tx, want) in TABLE {
17393 assert_eq!(sub_tx_size_map(tx.0, tx.1), want, "sub_tx_size_map({tx:?})");
17394 }
17395}
17396
17397/// The domain of var-tx leaf sizes, enumerated against the two refusals that
17398/// name a leaf "larger than 32x32" / "larger than 64x64".
17399///
17400/// [`read_var_tx_size`] emits a leaf in exactly three places, and each one is
17401/// either the unit it was entered with or a `sub_tx_size_map` step below it:
17402/// the depth cap, the `!split` return, and libaom's `sub_txs == TX_4X4` early
17403/// return. So the leaf set reachable from an entry unit is that unit plus the
17404/// chain of `sub_tx_size_map` steps under it, capped at `MAX_VARTX_DEPTH` --
17405/// which this test enumerates, and over which no leaf is ever larger than the
17406/// entry.
17407///
17408/// That closes both refusals:
17409///
17410/// * [`read_block_tx_size_rect`]'s `bw.max(bh) > 64` branch enters every unit
17411/// at TX_64X64 (`max_txsize_rect_lookup[BLOCK_128X64]`), so "larger than
17412/// 64x64" names a leaf the tree cannot produce;
17413/// * [`read_block_tx_size`] enters at `side.min(64)` with a ceiling of 32
17414/// below the 128 root. The only entry that exceeds that ceiling is 64x64,
17415/// reached only when `side == 64`, and then the block is ONE unit whose only
17416/// above-ceiling leaf is the whole 64x64 unit itself -- which is the `single`
17417/// case the refusal is guarded by.
17418#[test]
17419fn a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered() {
17420 // Every leaf `read_var_tx_size` can reach from `entry`, as (depth, w, h).
17421 fn reachable(entry: (usize, usize), depth: usize, out: &mut Vec<(usize, usize, usize)>) {
17422 out.push((depth, entry.0, entry.1));
17423 if depth == MAX_VARTX_DEPTH {
17424 return;
17425 }
17426 let sub = sub_tx_size_map(entry.0, entry.1);
17427 if sub == (4, 4) {
17428 out.push((depth + 1, 4, 4));
17429 return;
17430 }
17431 reachable(sub, depth + 1, out);
17432 }
17433
17434 for entry in [(4, 4), (8, 8), (16, 16), (32, 32), (64, 64)] {
17435 let mut leaves = Vec::new();
17436 reachable(entry, 0, &mut leaves);
17437 for (depth, w, h) in &leaves {
17438 assert!(
17439 w.max(h) <= &entry.0.max(entry.1),
17440 "a {}x{} unit reaches a {w}x{h} leaf at depth {depth}",
17441 entry.0,
17442 entry.1
17443 );
17444 }
17445 // Above-ceiling leaves of a 64x64 entry: the entry itself, at depth 0.
17446 if entry == (64, 64) {
17447 let above: Vec<&(usize, usize, usize)> =
17448 leaves.iter().filter(|(_, w, h)| w.max(h) > &32).collect();
17449 assert_eq!(above, [&(0usize, 64usize, 64usize)], "64x64 entry, leaves above 32");
17450 }
17451 }
17452
17453 // The entry size and ceiling each caller uses, over the block sides that
17454 // reach them (`read_block_tx_size`'s square path; the 128-root rect path
17455 // enters at a fixed 64).
17456 for side in [8usize, 16, 32, 64, 128] {
17457 let max_tx = side.min(64);
17458 let ceiling = if side > 64 { 64 } else { 32 };
17459 let units = (side / max_tx) * (side / max_tx);
17460 if max_tx <= ceiling {
17461 continue;
17462 }
17463 assert_eq!(
17464 (side, units),
17465 (64, 1),
17466 "a {side}px block enters var-tx at {max_tx} over a ceiling of {ceiling} in \
17467 {units} units -- an above-ceiling leaf there would NOT be the `single` case"
17468 );
17469 }
17470}
17471
17472/// `read_var_tx_size` (spec 5.11.17, libaom `decodeframe.c`
17473/// `read_tx_size_vartx`): the recursive `txfm_split` tree of one
17474/// max-transform-sized unit of an inter block, collecting the resolved leaf
17475/// transform units into `out` as `(row offset, col offset, side)` in mi units
17476/// -- exactly the order `decode_reconstruct_tx` later reads their
17477/// coefficients in. `blk_row`/`blk_col` are mi offsets inside the block;
17478/// `max_w_mi`/`max_h_mi` clip it to the true frame edge (`max_block_wide`/
17479/// `max_block_high`).
17480#[allow(clippy::too_many_arguments)]
17481fn read_var_tx_size(
17482 dec: &mut SymbolDecoder,
17483 cdfs: &mut Cdfs,
17484 n: &mut Neighbours,
17485 at_mi: (usize, usize),
17486 blk_max_px: usize,
17487 (max_w_mi, max_h_mi): (usize, usize),
17488 (tx_w, tx_h): (usize, usize),
17489 depth: usize,
17490 blk_row: usize,
17491 blk_col: usize,
17492 out: &mut Vec<(usize, usize, usize, usize)>,
17493) {
17494 if blk_row >= max_h_mi || blk_col >= max_w_mi {
17495 return;
17496 }
17497 let unit = (at_mi.0 + blk_row, at_mi.1 + blk_col);
17498 if depth == MAX_VARTX_DEPTH {
17499 out.push((blk_row, blk_col, tx_w, tx_h));
17500 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
17501 return;
17502 }
17503 let ctx = txfm_partition_ctx_rect(
17504 n.above_txfm[unit.1],
17505 n.left_txfm[unit.0],
17506 blk_max_px,
17507 tx_w,
17508 tx_h,
17509 );
17510 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
17511 hit!(TXFM_SPLIT_READS);
17512 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
17513 let (rng, _) = dec.debug_state();
17514 eprintln!(
17515 "EC_ISTEP mi_row={} mi_col={} name=txfm_split val={} ctx={ctx} rng={rng}",
17516 unit.0,
17517 unit.1,
17518 u8::from(split)
17519 );
17520 }
17521 if !split {
17522 out.push((blk_row, blk_col, tx_w, tx_h));
17523 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
17524 return;
17525 }
17526 hit!(TXFM_SPLIT_HITS);
17527 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
17528 if (sub_w, sub_h) == (4, 4) {
17529 // libaom's `sub_txs == TX_4X4` early return: every mi cell of the
17530 // unit is marked 4x4 (raster order) without recursing.
17531 for row in 0..tx_h / MI {
17532 for col in 0..tx_w / MI {
17533 if blk_row + row < max_h_mi && blk_col + col < max_w_mi {
17534 out.push((blk_row + row, blk_col + col, 4, 4));
17535 }
17536 }
17537 }
17538 txfm_partition_update_rect(n, unit, (4, 4), (tx_w, tx_h));
17539 return;
17540 }
17541 for row in (0..tx_h / MI).step_by(sub_h / MI) {
17542 for col in (0..tx_w / MI).step_by(sub_w / MI) {
17543 read_var_tx_size(
17544 dec,
17545 cdfs,
17546 n,
17547 at_mi,
17548 blk_max_px,
17549 (max_w_mi, max_h_mi),
17550 (sub_w, sub_h),
17551 depth + 1,
17552 blk_row + row,
17553 blk_col + col,
17554 out,
17555 );
17556 }
17557 }
17558}
17559
17560/// `read_block_tx_size` (libaom `decodeframe.c` `parse_decode_block`'s tx
17561/// branch): every block of a `TxMode::Select` inter frame codes its transform
17562/// size right after its own mode info -- an inter non-skip block through the
17563/// recursive var-tx tree ([`read_var_tx_size`], whose leaf list this returns),
17564/// every other block through the intra `tx_depth` symbol (a skipped inter
17565/// block codes no symbol at all) plus a `set_txfm_ctxs` write. Returns the
17566/// block's own resolved transform side and the leaf list, the latter only
17567/// when the tree resolved to more than one transform unit.
17568#[allow(clippy::too_many_arguments)]
17569fn read_block_tx_size(
17570 dec: &mut SymbolDecoder,
17571 cdfs: &mut Cdfs,
17572 n: &mut Neighbours,
17573 at_mi: (usize, usize),
17574 side: usize,
17575 (mi_cols, mi_rows): (usize, usize),
17576 is_inter: bool,
17577 skip: bool, fctx: &crate::decode::FrameCtx,
17578) -> Result<(usize, Option<Vec<(usize, usize, usize, usize)>>)> {
17579 // lane-lossless: TX_4X4 over the whole block, and NO var-tx tree -- libaom
17580 // `read_block_tx_size` (`decodeframe.c`) sends a lossless block down the
17581 // `read_tx_size` arm, which returns TX_4X4 before it reads anything.
17582 if lossless(fctx) {
17583 let mut leaves = Vec::new();
17584 for row in 0..side / MI {
17585 for col in 0..side / MI {
17586 leaves.push((row, col, 4, 4));
17587 }
17588 }
17589 return Ok((4, Some(leaves)));
17590 }
17591 if !fctx.tx_select_inter.with(std::cell::Cell::get) {
17592 // lane-sb128c r1: `max_txsize_rect_lookup[BLOCK_128X128]` is TX_64X64,
17593 // so a 128x128 inter block is FOUR luma units even with `tx_mode ==
17594 // TX_MODE_LARGEST` -- the same leaf shape the var-tx tree hands back.
17595 // lane-sb128c r3: intra too -- an INTRA 128x128 block under
17596 // `TX_MODE_LARGEST` also resolves to TX_64X64, i.e. four luma units.
17597 if side > 64 {
17598 let step = 64 / MI;
17599 let mut leaves = Vec::new();
17600 for row in (0..side / MI).step_by(step) {
17601 for col in (0..side / MI).step_by(step) {
17602 leaves.push((row, col, 64, 64));
17603 }
17604 }
17605 return Ok((64, Some(leaves)));
17606 }
17607 return Ok((side, None));
17608 }
17609 let side_mi = side / MI;
17610 if is_inter && !skip {
17611 let max_tx = side.min(64);
17612 let max_w_mi = side_mi.min(mi_cols.saturating_sub(at_mi.1));
17613 let max_h_mi = side_mi.min(mi_rows.saturating_sub(at_mi.0));
17614 let mut leaves = Vec::new();
17615 let step = max_tx / MI;
17616 for row in (0..side_mi).step_by(step) {
17617 for col in (0..side_mi).step_by(step) {
17618 read_var_tx_size(
17619 dec,
17620 cdfs,
17621 n,
17622 at_mi,
17623 side,
17624 (max_w_mi, max_h_mi),
17625 (max_tx, max_tx),
17626 0,
17627 row,
17628 col,
17629 &mut leaves,
17630 );
17631 }
17632 }
17633 let single = leaves.len() == 1 && leaves[0].2 == side && leaves[0].3 == side;
17634 // lane-sb128c r6: below the 128 root the ceiling is main's TX_32X32
17635 // ([`inter_txbset_for`] has no 64-point *inter* table set); a 128x128
17636 // block's own var-tx tree legitimately bottoms out at TX_64X64 leaves,
17637 // which the mu-chunk reader above codes as their 32x32 coded corner.
17638 let leaf_ceiling = if side > 64 { 64 } else { 32 };
17639 if !single && leaves.iter().any(|leaf| leaf.2.max(leaf.3) > leaf_ceiling) {
17640 // Only a block wider than a superblock's own 64x64 max transform
17641 // reaches here; this crate has no 64-point *inter* coefficient
17642 // table set ([`inter_txbset_for`] stops at 32).
17643 return Err(unsupported(
17644 "an inter var-tx tree with a leaf transform larger than 32x32",
17645 ));
17646 }
17647 let resolved = leaves.last().map_or(side, |l| l.2);
17648 return Ok((resolved, (!single).then_some(leaves)));
17649 }
17650 let tx = if is_inter {
17651 side.min(64)
17652 } else {
17653 read_tx_size(
17654 dec,
17655 cdfs,
17656 n,
17657 at_mi,
17658 side,
17659 // lane-sb128c r3: `get_tx_size_context` compares the neighbour txfm
17660 // contexts against `tx_size_wide[max_txsize_rect_lookup[bsize]]`,
17661 // which is 64 for BLOCK_128X128 -- never the block's own 128 side.
17662 Some(tx_size_context_txfm(n, at_mi, side.min(64))),
17663 )
17664 };
17665 set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter);
17666 if !is_inter && tx != side {
17667 // lane-intrainter r1: an intra block inside an inter frame whose
17668 // `tx_depth` split its luma transform codes exactly the key-frame
17669 // split path's transform units (`decode_block`'s multi-TU loop),
17670 // raster order over the block. Handed back in the same leaf shape the
17671 // inter var-tx tree uses, so the caller's per-TU luma loop, the
17672 // `record_split_luma` neighbour write-back and the per-TU deblock
17673 // edges are the ones it already runs for a var-tx inter block. A
17674 // caller that has no per-TU intra loop (the 8x8 leaf) refuses on
17675 // seeing `Some` here.
17676 let step = tx / MI;
17677 let mut leaves = Vec::new();
17678 for row in (0..side_mi).step_by(step) {
17679 for col in (0..side_mi).step_by(step) {
17680 leaves.push((row, col, tx, tx));
17681 }
17682 }
17683 hit_do! {
17684 INTRA_IN_INTER_SPLIT_TX_HITS.with(|c| {
17685 let mut h = c.get();
17686 h[(side.trailing_zeros() as usize).saturating_sub(3).min(3)] += 1;
17687 c.set(h);
17688 });
17689 }
17690 return Ok((tx, Some(leaves)));
17691 }
17692 Ok((tx, None))
17693}
17694
17695/// lane-inter4 r2: the shapes whose *rectangular inter* residual this
17696/// decoder codes -- a 2:1 strip whose own max rect transform
17697/// (`max_txsize_rect_lookup[BLOCK_32X16] == TX_32X16`) has both a
17698/// coefficient table set ([`TxbSet::LumaRect32x16Inter`], 512-coefficient
17699/// `eob_pt`) and a `tx_type` alphabet here. 64x32/64x16 strips would need a
17700/// 64-point rect transform, and 16x8/8x16 needs
17701/// `default_inter_ext_tx_cdf[2][TX_8X8]` (the 12-symbol
17702/// `DTT9_IDTX_1DDCT` row at `tx_size_sqr == TX_8X8`, only reachable through a
17703/// rect transform), neither of which exists yet -- both stay refused by name.
17704pub(crate) fn rect_inter_residual_supported(w: usize, h: usize) -> bool {
17705 matches!(
17706 (w, h),
17707 // 2:1 strips whose transform is coded in full (lane-inter4).
17708 (32, 16) | (16, 32) | (16, 8) | (8, 16)
17709 // lane-inter16ab r2: the 16x16-level 1:4 strips. TX_16X4/TX_4X16
17710 // codes all 64 of its positions, and its chroma pair is an 8x4 /
17711 // 4x8 unit (`ss_size_lookup[BLOCK_16X4]` = BLOCK_8X4).
17712 | (16, 4) | (4, 16)
17713 // lane-r14 r2: strips with a 64-px axis. `av1_get_max_eob` codes
17714 // only the low 32 coefficients of a 64-length axis, so these read
17715 // exactly the truncated corner the INTRA superblock-strip path
17716 // already reads (`read_intra_mode_rect`), through
17717 // `av1_get_adjusted_tx_size`'s CDF set. Their `tx_size_sqr_up` is
17718 // `TX_64X64`, so `av1_get_ext_tx_set_type` is `DCT_ONLY` and no
17719 // `tx_type` symbol is coded at all.
17720 | (64, 32) | (32, 64) | (64, 16) | (16, 64)
17721 // lane-inter16ab r4: `sub_tx_size_map[TX_16X4] == TX_8X4`, so a
17722 // split-transform 16x4/4x16 strip has RECTANGULAR 8x4/4x8 leaves.
17723 // Only reachable as a var-tx LEAF -- an 8x4/4x8 inter BLOCK is
17724 // refused earlier ("an inter partition below 8x8").
17725 | (8, 4) | (4, 8)
17726 // lane-sb128c r7: the 128 root's HORZ/VERT halves. These are NOT
17727 // one rectangular transform -- `max_txsize_rect_lookup
17728 // [BLOCK_128X64]` is TX_64X64, so the block tiles into two square
17729 // TX_64X64 units read through the mu-chunk loop, same as the
17730 // 128x128 NONE block's four.
17731 | (128, 64) | (64, 128)
17732 // lane-rectres r1: the 32x32-level 1:4 strips -- THE shape both
17733 // 10-bit film cuts and every measured 1080p offset stop on
17734 // (measured: 6/6 probes refuse at 32x8 or 8x32, nothing else).
17735 // `max_txsize_rect_lookup[BLOCK_32X8] == TX_32X8` codes all 256
17736 // positions, and its chroma pair is a 16x4 / 4x16 unit
17737 // (`ss_size_lookup[BLOCK_32X8]` = BLOCK_16X4).
17738 | (32, 8) | (8, 32)
17739 )
17740}
17741
17742// lane-t900 r20: the `(side, write_w, write_h)` triples the inter block path
17743// actually PRESENTS, as a thread-local bitmask -- the measured domain behind
17744// the "rectangular ... has no ... here" refusals. `side` is the square context
17745// a block reads its CDFs at and `write_w`/`write_h` its true footprint;
17746// `inter_piece!` derives `reject_residual` from exactly that inequality, so
17747// these triples are what decides whether those refusals can fire at all. Bit
17748// 31 is "a triple this table does not list", which is what makes the gate a
17749// census rather than a restatement of its own table.
17750pub(crate) const INTER_BLOCK_SHAPES: [(usize, usize, usize); 18] = [
17751 (16, 16, 16),
17752 (32, 32, 32),
17753 (32, 16, 32),
17754 (32, 32, 16),
17755 (16, 8, 16),
17756 (16, 16, 8),
17757 (32, 8, 32),
17758 (64, 64, 64),
17759 (32, 32, 8),
17760 (64, 16, 64),
17761 (128, 128, 128),
17762 (64, 32, 64),
17763 (64, 64, 32),
17764 (16, 4, 16),
17765 (64, 64, 16),
17766 (16, 16, 4),
17767 (128, 128, 64),
17768 (128, 64, 128),
17769];
17770
17771/// Bit 31 of [`inter_block_shape_mask`]: a `(side, write_w, write_h)` triple
17772/// outside [`INTER_BLOCK_SHAPES`].
17773pub const INTER_BLOCK_SHAPE_UNLISTED: u32 = 1 << 31;
17774
17775thread_local! {
17776 static INTER_BLOCK_SHAPE_MASK: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
17777}
17778
17779/// Which of [`INTER_BLOCK_SHAPES`] this THREAD has decoded (thread-local, so a
17780/// gate reading it sees only the streams it decoded itself).
17781pub fn inter_block_shape_mask() -> u32 {
17782 INTER_BLOCK_SHAPE_MASK.with(std::cell::Cell::get)
17783}
17784
17785/// Records one block's shape. The table is ordered by measured frequency over
17786/// the three witnesses the census gate decodes, so the common square shapes
17787/// leave the scan on their first comparison.
17788fn census_inter_block_shape(side: usize, w: usize, h: usize) {
17789 let bit = match INTER_BLOCK_SHAPES.iter().position(|&s| s == (side, w, h)) {
17790 Some(i) => 1u32 << i,
17791 None => INTER_BLOCK_SHAPE_UNLISTED,
17792 };
17793 let seen = inter_block_shape_mask();
17794 if seen & bit == 0 {
17795 INTER_BLOCK_SHAPE_MASK.with(|c| c.set(seen | bit));
17796 }
17797}
17798
17799/// The luma coefficient/`tx_type` table set of a whole-block rectangular
17800/// INTER transform unit (lane-inter4 r3). `av1_get_ext_tx_set_type` splits
17801/// the two shapes: a 32x16/16x32 unit has `tx_size_sqr_up == TX_32X32`, so
17802/// it reads the 2-symbol `EXT_TX_SET_DCT_IDTX` set regardless of
17803/// `reduced_tx_set`; a 16x8/8x16 unit has `tx_size_sqr_up == TX_16X16` and
17804/// `tx_size_sqr == TX_8X8`, so it reads `EXT_TX_SET_DCT_IDTX` when reduced
17805/// and the 16-symbol `EXT_TX_SET_ALL16` otherwise -- both at the *8x8* CDF
17806/// row (`txsize_sqr_map`), never the 16x16 one.
17807fn rect_inter_luma_set(w: usize, h: usize, fctx: &crate::decode::FrameCtx) -> Result<TxbSet> {
17808 Ok(match (w, h) {
17809 (32, 16) | (16, 32) => TxbSet::LumaRect32x16Inter,
17810 // lane-inter16ab r4: the 8x4/4x8 split leaf of a 16x4/4x16 strip.
17811 // `av1_get_ext_tx_set_type` (blockd.h:1097) at `tx_size_sqr_up ==
17812 // TX_8X8`, `tx_size_sqr == TX_4X4`, inter: DCT_IDTX when reduced,
17813 // ALL16 otherwise -- both at the TX_4X4 row.
17814 (8, 4) | (4, 8) => {
17815 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
17816 TxbSet::LumaRect8x4Inter
17817 } else {
17818 TxbSet::LumaRect8x4InterSet1
17819 }
17820 }
17821 (16, 4) | (4, 16) => {
17822 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
17823 TxbSet::LumaRect16x4Inter
17824 } else {
17825 TxbSet::LumaRect16x4Inter1
17826 }
17827 }
17828 (16, 8) | (8, 16) => {
17829 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
17830 TxbSet::LumaRect16x8Inter
17831 } else {
17832 TxbSet::LumaRect16x8InterSet1
17833 }
17834 }
17835 // lane-r14 r2: `av1_get_adjusted_tx_size` maps TX_64X32/TX_32X64 to
17836 // TX_32X32 and TX_64X16/TX_16X64 to TX_32X16/TX_16X32, and
17837 // `get_txsize_entropy_ctx`/`txsize_log2_minus4` agree with the
17838 // adjusted size, so the existing sets are bit-exact. Neither carries a
17839 // `tx_type` table (DCT_ONLY above), so the intra/inter split is moot.
17840 // lane-rectres r1: `tx_size_sqr_up[TX_32X8] == TX_32X32`, so
17841 // `av1_get_ext_tx_set_type` is `EXT_TX_SET_DCT_IDTX` for inter with or
17842 // without `reduced_tx_set` -- one set, no `REDUCED_TX_SET_INTER`
17843 // branch, read at the `txsize_sqr_map[TX_32X8] == TX_8X8` row.
17844 (32, 8) | (8, 32) => TxbSet::LumaRect32x8Inter,
17845 (64, 32) | (32, 64) => TxbSet::Luma64,
17846 (64, 16) | (16, 64) => TxbSet::LumaRect32x16,
17847 _ => {
17848 return Err(unsupported(
17849 "a rectangular inter luma transform unit whose shape has no coefficient table set here",
17850 ));
17851 }
17852 })
17853}
17854
17855/// The chroma table set of the same block's single rectangular chroma unit
17856/// (`av1_get_max_uv_txsize`): 16x8/8x16 under a 32x16/16x32 strip, 8x4/4x8
17857/// under a 16x8/8x16 one. Neither codes a `tx_type` symbol -- both inherit
17858/// the luma unit's.
17859fn rect_inter_chroma_set(w: usize, h: usize) -> Result<TxbSet> {
17860 Ok(match (w, h) {
17861 (16, 8) | (8, 16) => TxbSet::ChromaRect16x8,
17862 (8, 4) | (4, 8) => TxbSet::ChromaRect8x4,
17863 // lane-r14 r2: chroma of a 64-axis strip -- 32x16/16x32 under a
17864 // 64x32/32x64 one, 32x8/8x32 under a 64x16/16x64 one. Neither chroma
17865 // unit has a 64-px axis, so both are coded in full; `Chroma16` is the
17866 // exact set for TX_32X8/TX_8X32 (`get_txsize_entropy_ctx` = TX_16X16,
17867 // `txsize_log2_minus4` = 4), same as the intra strip path uses.
17868 (32, 16) | (16, 32) => TxbSet::ChromaRect32x16,
17869 (32, 8) | (8, 32) => TxbSet::Chroma16,
17870 // lane-rectres r1: chroma of a 32x8/8x32 strip. `Chroma8` is the exact
17871 // set for TX_16X4/TX_4X16 (`get_txsize_entropy_ctx` = TX_8X8,
17872 // `txsize_log2_minus4` = 2, 64-coefficient `eob_pt`).
17873 (16, 4) | (4, 16) => TxbSet::Chroma8,
17874 _ => {
17875 return Err(unsupported(
17876 "a rectangular inter chroma transform unit whose shape has no coefficient table set here",
17877 ));
17878 }
17879 })
17880}
17881
17882/// libaom `size_group_lookup[bsize]` for the block shapes this decoder's
17883/// inter path reaches, from the block's TRUE footprint rather than the
17884/// square `side` corner-cut: 8x8/8x16/16x8 -> 1, 16x16/16x32/32x16 -> 2,
17885/// everything 32 and above -> 3.
17886fn size_group_wh(w: usize, h: usize) -> usize {
17887 // lane-inter4 r4: `size_group_lookup[BLOCK_SIZES_ALL]` (libaom
17888 // `common_data.h:60`) is 0 for every block with a 4-px side
17889 // (4x4/4x8/8x4/4x16/16x4), 1 for min side 8, 2 for 16, 3 above -- the old
17890 // `0..=8 => 1` row gave a sub-8 leaf group 1 where libaom says 0.
17891 match w.min(h) {
17892 0..=4 => 0,
17893 8 => 1,
17894 16 => 2,
17895 _ => 3,
17896 }
17897}
17898
17899#[test]
17900fn size_group_wh_matches_libaom_size_group_lookup() {
17901 // `BLOCK_SIZES_ALL` in libaom's own order, with `size_group_lookup`'s
17902 // transcribed values (common_data.h:60-62).
17903 const TABLE: [((usize, usize), usize); 22] = [
17904 ((4, 4), 0), ((4, 8), 0), ((8, 4), 0), ((8, 8), 1), ((8, 16), 1), ((16, 8), 1),
17905 ((16, 16), 2), ((16, 32), 2), ((32, 16), 2), ((32, 32), 3), ((32, 64), 3),
17906 ((64, 32), 3), ((64, 64), 3), ((64, 128), 3), ((128, 64), 3), ((128, 128), 3),
17907 ((4, 16), 0), ((16, 4), 0), ((8, 32), 1), ((32, 8), 1), ((16, 64), 2), ((64, 16), 2),
17908 ];
17909 for ((w, h), want) in TABLE {
17910 assert_eq!(size_group_wh(w, h), want, "size_group_wh({w}, {h})");
17911 }
17912}
17913
17914/// The default (2D) coefficient scan of a rectangular transform.
17915fn rect_scan(w: usize, h: usize) -> Result<&'static [u16]> {
17916 Ok(match (w, h) {
17917 (32, 16) => &SCAN_32X16,
17918 (16, 32) => &SCAN_16X32,
17919 (16, 8) => &SCAN_16X8,
17920 (8, 16) => &SCAN_8X16,
17921 (16, 4) => &SCAN_16X4,
17922 (4, 16) => &SCAN_4X16,
17923 (8, 4) => &SCAN_8X4,
17924 (4, 8) => &SCAN_4X8,
17925 (32, 8) => &SCAN_32X8,
17926 (8, 32) => &SCAN_8X32,
17927 _ => {
17928 return Err(unsupported(
17929 "a rectangular transform unit whose shape has no coefficient scan table here",
17930 ));
17931 }
17932 })
17933}
17934
17935/// lane-t900 r20, refusal D -- the three "a rectangular inter luma/chroma
17936/// transform unit whose shape has no coefficient table set here" / "a
17937/// rectangular transform unit whose shape has no coefficient scan table here"
17938/// arms, enumerated against the MEASURED domain of the inter block path
17939/// ([`INTER_BLOCK_SHAPES`], filled from three real streams by the gate
17940/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`).
17941///
17942/// What each helper is actually handed:
17943///
17944/// * [`rect_inter_luma_set`] -- the block's own footprint (call sites at the
17945/// whole-block residual), and a var-tx LEAF shape. `sub_tx_size_map` is
17946/// square for every rect transform except TX_16X4/TX_4X16, whose leaves are
17947/// TX_8X4/TX_4X8, so the leaf domain adds exactly 8x4 and 4x8.
17948/// * [`rect_inter_chroma_set`] -- `(write_w / 2, write_h / 2)` for a 4:2:0
17949/// block, except a 16x4/4x16 strip, whose chroma is the PAIR's 8x4 / 4x8.
17950/// * [`rect_scan`] -- the `min(w, 32) x min(h, 32)` coded corner of a rect
17951/// unit, and only when that corner is not 32x32 (a square corner goes
17952/// through the square reader with `rect_shape = Some((w, h))`).
17953///
17954/// The 128-px halves take neither: `max_txsize_rect_lookup[BLOCK_128X64]` is
17955/// TX_64X64, so they tile into SQUARE 64x64 luma units through the mu-chunk
17956/// loop, which is why they are skipped below.
17957#[test]
17958fn every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan() {
17959 let fctx = &crate::decode::FrameCtx::new();
17960 let corner_scan = |w: usize, h: usize| {
17961 let (cw, ch) = (w.min(32), h.min(32));
17962 if (cw, ch) == (32, 32) {
17963 return; // the square coefficient reader, not `rect_scan`
17964 }
17965 assert!(
17966 rect_scan(cw, ch).is_ok(),
17967 "a {w}x{h} rect transform codes its {cw}x{ch} corner, which has no scan table"
17968 );
17969 };
17970 let mut checked = 0;
17971 for &(side, w, h) in &INTER_BLOCK_SHAPES {
17972 if (w, h) == (side, side) || w.max(h) > 64 {
17973 continue;
17974 }
17975 assert!(
17976 rect_inter_luma_set(w, h, fctx).is_ok(),
17977 "the inter path decodes {w}x{h} blocks but has no luma coefficient table set for one"
17978 );
17979 corner_scan(w, h);
17980 // 4:2:0 chroma: the pair's 8x4 / 4x8 for a 1:4 strip, the halved
17981 // footprint for every other shape.
17982 let (cw, ch) = match (w, h) {
17983 (16, 4) => (8, 4),
17984 (4, 16) => (4, 8),
17985 _ => (w / 2, h / 2),
17986 };
17987 assert!(
17988 rect_inter_chroma_set(cw, ch).is_ok(),
17989 "a {w}x{h} block's {cw}x{ch} chroma unit has no coefficient table set"
17990 );
17991 corner_scan(cw, ch);
17992 checked += 1;
17993 }
17994 assert_eq!(
17995 checked, 12,
17996 "the block-shape census changed: {checked} rect shapes reach the rect transform \
17997 tables, not the 12 this claim was measured over"
17998 );
17999 // `sub_tx_size_map[TX_16X4] == TX_8X4` -- the only RECTANGULAR var-tx leaf
18000 // shapes, which reach `rect_inter_luma_set` as `(tw, th)`.
18001 for (w, h) in [(8usize, 4usize), (4, 8)] {
18002 assert!(
18003 rect_inter_luma_set(w, h, fctx).is_ok(),
18004 "the {w}x{h} split leaf of a 16x4/4x16 strip has no luma coefficient table set"
18005 );
18006 corner_scan(w, h);
18007 }
18008}
18009
18010/// [`read_block_tx_size`] for a rectangular inter block (lane-inter4 r2):
18011/// spec 5.11.17 / libaom `read_tx_size_vartx` starting from the block's own
18012/// `max_txsize_rect_lookup` entry, which for a 2:1 strip IS rectangular. The
18013/// depth-0 `txfm_partition` symbol reads its context off the rect transform's
18014/// own width/height; a `0` leaves one whole-block rect transform unit
18015/// (`None`), and a `1` splits it into `sub_tx_size_map`'s two SQUARE
18016/// sub-transforms (`sub_tx_size_map[TX_32X16] == TX_16X16`), from which the
18017/// ordinary square [`read_var_tx_size`] recursion continues at depth 1 -- so
18018/// every leaf of a split rect block is square and the existing square leaf
18019/// loop reconstructs it unchanged.
18020#[allow(clippy::too_many_arguments)]
18021fn read_block_tx_size_rect(
18022 dec: &mut SymbolDecoder,
18023 cdfs: &mut Cdfs,
18024 n: &mut Neighbours,
18025 at_mi: (usize, usize),
18026 (bw, bh): (usize, usize),
18027 (mi_cols, mi_rows): (usize, usize),
18028 skip: bool, fctx: &crate::decode::FrameCtx,
18029) -> Result<Option<Vec<(usize, usize, usize, usize)>>> {
18030 if lossless(fctx) {
18031 let mut leaves = Vec::new();
18032 for row in 0..bh / MI {
18033 for col in 0..bw / MI {
18034 leaves.push((row, col, 4, 4));
18035 }
18036 }
18037 return Ok(Some(leaves));
18038 }
18039 if skip {
18040 // `set_txfm_ctxs(.., skip && is_inter)`: a skipped inter block records
18041 // its own BLOCK size -- width above, height left -- not a transform.
18042 txfm_partition_update_rect(n, at_mi, (bw, bh), (bw, bh));
18043 return Ok(None);
18044 }
18045 // `max_txsize_rect_lookup` is the block's own size, capped at 64 -- and
18046 // `rect_inter_residual_supported` has already excluded everything above 32.
18047 // lane-sb128c r7: except at the 128 root. `max_txsize_rect_lookup
18048 // [BLOCK_128X64] == TX_64X64` (libaom `common_data.h`), so a 128x64 block
18049 // is TWO square top-level transform units side by side and a 64x128 one is
18050 // two stacked -- exactly what libaom `read_block_tx_size`
18051 // (decodeframe.c:1140) codes with its `idy/idx` loop over
18052 // `tx_size_high_unit/tx_size_wide_unit[max_tx_size]`. Each unit reads its
18053 // own `txfm_partition` symbol at depth 0.
18054 if bw.max(bh) > 64 {
18055 let tx = 64usize;
18056 let (max_w_mi, max_h_mi) = (
18057 (bw / MI).min(mi_cols.saturating_sub(at_mi.1)),
18058 (bh / MI).min(mi_rows.saturating_sub(at_mi.0)),
18059 );
18060 let mut leaves = Vec::new();
18061 if !fctx.tx_select_inter.with(std::cell::Cell::get) {
18062 for row in (0..bh / MI).step_by(tx / MI) {
18063 for col in (0..bw / MI).step_by(tx / MI) {
18064 leaves.push((row, col, tx, tx));
18065 }
18066 }
18067 for &(row, col, tw, th) in &leaves {
18068 txfm_partition_update_rect(n, (at_mi.0 + row, at_mi.1 + col), (tw, th), (tw, th));
18069 }
18070 return Ok(Some(leaves));
18071 }
18072 for row in (0..bh / MI).step_by(tx / MI) {
18073 for col in (0..bw / MI).step_by(tx / MI) {
18074 read_var_tx_size(
18075 dec,
18076 cdfs,
18077 n,
18078 at_mi,
18079 bw.max(bh),
18080 (max_w_mi, max_h_mi),
18081 (tx, tx),
18082 0,
18083 row,
18084 col,
18085 &mut leaves,
18086 );
18087 }
18088 }
18089 if leaves.iter().any(|l| l.2.max(l.3) > 64) {
18090 return Err(unsupported(
18091 "an inter var-tx tree with a leaf transform larger than 64x64",
18092 ));
18093 }
18094 return Ok(Some(leaves));
18095 }
18096 let (tx_w, tx_h) = (bw, bh);
18097 if !fctx.tx_select_inter.with(std::cell::Cell::get) {
18098 // `TX_MODE_LARGEST`: no symbol at all, the whole block is one
18099 // transform, and `set_txfm_ctxs` records exactly what
18100 // `txfm_partition_update` would for that same unit.
18101 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
18102 hit!(RECT_INTER_TU_HITS);
18103 return Ok(None);
18104 }
18105 let ctx = txfm_partition_ctx_rect(
18106 n.above_txfm[at_mi.1],
18107 n.left_txfm[at_mi.0],
18108 bw.max(bh),
18109 tx_w,
18110 tx_h,
18111 );
18112 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
18113 hit!(TXFM_SPLIT_READS);
18114 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
18115 let (rng, _) = dec.debug_state();
18116 eprintln!(
18117 "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}",
18118 at_mi.0,
18119 at_mi.1,
18120 u8::from(split)
18121 );
18122 }
18123 if !split {
18124 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
18125 hit!(RECT_INTER_TU_HITS);
18126 return Ok(None);
18127 }
18128 hit!(TXFM_SPLIT_HITS);
18129 hit!(RECT_INTER_TXSPLIT_HITS);
18130 // lane-r14 r3: `sub_tx_size_map` (libaom `common_data.c`) stays
18131 // RECTANGULAR under a 1:4 strip -- `[TX_64X16] == TX_32X16`,
18132 // `[TX_16X64] == TX_16X32` -- so the recursion below is the general
18133 // rect one and its leaves carry their own width and height.
18134 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
18135 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(at_mi.1));
18136 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(at_mi.0));
18137 let mut leaves = Vec::new();
18138 for row in (0..bh / MI).step_by(sub_h / MI) {
18139 for col in (0..bw / MI).step_by(sub_w / MI) {
18140 read_var_tx_size(
18141 dec,
18142 cdfs,
18143 n,
18144 at_mi,
18145 bw.max(bh),
18146 (max_w_mi, max_h_mi),
18147 (sub_w, sub_h),
18148 1,
18149 row,
18150 col,
18151 &mut leaves,
18152 );
18153 }
18154 }
18155 Ok(Some(leaves))
18156}
18157
18158/// [`read_inter_plane`] for a rectangular transform unit (lane-inter4 r2):
18159/// the coefficients are read with the rect coefficient machinery
18160/// ([`read_coeffs_rect`], whose `TxClass` handling covers the 1D `V_*`/`H_*`
18161/// types), inverted with the rect inverse transform
18162/// ([`dequant_and_inverse_typed_wh`], which carries the 2:1 `sqrt2` scale),
18163/// and added onto the top-left `w x h` of the block's own square-strided
18164/// motion-compensated prediction buffer. Returns the *rect* coefficient grid
18165/// and the coded `tx_type`.
18166///
18167/// `txb_skip_ctx` is 0 for luma: this unit covers the whole block, i.e.
18168/// `get_txb_ctx`'s `plane_bsize == txsize_to_bsize[tx_size]` branch.
18169#[allow(clippy::too_many_arguments)]
18170fn read_inter_plane_rect(
18171 dec: &mut SymbolDecoder,
18172 cdfs: &mut Cdfs,
18173 set: TxbSet,
18174 (w, h): (usize, usize),
18175 stride: usize,
18176 plane_idx: usize,
18177 around: (bool, bool, i32),
18178 tx_mode: usize,
18179 // lane-wave1 step (i): unread -- this reader records its write
18180 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
18181 // stays in the signature so every call site still proves the plane is
18182 // exclusively held while its coefficients are parsed.
18183 _plane: &mut PlaneBuf<'static>,
18184 x: usize,
18185 y: usize,
18186 prediction: Pred<'_>,
18187 inherited_luma_tx_type: Option<TxType>,
18188 luma_skip_ctx: Option<usize>, fctx: &crate::decode::FrameCtx,
18189) -> Result<(Grid, TxType)> {
18190 let skip_ctx = if plane_idx == 0 {
18191 // `get_txb_ctx_general`: 0 only when this unit IS the whole plane
18192 // block; a var-tx leaf passes its own neighbour-table context.
18193 luma_skip_ctx.unwrap_or(0)
18194 } else {
18195 usize::from(around.0) + usize::from(around.1)
18196 };
18197 let mut coding = cdfs.txb(set, tx_mode);
18198 // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
18199 // transform type for lossless mode(qindex==0)" -- the symbol is not coded
18200 // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
18201 // plane of a lossless block (the residual then goes through the WHT, so
18202 // the type only picks the scan, which is the default one).
18203 if lossless(fctx) {
18204 coding.tx_type = None;
18205 }
18206 // `av1_get_ext_tx_set_type`'s DCT-only clamp is on `tx_size_sqr_up`, i.e.
18207 // the *longer* side of this rect transform.
18208 let default_tx_type = match inherited_luma_tx_type {
18209 Some(t) => reduce_inherited_chroma_tx_type(t, w, h, fctx),
18210 None => TxType::DctDct,
18211 };
18212 // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
18213 // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
18214 let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type };
18215 // lane-r14 r2: a 64-length axis codes only its low 32 coefficients
18216 // (`av1_get_max_eob`), so the coded unit is the `min(w,32) x min(h,32)`
18217 // corner, zero-extended into the true `w x h` grid before the inverse
18218 // transform -- exactly what the intra superblock-strip path does. A
18219 // corner that comes out square (32x32, under a 64x32/32x64 strip) reads
18220 // through the SQUARE coefficient reader with `rect_shape = Some((w, h))`,
18221 // because `av1_nz_map_ctx_offset` is indexed by the real, un-adjusted
18222 // rectangular shape (lane-sbpart r8).
18223 let (cw, ch) = (w.min(32), h.min(32));
18224 if plane_idx == 0 && w.max(h) == 64 {
18225 hit!(RECT64_INTER_TU_HITS);
18226 }
18227 if plane_idx == 0 && (w, h) == (32, 8) || plane_idx == 0 && (w, h) == (8, 32) {
18228 hit_do! {
18229 RECT32X8_INTER_TU_HITS.with(|c| {
18230 let mut v = c.get();
18231 v[usize::from(w == 8)] += 1;
18232 c.set(v);
18233 });
18234 }
18235 }
18236 let (corner, tx_type) = if (cw, ch) == (32, 32) {
18237 let scan32 = default_scan(TX32);
18238 read_coeffs(
18239 dec,
18240 &mut coding,
18241 &scan32,
18242 skip_ctx,
18243 dc_sign_ctx(around.2),
18244 default_tx_type,
18245 Some((w, h)),
18246 )?
18247 } else {
18248 read_coeffs_rect(
18249 dec,
18250 &mut coding,
18251 rect_scan(cw, ch)?,
18252 cw,
18253 ch,
18254 skip_ctx,
18255 dc_sign_ctx(around.2),
18256 default_tx_type,
18257 )?
18258 };
18259 let grid = extend_corner(corner, cw, ch, w, h);
18260 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
18261 if crate::envflags::env_flag!("EC_TRACE_TXTYPE") {
18262 eprintln!("OUR_TXTYPE plane={plane_idx} x={x} y={y} w={w} h={h} tx_type={tx_type:?} inh={inherited_luma_tx_type:?}");
18263 }
18264 // `reconstruct_mc_rect` reads both buffers at the square prediction
18265 // stride, so the dense `w x h` residual is re-laid at that stride
18266 // (`TxParams::stride`) after the inverse transform.
18267 let tx = TxParams {
18268 w, h, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta, ac_delta, tx_type,
18269 stride, lossless: lossless(fctx),
18270 };
18271 push_mc_rect_tx(plane_idx, x, y, stride, w, h, prediction, tx, &grid, fctx);
18272 Ok((grid, tx_type))
18273}
18274
18275/// The coded `cw x ch` corner of a transform zero-extended into its true
18276/// `w x h` grid (a 64-length axis codes only its low 32 coefficients). A
18277/// corner that coded nothing stays the shared zero grid -- no allocation
18278/// (lane-coefgrid).
18279fn extend_corner(corner: Grid, cw: usize, ch: usize, w: usize, h: usize) -> Grid {
18280 if (cw, ch) == (w, h) {
18281 return corner;
18282 }
18283 if let Grid::Zero(_) = corner {
18284 return Grid::Zero(w * h);
18285 }
18286 let mut full = vec![0i32; w * h];
18287 for row in 0..ch {
18288 full[row * w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
18289 }
18290 Grid::Own(full)
18291}
18292
18293/// A rect coefficient grid re-laid into the square `stride x stride` grid the
18294/// neighbour/deblock stamps downstream of the residual expect.
18295fn embed_rect_grid(grid: &[i32], w: usize, h: usize, stride: usize) -> Vec<i32> {
18296 let mut full = vec![0i32; stride * stride];
18297 for row in 0..h {
18298 full[row * stride..][..w].copy_from_slice(&grid[row * w..][..w]);
18299 }
18300 full
18301}
18302
18303/// One 8x8 inter leaf's luma residual (lane-txselect): either the whole-8x8
18304/// transform, or -- when [`read_block_tx_size`]'s var-tx tree took the single
18305/// split a `BLOCK_8X8` can take (`split`) -- the four 4x4 transform units in
18306/// raster order, each reading its own coefficient context off the units
18307/// already decoded before it. Returns the block's luma grid (all-zero in the
18308/// split case, whose reconstruction has already happened unit by unit) and
18309/// the `tx_type` chroma inherits: `av1_get_tx_type`'s colocated luma lookup,
18310/// which for a split block lands on the top-left unit.
18311#[allow(clippy::too_many_arguments)]
18312fn read_inter_luma8(
18313 dec: &mut SymbolDecoder,
18314 cdfs: &mut Cdfs,
18315 neighbours: &mut Neighbours,
18316 leaf_mi: (usize, usize),
18317 y: &mut PlaneBuf<'static>,
18318 px: usize,
18319 py: usize,
18320 pred_y: Pred<'_>,
18321 mode_for_tx: usize,
18322 base_q_idx: u8,
18323 scan8: &[u16],
18324 scan4: &[u16],
18325 reduced_tx_set: bool,
18326 split: bool, fctx: &crate::decode::FrameCtx,
18327) -> Result<(Grid, TxType)> {
18328 // lane-lossless: an 8x8 inter block is FOUR 4x4 units (libaom
18329 // `read_block_tx_size`'s lossless TX_4X4), tree or no tree.
18330 let split = split || lossless(fctx);
18331 if !split {
18332 return read_inter_plane(
18333 dec,
18334 cdfs,
18335 if reduced_tx_set {
18336 TxbSet::Luma8Inter
18337 } else {
18338 TxbSet::Luma8InterSet1
18339 },
18340 scan8,
18341 0,
18342 neighbours.around_mi(leaf_mi, 8)[0],
18343 mode_for_tx,
18344 y,
18345 px,
18346 py,
18347 8,
18348 base_q_idx,
18349 pred_y,
18350 None,
18351 None, fctx,
18352 );
18353 }
18354 let mut first = TxType::DctDct;
18355 for tu_row in 0..2 {
18356 for tu_col in 0..2 {
18357 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
18358 let tu_pred = pred_y.view(8).offset(tu_row * 4 * 8 + tu_col * 4);
18359 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
18360 let (tu_grid, tu_tx_type) = read_inter_plane(
18361 dec,
18362 cdfs,
18363 if reduced_tx_set {
18364 TxbSet::Luma4Inter
18365 } else {
18366 TxbSet::Luma4InterSet1
18367 },
18368 scan4,
18369 0,
18370 neighbours.around_mi(tu_mi, 4)[0],
18371 mode_for_tx,
18372 y,
18373 px + tu_col * 4,
18374 py + tu_row * 4,
18375 4,
18376 base_q_idx,
18377 tu_pred,
18378 None,
18379 Some(tu_skip_ctx), fctx,
18380 )?;
18381 if tu_row == 0 && tu_col == 0 {
18382 first = tu_tx_type;
18383 }
18384 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
18385 }
18386 }
18387 Ok((Grid::Zero(64), first))
18388}
18389
18390/// The [`TxbSet`] one leaf of an inter block's var-tx tree reads its
18391/// coefficient tables from -- the inter counterpart of [`txbset_for`].
18392/// `av1_get_tx_type`'s chroma tail (libaom `av1/common/blockd.h:1291-1305`):
18393/// an inter block's chroma transform inherits the *colocated luma* unit's
18394/// coded `tx_type`, then drops back to `DCT_DCT` unless that type is a member
18395/// of the extended set the CHROMA transform size selects
18396/// (`av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)][tx_type]`,
18397/// `blockd.h:1036`/`1097`). lane-golomb r7: we used to force `DCT_DCT` at
18398/// every chroma side >= 32, but `av1_get_ext_tx_set_type`'s DCT-only rung is
18399/// `tx_size_sqr_up > TX_32X32`; at exactly TX_32X32 an inter block reads
18400/// `EXT_TX_SET_DCT_IDTX`, so a 64x64 inter block whose first luma leaf coded
18401/// `IDTX` inherits IDTX on its 32x32 chroma units. `IDTX` and `DCT_DCT` are
18402/// both `TX_CLASS_2D`, so that mistake left the entropy stream perfectly in
18403/// sync and only corrupted the inverse transform (one 64x64 superblock of
18404/// high-frequency chroma noise, luma bit-exact).
18405fn reduce_inherited_chroma_tx_type(t: TxType, w: usize, h: usize, fctx: &crate::decode::FrameCtx) -> TxType {
18406 use TxType::*;
18407 let sqr_up = w.max(h);
18408 let sqr = w.min(h);
18409 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
18410 // `av1_get_ext_tx_set_type(tx_size, is_inter = 1, reduced)`.
18411 let allowed: &[TxType] = if sqr_up > 32 {
18412 // EXT_TX_SET_DCTONLY
18413 &[DctDct]
18414 } else if sqr_up == 32 || reduced {
18415 // EXT_TX_SET_DCT_IDTX
18416 &[DctDct, Idtx]
18417 } else if sqr == 16 {
18418 // EXT_TX_SET_DTT9_IDTX_1DDCT -- TX_TYPES 0..=11, i.e. everything but
18419 // the four 1D ADST/FLIPADST types.
18420 &[
18421 DctDct, AdstDct, DctAdst, AdstAdst, FlipAdstDct, DctFlipAdst, FlipAdstFlipAdst,
18422 AdstFlipAdst, FlipAdstAdst, Idtx, VDct, HDct,
18423 ]
18424 } else {
18425 // EXT_TX_SET_ALL16
18426 return t;
18427 };
18428 if allowed.contains(&t) { t } else { DctDct }
18429}
18430
18431fn inter_txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
18432 match tx_px {
18433 // lane-sb128c r1: a 128x128 inter block's own luma unit
18434 // (`max_txsize_rect_lookup[BLOCK_128X128] == TX_64X64`).
18435 // `av1_get_ext_tx_set_type` is `DCT_ONLY` at `tx_size_sqr_up ==
18436 // TX_64X64`, so no `tx_type` symbol is coded and the intra/inter sets
18437 // coincide -- exactly the set the whole-64x64 inter block already uses.
18438 64 => TxbSet::Luma64,
18439 32 => TxbSet::Luma32Inter,
18440 16 if reduced_tx_set => TxbSet::Luma16Inter,
18441 16 => TxbSet::Luma16InterSet1,
18442 8 if reduced_tx_set => TxbSet::Luma8Inter,
18443 8 => TxbSet::Luma8InterSet1,
18444 4 if reduced_tx_set => TxbSet::Luma4Inter,
18445 4 => TxbSet::Luma4InterSet1,
18446 _ => unreachable!("a var-tx leaf is never wider than a 64x64 block's 32x32 sub-transform"),
18447 }
18448}
18449
18450/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
18451/// the only four sizes a `TxMode::Select` block's coded coefficient grid
18452/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
18453fn scan_for<'a>(
18454 tx_px: usize,
18455 scan32: &'a [u16],
18456 scan16: &'a [u16],
18457 scan8: &'a [u16],
18458 scan4: &'a [u16],
18459) -> &'a [u16] {
18460 match tx_px {
18461 32 => scan32,
18462 16 => scan16,
18463 8 => scan8,
18464 4 => scan4,
18465 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
18466 }
18467}
18468
18469/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
18470/// from -- 64 is only ever the 64x64-block, depth-0, corner-scanned case
18471/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
18472/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
18473/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
18474/// regardless of the flag (`av1_get_ext_tx_set_type`'s
18475/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
18476/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
18477/// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]).
18478/// [`txbset_for`], for a block libaom's `is_inter_block` calls inter -- which
18479/// an intrabc block is (`blockd.h:373`), so its `tx_type` comes off the
18480/// inter `ext_tx` sets, never the mode-indexed intra ones.
18481fn txbset_for_inter(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
18482 match tx_px {
18483 64 => TxbSet::Luma64,
18484 32 => TxbSet::Luma32Inter,
18485 16 if reduced_tx_set => TxbSet::Luma16Inter,
18486 16 => TxbSet::Luma16InterSet1,
18487 8 if reduced_tx_set => TxbSet::Luma8Inter,
18488 8 => TxbSet::Luma8InterSet1,
18489 _ => TxbSet::Luma64,
18490 }
18491}
18492
18493fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
18494 match tx_px {
18495 64 => TxbSet::Luma64,
18496 32 => TxbSet::Luma32,
18497 16 => TxbSet::Luma16,
18498 8 if reduced_tx_set => TxbSet::Luma8,
18499 8 => TxbSet::Luma8Set1,
18500 4 if reduced_tx_set => TxbSet::Luma4,
18501 4 => TxbSet::Luma4Set1,
18502 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
18503 }
18504}
18505
18506/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
18507/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
18508fn unit_log2(px: u32) -> i32 {
18509 if px == 0 {
18510 0
18511 } else {
18512 px.trailing_zeros() as i32 - 2
18513 }
18514}
18515
18516/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
18517/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
18518/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
18519/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
18520/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
18521/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
18522/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
18523/// block anywhere aborted the whole stream's decode before comparison).
18524fn lf_level(
18525 lf: &LoopFilterParams,
18526 plane_idx: usize,
18527 dir: usize,
18528 ref_frame: i8,
18529 delta_lf: i32,
18530 segment_id: u8, fctx: &crate::decode::FrameCtx,
18531) -> i32 {
18532 let base = i32::from(if plane_idx == 0 {
18533 lf.level[dir]
18534 } else if plane_idx == 1 {
18535 lf.level[2]
18536 } else {
18537 lf.level[3]
18538 });
18539 // spec 7.14.4: the per-superblock `DeltaLF` term applies before the
18540 // ref/mode delta scaling below, and regardless of `delta_enabled`
18541 // (that flag only gates `ref_deltas`/`mode_deltas`).
18542 let base = (base + delta_lf).clamp(0, 63);
18543 // lane-seg, spec 7.14.4 / libaom `av1_loop_filter_frame_init`: this
18544 // block's segment's own `SEG_LVL_ALT_LF_*` delta applies after the
18545 // per-superblock `DeltaLF` term and before the ref/mode deltas below.
18546 // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4)
18547 // for chroma.
18548 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
18549 // lane-perf9: `segment_id` is `0` and this lookup is skipped entirely
18550 // when the frame codes no segmentation (`seg_lf_active`), which is what
18551 // spares the deblock loop two thread-local reads per 4x4 edge.
18552 let base = match seg_feature(usize::from(segment_id), feature, fctx) {
18553 Some(data) => (base + data).clamp(0, 63),
18554 None => base,
18555 };
18556 if !lf.delta_enabled {
18557 return base;
18558 }
18559 let scale = 1i32 << (base >> 5);
18560 let is_inter = ref_frame != 0;
18561 let is_globalmv = ref_frame < 0;
18562 let ref_idx = ref_frame.unsigned_abs() as usize;
18563 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
18564 if is_inter {
18565 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
18566 }
18567 lvl.clamp(0, 63)
18568}
18569
18570thread_local! {
18571 /// lane-pipefilt: [`EdgeCtx`]'s level LUT, memoised per thread. The table
18572 /// is a pure function of the frame's [`LoopFilterParams`], the plane, the
18573 /// pass and segment 0's own `SEG_LVL_ALT_LF_*` datum (the only thing
18574 /// [`lf_level`] reads out of the `FrameCtx` at `segment_id = 0`), so one
18575 /// build per plane and pass serves the whole frame. The pipeline builds
18576 /// an `EdgeCtx` per superblock-row band rather than per frame, which
18577 /// turned 20 builds a frame into ~680 -- 960 `lf_level` calls each.
18578 static LVL_CACHE: std::cell::RefCell<
18579 Vec<((usize, usize, LoopFilterParams, Option<i32>), [[u8; 15]; 64])>,
18580 > = const { std::cell::RefCell::new(Vec::new()) };
18581}
18582
18583/// `lf_level` over the whole `(base level, ref frame)` domain -- see
18584/// [`LVL_CACHE`]. `lf_level`'s own first step is
18585/// `(base0 + delta_lf).clamp(0, 63)`, so passing `b - base0` pins its base at
18586/// `b` and the rest of the function is a pure function of `(b, ref_frame)`.
18587fn lvl_table(
18588 lf: &LoopFilterParams,
18589 plane_idx: usize,
18590 dir: usize,
18591 base0: i32,
18592 fctx: &crate::decode::FrameCtx,
18593) -> [[u8; 15]; 64] {
18594 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
18595 let key = (plane_idx, dir, *lf, seg_feature(0, feature, fctx));
18596 if let Some(t) = LVL_CACHE.with(|c| {
18597 c.borrow().iter().find(|(k, _)| *k == key).map(|(_, t)| *t)
18598 }) {
18599 return t;
18600 }
18601 let mut lvl = [[0u8; 15]; 64];
18602 for (b, row) in lvl.iter_mut().enumerate() {
18603 for (r, cell) in row.iter_mut().enumerate() {
18604 *cell =
18605 lf_level(lf, plane_idx, dir, (r as i32 - 7) as i8, b as i32 - base0, 0, fctx) as u8;
18606 }
18607 }
18608 LVL_CACHE.with(|c| {
18609 let mut c = c.borrow_mut();
18610 if c.len() >= 8 {
18611 c.remove(0);
18612 }
18613 c.push((key, lvl));
18614 });
18615 lvl
18616}
18617
18618/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
18619/// no-segmentation, no-delta-LF path and to this decoder's own invariant
18620/// that a coded block's transform is always its own full size -- so a TU
18621/// edge is always also a PU edge, and the "both sides skipped, not a PU
18622/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
18623/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
18624/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
18625/// One plane pass's worth of [`edge_params`] constants (lane-deblock2): the
18626/// seven values that used to be re-passed per 4-pixel edge group -- half of
18627/// them on the stack, into an `inline(never)` body -- plus libaom's
18628/// `lfi->lfthr` idea in level form: `av1_loop_filter_frame_init` builds the
18629/// filter level for every `(base level, ref frame)` pair once per frame
18630/// instead of running `av1_get_filter_level`'s delta arithmetic per edge.
18631struct EdgeCtx<'a> {
18632 lf: &'a LoopFilterParams,
18633 n: &'a Neighbours,
18634 fctx: &'a crate::decode::FrameCtx,
18635 plane_idx: usize,
18636 dir: usize,
18637 chroma: bool,
18638 seg_lf_active: bool,
18639 /// `delta_lf_grid`'s column for this plane and direction.
18640 delta_idx: usize,
18641 /// `mode_step` (`set_lpf_parameters`): one mi for luma, `1 << ss` for
18642 /// chroma.
18643 step: usize,
18644 /// This pass's own `lf.level[..]`, the LUT's base.
18645 base0: i32,
18646 /// `lf_level` at `[base level][ref frame + 7]`, with no segment
18647 /// override -- the whole domain, since a level is `0..=63` and a ref
18648 /// frame `-7..=7` (`ref_deltas` holds `TOTAL_REFS_PER_FRAME` = 8
18649 /// entries and is indexed by the ref frame's magnitude).
18650 lvl: [[u8; 15]; 64],
18651}
18652
18653impl<'a> EdgeCtx<'a> {
18654 fn new(
18655 lf: &'a LoopFilterParams,
18656 n: &'a Neighbours,
18657 plane_idx: usize,
18658 dir: usize,
18659 chroma: bool,
18660 seg_lf_active: bool,
18661 fctx: &'a crate::decode::FrameCtx,
18662 ) -> Self {
18663 let base0 = i32::from(if plane_idx == 0 {
18664 lf.level[dir]
18665 } else if plane_idx == 1 {
18666 lf.level[2]
18667 } else {
18668 lf.level[3]
18669 });
18670 let lvl = lvl_table(lf, plane_idx, dir, base0, fctx);
18671 Self {
18672 lf,
18673 n,
18674 fctx,
18675 plane_idx,
18676 dir,
18677 chroma,
18678 seg_lf_active,
18679 delta_idx: if plane_idx == 0 { dir } else { plane_idx + 1 },
18680 step: if chroma { 2 } else { 1 },
18681 base0,
18682 lvl,
18683 }
18684 }
18685
18686 /// Spec 7.14.4's `get_filter_level`, off the table when no segment can
18687 /// override it (which is every frame that codes no segmentation).
18688 #[inline(always)]
18689 fn level(&self, ref_frame: i8, delta_lf: i32, seg: u8) -> i32 {
18690 if self.seg_lf_active {
18691 return lf_level(self.lf, self.plane_idx, self.dir, ref_frame, delta_lf, seg, self.fctx);
18692 }
18693 let b = (self.base0 + delta_lf).clamp(0, 63) as usize;
18694 debug_assert!((-7..=7).contains(&ref_frame));
18695 let r = (i32::from(ref_frame) + 7).clamp(0, 14) as usize;
18696 i32::from(self.lvl[b][r])
18697 }
18698}
18699
18700/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
18701/// no-segmentation, no-delta-LF path and to this decoder's own invariant
18702/// that a coded block's transform is always its own full size -- so a TU
18703/// edge is always also a PU edge, and the "both sides skipped, not a PU
18704/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
18705/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
18706/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
18707#[inline(always)]
18708fn edge_params(c: &EdgeCtx, x0: usize, y0: usize) -> Option<(u8, i32)> {
18709 let (mi_r, mi_c) = (plane_to_mi(c.chroma, y0), plane_to_mi(c.chroma, x0));
18710 let cur_tx = if c.dir == 0 {
18711 tx_px_at(c.n, c.chroma, mi_r, mi_c)
18712 } else {
18713 tx_h_px_at(c.n, c.chroma, mi_r, mi_c)
18714 };
18715 // lane-deblock: `cur_tx` is a power-of-two pixel size, so the alignment
18716 // test is a mask, not the hardware `divl` this used to emit (10.7% of
18717 // `edge_params`' own samples sat on that divide's result test).
18718 //
18719 // Most 4-pixel edge groups die right here (a 4-aligned coordinate that
18720 // the covering transform does not start at), so this head is inlined
18721 // into the deblock loops and only survivors pay the call and the
18722 // register-spilling prologue of the body below.
18723 if cur_tx == 0 || (if c.dir == 0 { x0 } else { y0 }) & (cur_tx as usize - 1) != 0 {
18724 return None;
18725 }
18726 edge_params_body(c, x0, y0, mi_r, mi_c, cur_tx)
18727}
18728
18729/// [`edge_params`] past its transform-alignment gate.
18730#[inline(never)]
18731fn edge_params_body(
18732 c: &EdgeCtx,
18733 x0: usize,
18734 y0: usize,
18735 mi_r: usize,
18736 mi_c: usize,
18737 cur_tx: u32,
18738) -> Option<(u8, i32)> {
18739 let n = c.n;
18740 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
18741 // The previous cell must keep the odd parity `plane_to_mi` just
18742 // established, i.e. the bottom/right mi of the PREVIOUS 8x8 luma group,
18743 // not the other half of this one.
18744 let (pv_mi_r, pv_mi_c) = if c.dir == 0 {
18745 (mi_r, mi_c - c.step)
18746 } else {
18747 (mi_r - c.step, mi_c)
18748 };
18749 let pv_tx = if c.dir == 0 {
18750 tx_px_at(n, c.chroma, pv_mi_r, pv_mi_c)
18751 } else {
18752 tx_h_px_at(n, c.chroma, pv_mi_r, pv_mi_c)
18753 };
18754 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
18755 let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][c.delta_idx]);
18756 let pv_delta_lf =
18757 i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][c.delta_idx]);
18758
18759 // spec 7.14.2 / libaom `set_lpf_parameters`: a transform edge between two
18760 // SKIPPED INTER blocks is filtered only when it is also a prediction
18761 // (coded-block) edge -- `!pv_skip || !curr_skipped || pu_edge`. The
18762 // omission of this term (on the stale invariant "a coded block's transform
18763 // is always its own full size", which var-tx broke) had us filtering an
18764 // interior 8-px lattice the reference never touches: on the pinned 192x68
18765 // inter stream frame 1 went from 7244 wrong post-deblock luma px to 0.
18766 // libaom prices `pu_edge` in the PLANE's own pixels against the plane's
18767 // block size (`!(coord & (block_size_wide[get_plane_block_size(bsize)] -
18768 // 1))`), which for chroma bottoms out at 4 px: every 4-aligned chroma
18769 // edge of a sub-8x8 group is a prediction edge, even though the group's
18770 // bottom/right mi does not start there. Comparing mi origins instead is
18771 // the same test only while the block's own origin is aligned to its
18772 // size, which a 4x4 luma block read at the `| 1` mi is not.
18773 let cur_cell = n.blk_grid[mi_r * n.skip_grid_cols_mi + mi_c];
18774 let (cur_org, cur_dim) = (cur_cell.org, cur_cell.dim);
18775 let (org_px, dim_mi) = if c.dir == 0 {
18776 (usize::from(cur_org[1]), usize::from(cur_dim[0]))
18777 } else {
18778 (usize::from(cur_org[0]), usize::from(cur_dim[1]))
18779 };
18780 let pu_edge = if c.chroma {
18781 let plane_dim = (dim_mi * MI / 2).max(4);
18782 (if c.dir == 0 { x0 } else { y0 }) % plane_dim == 0
18783 } else {
18784 plane_to_mi(false, if c.dir == 0 { x0 } else { y0 }) == org_px
18785 };
18786 if !pu_edge
18787 && cur_ref != 0
18788 && pv_ref != 0
18789 && n.skip_at(mi_r, mi_c)
18790 && n.skip_at(pv_mi_r, pv_mi_c)
18791 {
18792 return None;
18793 }
18794 let (cur_seg, pv_seg) = if c.seg_lf_active {
18795 (segment_id_at(mi_r, mi_c, c.fctx), segment_id_at(pv_mi_r, pv_mi_c, c.fctx))
18796 } else {
18797 (0, 0)
18798 };
18799 let cur_level = c.level(cur_ref, cur_delta_lf, cur_seg);
18800 let pv_level = c.level(pv_ref, pv_delta_lf, pv_seg);
18801 if cur_level == 0 && pv_level == 0 {
18802 return None;
18803 }
18804 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
18805 let len: u8 = if c.chroma {
18806 if dim == 0 { 4 } else { 6 }
18807 } else {
18808 [4, 8, 14, 14, 14][dim]
18809 };
18810 let level = if cur_level != 0 { cur_level } else { pv_level };
18811 hit!(DEBLOCK_HITS);
18812 Some((len, level))
18813}
18814
18815/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
18816fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
18817 let sharpness = i32::from(sharpness);
18818 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
18819 let mut lim = level >> shift;
18820 if sharpness > 0 {
18821 lim = lim.min(9 - sharpness);
18822 }
18823 lim = lim.max(1);
18824 (2 * (level + 2) + lim, lim, level >> 4)
18825}
18826
18827#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
18828fn sclamp(v: i32, fctx: &crate::decode::FrameCtx) -> i32 {
18829 // libaom's `signed_char_clamp_high`: the clamp range scales with
18830 // `128 << (bit_depth - 8)` alongside the centering constant below.
18831 let scale = 1i32 << (bit_depth(fctx) - 8);
18832 v.clamp(-128 * scale, 128 * scale - 1)
18833}
18834
18835fn round_pow2(v: i32, n: u32) -> i32 {
18836 (v + (1 << (n - 1))) >> n
18837}
18838
18839/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
18840/// fallback.
18841fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32, fctx: &crate::decode::FrameCtx) -> [i32; 4] {
18842 if !mask {
18843 return [p1, p0, q0, q1];
18844 }
18845 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
18846 // lane-perf6: `sclamp` re-read the thread-local bit depth on every one of
18847 // this kernel's eight clamps, and this kernel runs per deblocked sample.
18848 // Same bound, resolved once.
18849 let scale = 1i32 << (bit_depth(fctx) - 8);
18850 let sclamp = |v: i32| v.clamp(-128 * scale, 128 * scale - 1);
18851 let centre = 128i32 * scale;
18852 let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre);
18853 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
18854 let filter = sclamp(outer + 3 * (qs0 - ps0));
18855 let filter1 = sclamp(filter + 4) >> 3;
18856 let filter2 = sclamp(filter + 3) >> 3;
18857 let oq0 = sclamp(qs0 - filter1) + centre;
18858 let op0 = sclamp(ps0 + filter2) + centre;
18859 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
18860 let oq1 = sclamp(qs1 - tap) + centre;
18861 let op1 = sclamp(ps1 + tap) + centre;
18862 [op1, op0, oq0, oq1]
18863}
18864
18865/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
18866/// `filter4`'s narrow taps.
18867#[allow(clippy::too_many_arguments)]
18868fn filter6(
18869 mask: bool,
18870 thresh: i32,
18871 flat: bool,
18872 p2: i32,
18873 p1: i32,
18874 p0: i32,
18875 q0: i32,
18876 q1: i32,
18877 q2: i32, fctx: &crate::decode::FrameCtx,
18878) -> [i32; 4] {
18879 if flat && mask {
18880 [
18881 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
18882 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
18883 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
18884 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
18885 ]
18886 } else {
18887 filter4(mask, thresh, p1, p0, q0, q1, fctx)
18888 }
18889}
18890
18891/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
18892#[allow(clippy::too_many_arguments)]
18893fn filter8(
18894 mask: bool,
18895 thresh: i32,
18896 flat: bool,
18897 p3: i32,
18898 p2: i32,
18899 p1: i32,
18900 p0: i32,
18901 q0: i32,
18902 q1: i32,
18903 q2: i32,
18904 q3: i32, fctx: &crate::decode::FrameCtx,
18905) -> [i32; 6] {
18906 if flat && mask {
18907 [
18908 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
18909 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
18910 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
18911 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
18912 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
18913 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
18914 ]
18915 } else {
18916 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1, fctx);
18917 [p2, op1, op0, oq0, oq1, q2]
18918 }
18919}
18920
18921/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
18922/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
18923/// way -- they are only ever taps here, never written).
18924#[allow(clippy::too_many_arguments)]
18925fn filter14(
18926 mask: bool,
18927 thresh: i32,
18928 flat: bool,
18929 flat2: bool,
18930 p6: i32,
18931 p5: i32,
18932 p4: i32,
18933 p3: i32,
18934 p2: i32,
18935 p1: i32,
18936 p0: i32,
18937 q0: i32,
18938 q1: i32,
18939 q2: i32,
18940 q3: i32,
18941 q4: i32,
18942 q5: i32,
18943 q6: i32, fctx: &crate::decode::FrameCtx,
18944) -> [i32; 12] {
18945 if flat2 && flat && mask {
18946 [
18947 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
18948 round_pow2(
18949 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
18950 4,
18951 ),
18952 round_pow2(
18953 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
18954 4,
18955 ),
18956 round_pow2(
18957 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
18958 4,
18959 ),
18960 round_pow2(
18961 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
18962 4,
18963 ),
18964 round_pow2(
18965 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
18966 4,
18967 ),
18968 round_pow2(
18969 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
18970 4,
18971 ),
18972 round_pow2(
18973 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
18974 4,
18975 ),
18976 round_pow2(
18977 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
18978 4,
18979 ),
18980 round_pow2(
18981 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
18982 4,
18983 ),
18984 round_pow2(
18985 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
18986 4,
18987 ),
18988 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
18989 ]
18990 } else {
18991 let [op2, op1, op0, oq0, oq1, oq2] =
18992 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3, fctx);
18993 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
18994 }
18995}
18996
18997/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
18998/// the first (`q0`) sample past the edge, `outer_stride` advances to the
18999/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
19000/// the next along the edge's own filtering direction.
19001#[allow(clippy::too_many_arguments)]
19002fn filter_edge(
19003 data: &mut [u16],
19004 base: usize,
19005 outer_stride: isize,
19006 tap_stride: isize,
19007 len: u8,
19008 level: i32,
19009 sharpness: u8, fctx: &crate::decode::FrameCtx,
19010) {
19011 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
19012 // libaom `highbd_filter_mask*`/`highbd_flat_mask4`/`highbd_hev_mask`:
19013 // every 8-bit threshold (including the flat masks' fixed `1`) is
19014 // compared against a raw pixel difference on the stream's own bit-depth
19015 // scale, so each is shifted left by `bit_depth - 8` before use.
19016 let shift = bit_depth(fctx) - 8;
19017 let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift);
19018 let flat_thresh = 1i32 << shift;
19019 let smax = sample_max(fctx);
19020 for i in 0..4isize {
19021 let center = (base as isize + i * outer_stride) as usize;
19022 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
19023 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
19024 match len {
19025 4 => {
19026 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
19027 let mask = (p1 - p0).abs() <= limit
19028 && (q1 - q0).abs() <= limit
19029 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
19030 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1, fctx);
19031 data[idx(-2)] = op1.clamp(0, smax) as u16;
19032 data[idx(-1)] = op0.clamp(0, smax) as u16;
19033 data[idx(0)] = oq0.clamp(0, smax) as u16;
19034 data[idx(1)] = oq1.clamp(0, smax) as u16;
19035 }
19036 6 => {
19037 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
19038 let mask = (p2 - p1).abs() <= limit
19039 && (p1 - p0).abs() <= limit
19040 && (q1 - q0).abs() <= limit
19041 && (q2 - q1).abs() <= limit
19042 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
19043 let flat = (p1 - p0).abs() <= flat_thresh
19044 && (q1 - q0).abs() <= flat_thresh
19045 && (p2 - p0).abs() <= flat_thresh
19046 && (q2 - q0).abs() <= flat_thresh;
19047 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2, fctx);
19048 data[idx(-2)] = op1.clamp(0, smax) as u16;
19049 data[idx(-1)] = op0.clamp(0, smax) as u16;
19050 data[idx(0)] = oq0.clamp(0, smax) as u16;
19051 data[idx(1)] = oq1.clamp(0, smax) as u16;
19052 }
19053 8 => {
19054 let (p3, p2, p1, p0, q0, q1, q2, q3) =
19055 (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3));
19056 let mask = (p3 - p2).abs() <= limit
19057 && (p2 - p1).abs() <= limit
19058 && (p1 - p0).abs() <= limit
19059 && (q1 - q0).abs() <= limit
19060 && (q2 - q1).abs() <= limit
19061 && (q3 - q2).abs() <= limit
19062 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
19063 let flat = (p1 - p0).abs() <= flat_thresh
19064 && (q1 - q0).abs() <= flat_thresh
19065 && (p2 - p0).abs() <= flat_thresh
19066 && (q2 - q0).abs() <= flat_thresh
19067 && (p3 - p0).abs() <= flat_thresh
19068 && (q3 - q0).abs() <= flat_thresh;
19069 let [op2, op1, op0, oq0, oq1, oq2] =
19070 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3, fctx);
19071 data[idx(-3)] = op2.clamp(0, smax) as u16;
19072 data[idx(-2)] = op1.clamp(0, smax) as u16;
19073 data[idx(-1)] = op0.clamp(0, smax) as u16;
19074 data[idx(0)] = oq0.clamp(0, smax) as u16;
19075 data[idx(1)] = oq1.clamp(0, smax) as u16;
19076 data[idx(2)] = oq2.clamp(0, smax) as u16;
19077 }
19078 _ => {
19079 let (p6, p5, p4, p3, p2, p1, p0) =
19080 (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1));
19081 let (q0, q1, q2, q3, q4, q5, q6) =
19082 (px(0), px(1), px(2), px(3), px(4), px(5), px(6));
19083 let mask = (p3 - p2).abs() <= limit
19084 && (p2 - p1).abs() <= limit
19085 && (p1 - p0).abs() <= limit
19086 && (q1 - q0).abs() <= limit
19087 && (q2 - q1).abs() <= limit
19088 && (q3 - q2).abs() <= limit
19089 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
19090 let flat = (p1 - p0).abs() <= flat_thresh
19091 && (q1 - q0).abs() <= flat_thresh
19092 && (p2 - p0).abs() <= flat_thresh
19093 && (q2 - q0).abs() <= flat_thresh
19094 && (p3 - p0).abs() <= flat_thresh
19095 && (q3 - q0).abs() <= flat_thresh;
19096 let flat2 = (p4 - p0).abs() <= flat_thresh
19097 && (q4 - q0).abs() <= flat_thresh
19098 && (p5 - p0).abs() <= flat_thresh
19099 && (q5 - q0).abs() <= flat_thresh
19100 && (p6 - p0).abs() <= flat_thresh
19101 && (q6 - q0).abs() <= flat_thresh;
19102 let out = filter14(
19103 mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5,
19104 q6, fctx,
19105 );
19106 for (k, v) in (-6..=5isize).zip(out) {
19107 data[idx(k)] = v.clamp(0, smax) as u16;
19108 }
19109 }
19110 }
19111 }
19112}
19113
19114/// lane-perf8: [`filter_edge`]'s AVX2 kernel -- the scalar loop was 8.0% of a
19115/// 4K decode's self time, spent almost entirely on the per-tap strided
19116/// addressing (`perf annotate`'s hot lines are `leaq`/`movzwl` pairs, not the
19117/// arithmetic). Nothing here is spec logic: the same masks, the same
19118/// `filter4`/`filter6`/`filter8`/`filter14` weighted sums and the same
19119/// rounding, done for 16 edge lines at once.
19120///
19121/// 16-bit lanes are exact for every value these filters see. Samples are in
19122/// `[0, 4095]`, so a difference and the `blimit` term (`2 * |p0 - q0| +
19123/// |p1 - q1| / 2 <= 10237`) fit `i16`; `filter4` works in the centred domain
19124/// where every intermediate is clamped to `+-128 << (bit_depth - 8)`; and the
19125/// wide kernels' weights each total 8 or 16, so their sums (at most
19126/// `16 * 4095 + 8 = 65528`) fit `u16` -- hence `_mm256_srli_epi16` for their
19127/// rounding shift, which is the unsigned shift the scalar's non-negative sum
19128/// takes.
19129#[cfg(target_arch = "x86_64")]
19130#[allow(unsafe_code)]
19131#[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract
19132mod deblock_simd {
19133 use std::arch::x86_64::*;
19134
19135 /// `a <= b` lane-wise, as a full-width mask.
19136 ///
19137 /// # Safety
19138 /// Requires AVX2.
19139 #[target_feature(enable = "avx2")]
19140 #[inline]
19141 unsafe fn le(a: __m256i, b: __m256i) -> __m256i {
19142 _mm256_cmpeq_epi16(_mm256_max_epi16(a, b), b)
19143 }
19144
19145 /// `|a - b|` lane-wise.
19146 ///
19147 /// # Safety
19148 /// Requires AVX2.
19149 #[target_feature(enable = "avx2")]
19150 #[inline]
19151 unsafe fn ad(a: __m256i, b: __m256i) -> __m256i {
19152 _mm256_abs_epi16(_mm256_sub_epi16(a, b))
19153 }
19154
19155 /// `signed_char_clamp_high`, lane-wise.
19156 ///
19157 /// # Safety
19158 /// Requires AVX2.
19159 #[target_feature(enable = "avx2")]
19160 #[inline]
19161 unsafe fn sclamp(v: __m256i, lo: __m256i, hi: __m256i) -> __m256i {
19162 _mm256_min_epi16(_mm256_max_epi16(v, lo), hi)
19163 }
19164
19165 /// 16 rows of 16 `i16` transposed in place (unpack ladder, then the
19166 /// 128-bit lane swap AVX2's in-lane unpacks leave behind).
19167 ///
19168 /// # Safety
19169 /// Requires AVX2.
19170 #[target_feature(enable = "avx2")]
19171 unsafe fn transpose16(t: &mut [__m256i; 16]) {
19172 let mut a = [_mm256_setzero_si256(); 16];
19173 for k in 0..8 {
19174 a[2 * k] = _mm256_unpacklo_epi16(t[2 * k], t[2 * k + 1]);
19175 a[2 * k + 1] = _mm256_unpackhi_epi16(t[2 * k], t[2 * k + 1]);
19176 }
19177 let mut b = [_mm256_setzero_si256(); 16];
19178 for g in 0..4 {
19179 let s = 4 * g;
19180 b[s] = _mm256_unpacklo_epi32(a[s], a[s + 2]);
19181 b[s + 1] = _mm256_unpackhi_epi32(a[s], a[s + 2]);
19182 b[s + 2] = _mm256_unpacklo_epi32(a[s + 1], a[s + 3]);
19183 b[s + 3] = _mm256_unpackhi_epi32(a[s + 1], a[s + 3]);
19184 }
19185 let mut c = [_mm256_setzero_si256(); 16];
19186 for g in 0..2 {
19187 let s = 8 * g;
19188 for j in 0..4 {
19189 c[s + 2 * j] = _mm256_unpacklo_epi64(b[s + j], b[s + j + 4]);
19190 c[s + 2 * j + 1] = _mm256_unpackhi_epi64(b[s + j], b[s + j + 4]);
19191 }
19192 }
19193 for i in 0..8 {
19194 t[i] = _mm256_permute2x128_si256(c[i], c[i + 8], 0x20);
19195 t[i + 8] = _mm256_permute2x128_si256(c[i], c[i + 8], 0x31);
19196 }
19197 }
19198
19199 /// The wide kernels' tap weights, in tap order and with the spec's
19200 /// rounding divisor as the row sum: `filter6` over `p2..q2`, `filter8`
19201 /// over `p3..q3`, `filter14` over `p6..q6`.
19202 const W6: [[i16; 6]; 4] = [
19203 [3, 2, 2, 1, 0, 0],
19204 [1, 2, 2, 2, 1, 0],
19205 [0, 1, 2, 2, 2, 1],
19206 [0, 0, 1, 2, 2, 3],
19207 ];
19208 const W8: [[i16; 8]; 6] = [
19209 [3, 2, 1, 1, 1, 0, 0, 0],
19210 [2, 1, 2, 1, 1, 1, 0, 0],
19211 [1, 1, 1, 2, 1, 1, 1, 0],
19212 [0, 1, 1, 1, 2, 1, 1, 1],
19213 [0, 0, 1, 1, 1, 2, 1, 2],
19214 [0, 0, 0, 1, 1, 1, 2, 3],
19215 ];
19216 #[allow(dead_code)] // superseded by the running-sum rows; kept as the weights' statement
19217 const W14: [[i16; 14]; 12] = [
19218 [7, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
19219 [5, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
19220 [4, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0],
19221 [3, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0],
19222 [2, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0],
19223 [1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0],
19224 [0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1],
19225 [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2],
19226 [0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 3],
19227 [0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 4],
19228 [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 5],
19229 [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 7],
19230 ];
19231
19232 /// One weighted tap sum, rounded by `shift` (3 for the divide-by-8 rows,
19233 /// 4 for `filter14`'s divide-by-16 ones). The sum is non-negative and
19234 /// below `1 << 16`, so the logical shift is the arithmetic one.
19235 ///
19236 /// # Safety
19237 /// Requires AVX2.
19238 ///
19239 /// lane-deblock: the tap count, the weights and the shift are all const
19240 /// here (they were slice parameters, which left the weight `match` as a
19241 /// runtime branch and a `movzwl` per tap -- `testl`/`je`/`movzwl` were
19242 /// 34% of this kernel's samples, and the spilled tap slices another 17%).
19243 #[target_feature(enable = "avx2")]
19244 #[inline] // rust#145574: `inline(always)` is rejected on a `target_feature` fn
19245 unsafe fn wsum<const N: usize, const SHIFT: i32>(
19246 taps: &[__m256i; N],
19247 w: &[i16; N],
19248 ) -> __m256i {
19249 let mut s = _mm256_setzero_si256();
19250 for i in 0..N {
19251 match w[i] {
19252 0 => {}
19253 1 => s = _mm256_add_epi16(s, taps[i]),
19254 2 => s = _mm256_add_epi16(s, _mm256_add_epi16(taps[i], taps[i])),
19255 k => s = _mm256_add_epi16(s, _mm256_mullo_epi16(taps[i], _mm256_set1_epi16(k))),
19256 }
19257 }
19258 let s = _mm256_add_epi16(s, _mm256_set1_epi16(1 << (SHIFT - 1)));
19259 if SHIFT == 3 {
19260 _mm256_srli_epi16(s, 3)
19261 } else {
19262 _mm256_srli_epi16(s, 4)
19263 }
19264 }
19265
19266 /// [`super::filter_edge`]'s body for 16 lines held as `t[0..16]`, `q0` in
19267 /// `t[8]`; the filtered taps are written back in place. Returns `false`
19268 /// when the filter mask is empty on every one of the 16 lines -- nothing
19269 /// was written and the caller can skip the whole write-back.
19270 ///
19271 /// # Safety
19272 /// Requires AVX2.
19273 ///
19274 /// lane-deblock2: `LEN` is a const parameter, so each edge length gets
19275 /// its own kernel holding only its own taps, and every wide row is
19276 /// clamped straight into `t` instead of into a shared twelve-entry
19277 /// result array (which the register allocator spilled -- 35% of this
19278 /// kernel's samples were `vmovdqa` to the stack).
19279 #[target_feature(enable = "avx2")]
19280 #[allow(clippy::too_many_arguments)]
19281 unsafe fn filter16<const LEN: u8>(
19282 t: &mut [__m256i; 16],
19283 blimit: i32,
19284 limit: i32,
19285 hev_thr: i32,
19286 flat_thresh: i32,
19287 scale: i32,
19288 smax: i32,
19289 ) -> bool {
19290 let lim = _mm256_set1_epi16(limit as i16);
19291 let blim = _mm256_set1_epi16(blimit as i16);
19292 let hthr = _mm256_set1_epi16(hev_thr as i16);
19293 let fthr = _mm256_set1_epi16(flat_thresh as i16);
19294 let zero = _mm256_setzero_si256();
19295 let smaxv = _mm256_set1_epi16(smax as i16);
19296 macro_rules! put {
19297 ($i:expr, $v:expr) => {
19298 t[$i] = _mm256_min_epi16(_mm256_max_epi16($v, zero), smaxv);
19299 };
19300 }
19301 let (p6, p5, p4, p3, p2, p1, p0) = (t[1], t[2], t[3], t[4], t[5], t[6], t[7]);
19302 let (q0, q1, q2, q3, q4, q5, q6) = (t[8], t[9], t[10], t[11], t[12], t[13], t[14]);
19303
19304 // `highbd_filter_mask`: the neighbour steps this kernel's length
19305 // reaches, plus the shared `blimit` term.
19306 let d1 = _mm256_max_epi16(ad(p1, p0), ad(q1, q0));
19307 let mut md = d1;
19308 if LEN >= 6 {
19309 md = _mm256_max_epi16(md, _mm256_max_epi16(ad(p2, p1), ad(q2, q1)));
19310 }
19311 if LEN >= 8 {
19312 md = _mm256_max_epi16(md, _mm256_max_epi16(ad(p3, p2), ad(q3, q2)));
19313 }
19314 let bl = _mm256_add_epi16(
19315 _mm256_slli_epi16(ad(p0, q0), 1),
19316 _mm256_srli_epi16(ad(p1, q1), 1),
19317 );
19318 let mask = _mm256_and_si256(le(md, lim), le(bl, blim));
19319 // lane-deblock2: an empty mask leaves every tap at its loaded value
19320 // (the flat masks are `& mask`, so they are empty too, and the final
19321 // clamp is the identity on samples that came out of the plane), so
19322 // the whole write-back -- including the vertical edge's second
19323 // transpose -- is dead.
19324 if _mm256_testz_si256(mask, mask) != 0 {
19325 return false;
19326 }
19327 let hev = _mm256_cmpgt_epi16(d1, hthr);
19328
19329 // `filter4`, in the centred domain.
19330 let centre = _mm256_set1_epi16((128 * scale) as i16);
19331 let lo = _mm256_set1_epi16((-128 * scale) as i16);
19332 let hi = _mm256_set1_epi16((128 * scale - 1) as i16);
19333 let ps1 = _mm256_sub_epi16(p1, centre);
19334 let ps0 = _mm256_sub_epi16(p0, centre);
19335 let qs0 = _mm256_sub_epi16(q0, centre);
19336 let qs1 = _mm256_sub_epi16(q1, centre);
19337 let outer = _mm256_and_si256(hev, sclamp(_mm256_sub_epi16(ps1, qs1), lo, hi));
19338 let f = sclamp(
19339 _mm256_add_epi16(
19340 outer,
19341 _mm256_mullo_epi16(_mm256_set1_epi16(3), _mm256_sub_epi16(qs0, ps0)),
19342 ),
19343 lo,
19344 hi,
19345 );
19346 let f1 = _mm256_srai_epi16(sclamp(_mm256_add_epi16(f, _mm256_set1_epi16(4)), lo, hi), 3);
19347 let f2 = _mm256_srai_epi16(sclamp(_mm256_add_epi16(f, _mm256_set1_epi16(3)), lo, hi), 3);
19348 let tap = _mm256_andnot_si256(
19349 hev,
19350 _mm256_srai_epi16(_mm256_add_epi16(f1, _mm256_set1_epi16(1)), 1),
19351 );
19352 let n_p1 = _mm256_add_epi16(sclamp(_mm256_add_epi16(ps1, tap), lo, hi), centre);
19353 let n_p0 = _mm256_add_epi16(sclamp(_mm256_add_epi16(ps0, f2), lo, hi), centre);
19354 let n_q0 = _mm256_add_epi16(sclamp(_mm256_sub_epi16(qs0, f1), lo, hi), centre);
19355 let n_q1 = _mm256_add_epi16(sclamp(_mm256_sub_epi16(qs1, tap), lo, hi), centre);
19356 let b_p1 = _mm256_blendv_epi8(p1, n_p1, mask);
19357 let b_p0 = _mm256_blendv_epi8(p0, n_p0, mask);
19358 let b_q0 = _mm256_blendv_epi8(q0, n_q0, mask);
19359 let b_q1 = _mm256_blendv_epi8(q1, n_q1, mask);
19360 if LEN == 4 {
19361 put!(6, b_p1);
19362 put!(7, b_p0);
19363 put!(8, b_q0);
19364 put!(9, b_q1);
19365 return true;
19366 }
19367
19368 // `highbd_flat_mask4`, over the same reach as this length's mask.
19369 let mut fl = _mm256_max_epi16(
19370 _mm256_max_epi16(ad(p1, p0), ad(q1, q0)),
19371 _mm256_max_epi16(ad(p2, p0), ad(q2, q0)),
19372 );
19373 if LEN >= 8 {
19374 fl = _mm256_max_epi16(fl, _mm256_max_epi16(ad(p3, p0), ad(q3, q0)));
19375 }
19376 let flat = _mm256_and_si256(le(fl, fthr), mask);
19377 let any_flat = _mm256_testz_si256(flat, flat) == 0;
19378 if LEN == 6 {
19379 if any_flat {
19380 let taps = [p2, p1, p0, q0, q1, q2];
19381 put!(6, _mm256_blendv_epi8(b_p1, wsum::<_, 3>(&taps, &W6[0]), flat));
19382 put!(7, _mm256_blendv_epi8(b_p0, wsum::<_, 3>(&taps, &W6[1]), flat));
19383 put!(8, _mm256_blendv_epi8(b_q0, wsum::<_, 3>(&taps, &W6[2]), flat));
19384 put!(9, _mm256_blendv_epi8(b_q1, wsum::<_, 3>(&taps, &W6[3]), flat));
19385 } else {
19386 put!(6, b_p1);
19387 put!(7, b_p0);
19388 put!(8, b_q0);
19389 put!(9, b_q1);
19390 }
19391 return true;
19392 }
19393
19394 // `filter8`'s six rows over `p2..q2`, the wide kernel's base.
19395 let (o0, o1, o2, o3, o4, o5) = if any_flat {
19396 let taps = [p3, p2, p1, p0, q0, q1, q2, q3];
19397 (
19398 _mm256_blendv_epi8(p2, wsum::<_, 3>(&taps, &W8[0]), flat),
19399 _mm256_blendv_epi8(b_p1, wsum::<_, 3>(&taps, &W8[1]), flat),
19400 _mm256_blendv_epi8(b_p0, wsum::<_, 3>(&taps, &W8[2]), flat),
19401 _mm256_blendv_epi8(b_q0, wsum::<_, 3>(&taps, &W8[3]), flat),
19402 _mm256_blendv_epi8(b_q1, wsum::<_, 3>(&taps, &W8[4]), flat),
19403 _mm256_blendv_epi8(q2, wsum::<_, 3>(&taps, &W8[5]), flat),
19404 )
19405 } else {
19406 (p2, b_p1, b_p0, b_q0, b_q1, q2)
19407 };
19408 macro_rules! put8 {
19409 () => {
19410 put!(5, o0);
19411 put!(6, o1);
19412 put!(7, o2);
19413 put!(8, o3);
19414 put!(9, o4);
19415 put!(10, o5);
19416 };
19417 }
19418 if LEN == 8 {
19419 put8!();
19420 return true;
19421 }
19422
19423 let fl2 = _mm256_max_epi16(
19424 _mm256_max_epi16(
19425 _mm256_max_epi16(ad(p4, p0), ad(q4, q0)),
19426 _mm256_max_epi16(ad(p5, p0), ad(q5, q0)),
19427 ),
19428 _mm256_max_epi16(ad(p6, p0), ad(q6, q0)),
19429 );
19430 let flat2 = _mm256_and_si256(le(fl2, fthr), flat);
19431 if _mm256_testz_si256(flat2, flat2) != 0 {
19432 // No line takes the wide rows: `t[2..5]`/`t[11..14]` keep the
19433 // taps they were loaded with, exactly as the blend would.
19434 put8!();
19435 return true;
19436 }
19437 // lane-deblock: `filter14`'s twelve rows as a RUNNING sum.
19438 // Consecutive `W14` rows differ by three or four taps (row j+1 - row
19439 // j is a constant vector with two negative and two positive
19440 // entries), so each output costs one add, one sub and the rounding
19441 // shift instead of a fresh 14-tap weighted sum -- 168 tap operations
19442 // become 44. Exact: every partial sum is taken mod 2^16 by
19443 // `add/sub_epi16` and every ROW sum is a real `W14` row, at most
19444 // `16 * 4095 + 8 < 2^16`, so the unsigned rounding shift sees the
19445 // true value. `deblock_simd_kernel_matches_the_scalar_filter` pins
19446 // it against `filter_edge` at 8/10/12-bit.
19447 let mut s = _mm256_add_epi16(
19448 _mm256_add_epi16(
19449 _mm256_mullo_epi16(p6, _mm256_set1_epi16(7)),
19450 _mm256_slli_epi16(_mm256_add_epi16(p5, p4), 1),
19451 ),
19452 _mm256_add_epi16(
19453 _mm256_add_epi16(_mm256_add_epi16(p3, p2), _mm256_add_epi16(p1, p0)),
19454 q0,
19455 ),
19456 );
19457 let add2 = |a, b| _mm256_add_epi16(a, b);
19458 macro_rules! row14 {
19459 ($idx:literal, $base:expr) => {
19460 put!(
19461 $idx,
19462 _mm256_blendv_epi8(
19463 $base,
19464 _mm256_srli_epi16(_mm256_add_epi16(s, _mm256_set1_epi16(8)), 4),
19465 flat2,
19466 )
19467 );
19468 };
19469 ($idx:literal, $base:expr, $plus:expr, $minus:expr) => {
19470 s = _mm256_sub_epi16(_mm256_add_epi16(s, $plus), $minus);
19471 row14!($idx, $base);
19472 };
19473 }
19474 row14!(2, p5);
19475 row14!(3, p4, add2(p3, q1), _mm256_slli_epi16(p6, 1));
19476 row14!(4, p3, add2(p2, q2), add2(p6, p5));
19477 row14!(5, o0, add2(p1, q3), add2(p6, p4));
19478 row14!(6, o1, add2(p0, q4), add2(p6, p3));
19479 row14!(7, o2, add2(q0, q5), add2(p6, p2));
19480 row14!(8, o3, add2(q1, q6), add2(p6, p1));
19481 row14!(9, o4, add2(q2, q6), add2(p5, p0));
19482 row14!(10, o5, add2(q3, q6), add2(p4, q0));
19483 row14!(11, q3, add2(q4, q6), add2(p3, q1));
19484 row14!(12, q4, add2(q5, q6), add2(p2, q2));
19485 row14!(13, q5, _mm256_slli_epi16(q6, 1), add2(p1, q3));
19486 true
19487 }
19488
19489 /// 16 edge lines at `base`. `vertical` names the edge: a vertical edge's
19490 /// 16 lines are 16 consecutive rows and its taps are consecutive samples
19491 /// (loaded as a 16x16 tile and transposed), a horizontal edge's are 16
19492 /// consecutive columns with each tap a whole row segment.
19493 ///
19494 /// # Safety
19495 /// Requires AVX2. For a vertical edge `base % stride >= 8`, `base %
19496 /// stride + 8 <= stride` and 16 rows from `base` must be inside `data`;
19497 /// for a horizontal edge `base >= 8 * stride` and `base + 8 * stride`
19498 /// must be inside it.
19499 #[target_feature(enable = "avx2")]
19500 #[allow(clippy::too_many_arguments)]
19501 pub unsafe fn edge16(
19502 data: &mut [u16],
19503 base: usize,
19504 stride: usize,
19505 vertical: bool,
19506 len: u8,
19507 blimit: i32,
19508 limit: i32,
19509 hev_thr: i32,
19510 flat_thresh: i32,
19511 scale: i32,
19512 smax: i32,
19513 ) {
19514 let p = data.as_mut_ptr();
19515 let mut t = [_mm256_setzero_si256(); 16];
19516 // The taps this length reads, as `t` indices.
19517 let (lo, hi) = match len {
19518 4 => (6, 10),
19519 6 => (5, 11),
19520 8 => (4, 12),
19521 _ => (1, 15),
19522 };
19523 if vertical {
19524 for j in 0..16 {
19525 t[j] = _mm256_loadu_si256(p.add(base + j * stride - 8).cast());
19526 }
19527 transpose16(&mut t);
19528 } else {
19529 let top = base - 8 * stride;
19530 for i in lo..hi {
19531 t[i] = _mm256_loadu_si256(p.add(top + i * stride).cast());
19532 }
19533 }
19534 // lane-deblock2: one monomorphised kernel per edge length, and an
19535 // empty filter mask returns without any write-back at all.
19536 let modified = match len {
19537 4 => filter16::<4>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
19538 6 => filter16::<6>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
19539 8 => filter16::<8>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
19540 _ => filter16::<14>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
19541 };
19542 if !modified {
19543 return;
19544 }
19545 if vertical {
19546 transpose16(&mut t);
19547 for j in 0..16 {
19548 _mm256_storeu_si256(p.add(base + j * stride - 8).cast(), t[j]);
19549 }
19550 } else {
19551 let top = base - 8 * stride;
19552 let (a, b) = match len {
19553 4 | 6 => (6, 10),
19554 8 => (5, 11),
19555 _ => (2, 14),
19556 };
19557 for i in a..b {
19558 _mm256_storeu_si256(p.add(top + i * stride).cast(), t[i]);
19559 }
19560 }
19561 }
19562}
19563
19564/// [`filter_edge`] for 16 adjacent edge lines that share `edge_params`'
19565/// output. Returns `false` when this build or CPU has no kernel, leaving the
19566/// caller on the scalar path.
19567#[allow(unused_variables)]
19568fn filter_edge16(
19569 data: &mut [u16],
19570 base: usize,
19571 stride: usize,
19572 vertical: bool,
19573 len: u8,
19574 level: i32,
19575 sharpness: u8, fctx: &crate::decode::FrameCtx,
19576) -> bool {
19577 #[cfg(target_arch = "x86_64")]
19578 {
19579 if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 {
19580 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
19581 let shift = bit_depth(fctx) - 8;
19582 // SAFETY: the avx2 arm is reached only when the CPU reports it,
19583 // and `deblock_plane` checks the kernel's edge bounds.
19584 #[allow(unsafe_code)]
19585 unsafe {
19586 deblock_simd::edge16(
19587 data,
19588 base,
19589 stride,
19590 vertical,
19591 len,
19592 blimit << shift,
19593 limit << shift,
19594 hev_thr << shift,
19595 1 << shift,
19596 1 << shift,
19597 sample_max(fctx),
19598 )
19599 };
19600 return true;
19601 }
19602 }
19603 false
19604}
19605
19606/// One plane's worth of spec 7.14: every vertical edge across the plane,
19607/// then every horizontal edge (the order the spec and libaom both use).
19608fn deblock_plane(
19609 plane: &mut PlaneBuf<'static>,
19610 plane_idx: usize,
19611 lf: &LoopFilterParams,
19612 n: &Neighbours,
19613 frame_width: usize,
19614 frame_height: usize, fctx: &crate::decode::FrameCtx,
19615) {
19616 // spec 7.14's order: this plane's whole vertical pass, then its whole
19617 // horizontal one. lane-pipefilt split the two into one row-ranged
19618 // function so the per-superblock-row pipeline can run them a band at a
19619 // time; `0..usize::MAX` is the whole plane, i.e. exactly this call.
19620 deblock_plane_span(plane, plane_idx, lf, n, frame_width, frame_height, 0, usize::MAX, false, fctx);
19621 deblock_plane_span(plane, plane_idx, lf, n, frame_width, frame_height, 0, usize::MAX, true, fctx);
19622}
19623
19624/// One pass of [`deblock_plane`] -- vertical edges (`horz == false`) or
19625/// horizontal ones -- restricted to the plane rows `span_lo..span_hi`.
19626///
19627/// A row span is a legal cut of either pass because a band boundary is a
19628/// multiple of 16 rows and every edge's kernel stays inside its own
19629/// 4-sample group's reach; the pipeline's row lags (see [`pipe_run`]) are
19630/// what keep the two passes in spec order across bands.
19631#[allow(clippy::too_many_arguments)]
19632fn deblock_plane_span(
19633 plane: &mut PlaneBuf<'static>,
19634 plane_idx: usize,
19635 lf: &LoopFilterParams,
19636 n: &Neighbours,
19637 frame_width: usize,
19638 frame_height: usize,
19639 span_lo: usize,
19640 span_hi: usize,
19641 horz: bool,
19642 fctx: &crate::decode::FrameCtx,
19643) {
19644 let chroma = plane_idx != 0;
19645 // r7: libaom clips the deblock loop to the CODED frame's own
19646 // width/height, not the mi-aligned `true_width`/`true_height` margin
19647 // (the padding up to the next 8-pixel/superblock boundary that
19648 // reconstruction still fills in but the loop filter never visits).
19649 // Confirmed against the superres gate: with the margin included, the
19650 // last coded mi column's horizontal edges were filtered when libaom's
19651 // real output leaves them untouched (r6's post-deblock diff, 37 px, all
19652 // in columns 44-47); clipping here closes it (3/3 frames pixel-exact).
19653 // lane-golomb r9: the bound is the MI-ROUNDED frame, not the coded
19654 // frame. libaom's `av1_filter_block_plane_vert/horz` walk the superblock
19655 // and stop at `cm->mi_params.mi_cols`/`mi_rows`, which
19656 // `av1_set_mb_mi` derives from `ALIGN_POWER_OF_TWO(width, 3)` -- the
19657 // 8-pixel-aligned frame, i.e. a 68-wide frame is filtered out to column
19658 // 72 and the vertical edge AT x=68 is a real edge that rewrites the
19659 // in-crop columns 64..67. Clipping at `frame_width` skipped it, which is
19660 // the +-1 straddling-band defect (68x192 cq35, frame 1, 141 luma pixels
19661 // all in columns 64..67; frame 0 survived because that edge carried no
19662 // filter level there). r7's superres measurement is preserved: its frame
19663 // was already 8-aligned, so this bound equals `frame_width` there and
19664 // still excludes the superblock padding up to `true_width`.
19665 let (cw, ch) = if chroma {
19666 (frame_width.div_ceil(2), frame_height.div_ceil(2))
19667 } else {
19668 (frame_width, frame_height)
19669 };
19670 let (tw, th, stride) = (
19671 plane.true_width.min(cw),
19672 plane.true_height.min(ch),
19673 plane.width,
19674 );
19675 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") {
19676 eprintln!("DEBLOCK plane={plane_idx} tw={tw} th={th} stride={stride} true={}x{} crop={cw}x{ch}", plane.true_width, plane.true_height);
19677 }
19678 // lane-perf8: both passes iterate the edge's OWN direction innermost, so
19679 // 4 consecutive 4-sample groups (16 lines) can go through one AVX2
19680 // kernel. The swap is order-preserving: a filtered group overlaps only
19681 // groups along the edge it sits on -- the vertical pass's writes at
19682 // `x0` reach columns `x0 - 7 ..= x0 + 5` of its own 4 rows, so the
19683 // dependence is on ascending `x0` within a row, which stays the outer
19684 // loop's order, and rows remain independent (horizontal pass mirrored).
19685 let rows = plane.data.len() / stride.max(1);
19686 let seg_lf_active = fctx.seg.with(|s| s.borrow().enabled);
19687 // lane-filt1: both passes are split across `EC_AV1_FILTER_THREADS`
19688 // bands along the axis whose writes are disjoint. A vertical edge's
19689 // 4-sample groups write columns `x0-7 ..= x0+5` of their OWN 4 rows, so
19690 // row bands never touch each other; a horizontal edge's groups write rows
19691 // `y0-7 ..= y0+6` of their own 4 columns, so column bands never do. Both
19692 // read the mode-info grids immutably. The grouping a band starts with is
19693 // free: every 4-row (4-column) group's output is a pure function of that
19694 // group, whether it goes through `filter_edge16` with three neighbours or
19695 // through `filter_edge` alone. Band boundaries are multiples of 16 so no
19696 // group ever straddles one.
19697 // lane-perf10 merge: the output plane is owned (perf10 made mutable
19698 // plane params PlaneBuf<'static>); force the Cow to Owned ONCE here so
19699 // the bands below never clone it concurrently.
19700 plane.data.to_mut();
19701 let threads = crate::par::filter_threads();
19702 let sp = crate::par::Shared::new(plane);
19703 let (sp_lo, sp_hi) = (span_lo.min(th), span_hi.min(th));
19704 let vbands: Vec<(usize, usize)> = if horz || sp_lo >= sp_hi {
19705 Vec::new()
19706 } else {
19707 crate::par::bands((sp_hi - sp_lo).div_ceil(16), threads)
19708 .into_iter()
19709 .map(|(a, b)| (sp_lo + a * 16, (sp_lo + b * 16).min(sp_hi)))
19710 .collect()
19711 };
19712 crate::par::run_bands(&vbands, fctx, |y_lo, y_hi, fctx| {
19713 // SAFETY: this band writes only rows `y_lo..y_hi` of the plane, which
19714 // no other band touches (see `Shared`'s own corner-cut note).
19715 #[allow(unsafe_code)]
19716 let plane = unsafe { sp.get() };
19717 // lane-deblock2: this band's own level table and pass constants,
19718 // built once per band instead of re-derived per 4-pixel edge.
19719 let vctx = EdgeCtx::new(lf, n, plane_idx, 0, chroma, seg_lf_active, fctx);
19720 let mut x0 = 4usize;
19721 while x0 < tw {
19722 let mut y0 = y_lo;
19723 while y0 < y_hi {
19724 if y0 + 16 <= y_hi && x0 >= 8 && x0 + 8 <= stride {
19725 let ps: [Option<(u8, i32)>; 4] =
19726 std::array::from_fn(|k| edge_params(&vctx, x0, y0 + 4 * k));
19727 if let Some((len, level)) = ps[0] {
19728 if ps.iter().all(|p| *p == ps[0])
19729 && filter_edge16(
19730 plane.data.to_mut(),
19731 y0 * stride + x0,
19732 stride,
19733 true,
19734 len,
19735 level,
19736 lf.sharpness, fctx,
19737 )
19738 {
19739 y0 += 16;
19740 continue;
19741 }
19742 }
19743 for (k, p) in ps.iter().enumerate() {
19744 if let Some((len, level)) = *p {
19745 filter_edge(
19746 plane.data.to_mut(),
19747 (y0 + 4 * k) * stride + x0,
19748 stride as isize,
19749 1,
19750 len,
19751 level,
19752 lf.sharpness, fctx,
19753 );
19754 }
19755 }
19756 y0 += 16;
19757 continue;
19758 }
19759 if let Some((len, level)) = edge_params(&vctx, x0, y0) {
19760 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") && plane_idx == 0 {
19761 eprintln!("VEDGE x0={x0} y0={y0} len={len} level={level}");
19762 }
19763 filter_edge(
19764 plane.data.to_mut(),
19765 y0 * stride + x0,
19766 stride as isize,
19767 1,
19768 len,
19769 level,
19770 lf.sharpness, fctx,
19771 );
19772 }
19773 y0 += 4;
19774 }
19775 x0 += 4;
19776 }
19777 });
19778 // The horizontal pass runs only after the WHOLE vertical pass of this
19779 // plane (spec 7.14 order), which `run_bands` guarantees by joining.
19780 let hbands: Vec<(usize, usize)> = if !horz || sp_lo >= sp_hi {
19781 Vec::new()
19782 } else {
19783 crate::par::bands(tw.div_ceil(16), threads)
19784 .into_iter()
19785 .map(|(a, b)| (a * 16, (b * 16).min(tw)))
19786 .collect()
19787 };
19788 crate::par::run_bands(&hbands, fctx, |x_lo, x_hi, fctx| {
19789 // SAFETY: this band writes only columns `x_lo..x_hi`.
19790 #[allow(unsafe_code)]
19791 let plane = unsafe { sp.get() };
19792 let hctx = EdgeCtx::new(lf, n, plane_idx, 1, chroma, seg_lf_active, fctx);
19793 let mut y0 = sp_lo.max(4);
19794 while y0 < sp_hi {
19795 let mut x0 = x_lo;
19796 while x0 < x_hi {
19797 if x0 + 16 <= x_hi && y0 >= 8 && y0 + 7 <= rows {
19798 let ps: [Option<(u8, i32)>; 4] =
19799 std::array::from_fn(|k| edge_params(&hctx, x0 + 4 * k, y0));
19800 if let Some((len, level)) = ps[0] {
19801 if ps.iter().all(|p| *p == ps[0])
19802 && filter_edge16(
19803 plane.data.to_mut(),
19804 y0 * stride + x0,
19805 stride,
19806 false,
19807 len,
19808 level,
19809 lf.sharpness, fctx,
19810 )
19811 {
19812 x0 += 16;
19813 continue;
19814 }
19815 }
19816 for (k, p) in ps.iter().enumerate() {
19817 if let Some((len, level)) = *p {
19818 filter_edge(
19819 plane.data.to_mut(),
19820 y0 * stride + x0 + 4 * k,
19821 1,
19822 stride as isize,
19823 len,
19824 level,
19825 lf.sharpness, fctx,
19826 );
19827 }
19828 }
19829 x0 += 16;
19830 continue;
19831 }
19832 if let Some((len, level)) = edge_params(&hctx, x0, y0) {
19833 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE")
19834 && plane_idx == 0
19835 && x0 == 44
19836 {
19837 eprintln!(
19838 "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}",
19839 lf.sharpness
19840 );
19841 }
19842 filter_edge(
19843 plane.data.to_mut(),
19844 y0 * stride + x0,
19845 1,
19846 stride as isize,
19847 len,
19848 level,
19849 lf.sharpness, fctx,
19850 );
19851 }
19852 x0 += 4;
19853 }
19854 y0 += 4;
19855 } });
19856}
19857
19858/// lane-perf6: reused whole-plane `u16` buffers. Every frame takes a
19859/// pre-CDEF snapshot of all three planes, a post-deblock snapshot when loop
19860/// restoration is active, and a fresh LR destination per plane -- freshly
19861/// allocated that is ~25 MB of `mmap`/`munmap` per frame at 4K, so every
19862/// sample written also takes a first-touch page fault. The buffers are handed
19863/// back here instead and refilled in place.
19864///
19865/// lane-memfix: PROCESS-WIDE, not one stash per thread. These buffers do not
19866/// stay on one thread: the frame thread allocates the snapshots and a filter
19867/// worker returns them ([`pipe_run_lr`] swaps the picture's pre-LR planes
19868/// into the pool from whichever worker ran it), so a per-thread pool leaked
19869/// whole-plane buffers into every worker it touched -- 19 MB a set, times
19870/// every pool thread the decode ever created. One shared pool with a hard
19871/// entry cap bounds the retention at [`SCRATCH_CAP`] buffers no matter how
19872/// many threads cycle through it; anything over the cap is freed.
19873static PLANE_SCRATCH: std::sync::Mutex<Vec<Vec<u16>>> = std::sync::Mutex::new(Vec::new());
19874
19875/// Most buffers the shared pool keeps. ~3 whole-plane sets per in-flight 4K
19876/// frame at the shipped `EC_AV1_THREADS` ceiling; the frames actually in
19877/// flight cycle through far fewer.
19878const SCRATCH_CAP: usize = 32;
19879
19880/// Takes a pooled buffer for a caller that wants `n` samples, best-fit by
19881/// CAPACITY so a chroma-sized request does not permanently promote a
19882/// luma-sized allocation (every pooled buffer would drift to the largest
19883/// size otherwise). `None` when the pool is empty.
19884fn scratch_take(n: usize) -> Option<Vec<u16>> {
19885 let mut p = PLANE_SCRATCH.lock().unwrap();
19886 if p.is_empty() {
19887 return None;
19888 }
19889 let fit = p
19890 .iter()
19891 .enumerate()
19892 .filter(|(_, v)| v.capacity() >= n)
19893 .min_by_key(|(_, v)| v.capacity())
19894 .map(|(i, _)| i);
19895 let i = match fit {
19896 Some(i) => i,
19897 // Nothing big enough: grow the largest rather than a small one.
19898 None => p
19899 .iter()
19900 .enumerate()
19901 .max_by_key(|(_, v)| v.capacity())
19902 .map(|(i, _)| i)
19903 .expect("the pool is not empty"),
19904 };
19905 Some(p.swap_remove(i))
19906}
19907
19908/// A pooled buffer holding a copy of `src`.
19909fn scratch_from(src: &[u16]) -> Vec<u16> {
19910 let mut v = scratch_take(src.len()).unwrap_or_default();
19911 v.clear();
19912 v.extend_from_slice(src);
19913 v
19914}
19915
19916/// An empty pooled buffer, for a caller that fills it itself.
19917fn scratch_empty() -> Vec<u16> {
19918 let mut v = scratch_take(0).unwrap_or_default();
19919 v.clear();
19920 v
19921}
19922
19923/// A pooled buffer of exactly `n` samples whose contents are NOT cleared --
19924/// for a caller that writes every element it later reads (lane-copy: the
19925/// post-deblock snapshot writes 4 rows in 64 and reads no other).
19926fn scratch_sized(n: usize) -> Vec<u16> {
19927 let mut v = scratch_take(n).unwrap_or_default();
19928 if v.len() > n {
19929 v.truncate(n);
19930 } else if v.len() < n {
19931 v.resize(n, 0);
19932 }
19933 v
19934}
19935
19936/// A plane's post-deblock snapshot, its samples taken from the pool (every
19937/// other field is `usize`).
19938///
19939/// lane-copy: loop restoration is the only reader, and spec 7.17.2's stripe
19940/// boundary substitution reads the post-deblock plane at just four rows
19941/// around each interior stripe boundary (`row` outside
19942/// `[stripe_v_start, stripe_v_end)` resolves to `stripe_v_start-1`,
19943/// `stripe_v_start-2`, `stripe_v_end` or `stripe_v_end+1` in
19944/// `restoration::lr_src_row`); stripes are `64 >> ss_y` rows offset by
19945/// `RESTORATION_UNIT_OFFSET = 8 >> ss_y`, so the boundaries sit at
19946/// `k*stripe_h - offset`. Copying only those rows turns a full-plane
19947/// memmove per plane per frame into 4 rows in 64 (luma). Every other row of
19948/// the pooled buffer keeps whatever a previous frame left there -- an
19949/// initialised value that no reader ever reaches.
19950fn snap_alloc(p: &PlaneBuf<'_>) -> PlaneBuf<'static> {
19951 PlaneBuf { data: std::borrow::Cow::Owned(scratch_sized(p.data.len())), ..*p }
19952}
19953
19954fn plane_snapshot(p: &PlaneBuf<'_>, ss_y: u32) -> PlaneBuf<'static> {
19955 let mut data = scratch_sized(p.data.len());
19956 let rows = if p.width == 0 { 0 } else { p.data.len() / p.width };
19957 let stripe_h = 64usize >> ss_y;
19958 let offset = 8usize >> ss_y;
19959 let mut b = stripe_h - offset;
19960 while b < rows {
19961 let (lo, hi) = (b - 2, (b + 2).min(rows));
19962 data[lo * p.width..hi * p.width].copy_from_slice(&p.data[lo * p.width..hi * p.width]);
19963 b += stripe_h;
19964 }
19965 PlaneBuf { data: std::borrow::Cow::Owned(data), ..*p }
19966}
19967
19968/// The pre-filter reconstruction of one coded frame, plus the per-block state
19969/// the loop filters read.
19970///
19971/// The encoder's filter search ([`crate::filter_search::pick_filters`])
19972/// decodes the same coded tile under ~25 candidate deblock/CDEF parameter
19973/// sets to score each one, and the entropy decode and reconstruction it
19974/// repeats are identical every time -- both filters run after it, on the
19975/// finished planes. That re-parse was 24% of the encoder's profile. A caller
19976/// arms [`arm_filter_replay`] around ONE decode and then re-runs the filters
19977/// alone through [`replay_filters`]; the result is the same picture the full
19978/// decode would have returned, because it is the same two calls on a copy of
19979/// the same planes.
19980pub(crate) struct FilterReplay {
19981 y: PlaneBuf<'static>,
19982 u: PlaneBuf<'static>,
19983 v: PlaneBuf<'static>,
19984 neighbours: Neighbours,
19985 frame_width: usize,
19986 frame_height: usize,
19987 width: usize,
19988 height: usize,
19989 /// The reconstructed extent (`mi_cols`/`mi_rows` * 4), for the wide-margin
19990 /// stash the cropped return path leaves behind.
19991 true_width: usize,
19992 true_height: usize,
19993 /// lane-av1fpar: plane buffers this replay is done with. Every candidate
19994 /// works on its own copy of three ~6 MB planes, and a fresh `Vec` per
19995 /// copy is a fresh mmap the kernel faults in page by page -- 12.6% of a
19996 /// 1080p frame's wall in allocation, not in filtering. Recycled here
19997 /// instead; the pool holds at most the six planes one candidate has live.
19998 scratch: Vec<Vec<u16>>,
19999 /// lane-av1cap2: the final replay's post-CDEF luma plane and the TRUE
20000 /// post-deblock rows loop restoration substitutes at its stripe
20001 /// borders ([`plane_snapshot`], exactly `restoration::lr_src_row`'s
20002 /// rows) -- what [`replay_restoration`] filters, instead of decoding
20003 /// the re-coded tile a second time.
20004 final_luma: Option<(PlaneBuf<'static>, PlaneBuf<'static>)>,
20005 /// lane-av1speed3: the previous candidate's DESTINATION planes, still
20006 /// holding its post-CDEF samples, and one byte per 8x8 CDEF unit its
20007 /// filter wrote (see [`cdef_band`]). The CDEF half of the search moves
20008 /// no deblocking level, so every candidate of it used to copy the three
20009 /// post-deblock planes (~19 MB at 4K) into fresh destinations. Here the
20010 /// destinations are kept and only the units the last candidate touched
20011 /// are restored -- the same bytes, since a unit nobody wrote still holds
20012 /// the deblocked sample it was copied from.
20013 work: Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
20014 wrote: Vec<u8>,
20015 /// The strengths [`FilterReplay::work`] was filtered under: a plane whose
20016 /// new candidate can only write MORE units than the old one needs no
20017 /// restore at all, since every unit CDEF writes it writes from the
20018 /// post-deblock source alone.
20019 work_cdef: Option<CdefParams>,
20020 /// The last deblocked planes and the levels that produced them.
20021 /// Deblocking depends on nothing else the search moves, and the search
20022 /// fixes the levels before it walks the CDEF strengths, so every
20023 /// candidate after the first of a level pair replays CDEF alone.
20024 deblocked: Option<(LoopFilterParams, PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
20025}
20026
20027thread_local! {
20028 /// Set by [`arm_filter_replay`] for the span of one decode.
20029 static REPLAY_ARMED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
20030 /// What that decode captured, until [`clear_filter_replay`].
20031 static REPLAY: std::cell::RefCell<Option<FilterReplay>> =
20032 const { std::cell::RefCell::new(None) };
20033}
20034
20035/// Capture this thread's next decode's pre-filter frame (see [`FilterReplay`]).
20036pub(crate) fn arm_filter_replay() {
20037 REPLAY_ARMED.set(true);
20038}
20039
20040/// Test-only: force every filter candidate through a full decode, so a gate
20041/// can hold the replay against the decode it stands in for
20042/// (`encoder::tests::filter_replay_codes_the_same_stream_as_a_full_decode`).
20043#[cfg(test)]
20044static REPLAY_DISABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
20045
20046#[cfg(test)]
20047pub(crate) fn set_filter_replay_disabled(off: bool) {
20048 REPLAY_DISABLED.store(off, std::sync::atomic::Ordering::Relaxed);
20049}
20050
20051// Test-only: run the capture decode `replay_final` replaced as well, and
20052// hold its picture and its `FilterStages` against the replay's
20053// (`encoder::tests::filter_replay_final_matches_the_capture_decode`).
20054// Thread-local, not a global: the filter stage runs on the frame thread the
20055// test itself drives, and a process-wide flag would put every test encoding
20056// in parallel with this one through the extra decode too.
20057#[cfg(test)]
20058thread_local! {
20059 static VERIFY_FINAL: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
20060}
20061
20062#[cfg(test)]
20063pub(crate) fn set_verify_final_replay(on: bool) {
20064 VERIFY_FINAL.set(on);
20065}
20066
20067#[cfg(test)]
20068pub(crate) fn verify_final_replay() -> bool {
20069 VERIFY_FINAL.get()
20070}
20071
20072/// Drop the armed flag and anything captured: the tile it belongs to is done.
20073pub(crate) fn clear_filter_replay() {
20074 REPLAY_ARMED.set(false);
20075 REPLAY.with_borrow_mut(|r| *r = None);
20076}
20077
20078/// The capture itself, called from the decoder's own pre-filter point. Owns
20079/// copies of the planes, since the caller filters them in place.
20080fn capture_filter_replay(
20081 y: &PlaneBuf<'_>,
20082 u: &PlaneBuf<'_>,
20083 v: &PlaneBuf<'_>,
20084 neighbours: &Neighbours,
20085 frame_width: usize,
20086 frame_height: usize,
20087 width: usize,
20088 height: usize,
20089 true_width: usize,
20090 true_height: usize,
20091) {
20092 if !REPLAY_ARMED.replace(false) {
20093 return;
20094 }
20095 let own = |p: &PlaneBuf<'_>| PlaneBuf { data: std::borrow::Cow::Owned(p.data.to_vec()), ..*p };
20096 REPLAY.with_borrow_mut(|slot| {
20097 *slot = Some(FilterReplay {
20098 y: own(y),
20099 u: own(u),
20100 v: own(v),
20101 neighbours: neighbours.clone(),
20102 frame_width,
20103 frame_height,
20104 width,
20105 height,
20106 true_width,
20107 true_height,
20108 scratch: Vec::new(),
20109 work: None,
20110 wrote: Vec::new(),
20111 work_cdef: None,
20112 final_luma: None,
20113 deblocked: None,
20114 });
20115 });
20116}
20117
20118/// Restores, from the post-deblock cache, every sample the previous CDEF
20119/// candidate may have written: for each unit row, the column span between
20120/// its first and last written unit (a superset of the written units, which
20121/// is what makes the copy contiguous -- and never more than the whole-plane
20122/// copy it replaces). `unit` is this plane's CDEF unit side, 8 for luma and
20123/// 4 for 4:2:0 chroma.
20124fn restore_written(
20125 dst: &mut PlaneBuf<'static>,
20126 src: &PlaneBuf<'_>,
20127 wrote: &[u8],
20128 mask: u8,
20129 unit_cols: usize,
20130 unit: usize,
20131) {
20132 let w = dst.width;
20133 if w == 0 || unit_cols == 0 || wrote.is_empty() {
20134 return;
20135 }
20136 let rows = dst.data.len() / w;
20137 let s: &[u16] = &src.data;
20138 let d = dst.data.to_mut();
20139 let band = |d: &mut [u16], wr: &[u8], ur0: usize| {
20140 for (i, row) in wr.chunks(unit_cols).enumerate() {
20141 let Some(c0) = row.iter().position(|&b| b & mask != 0) else {
20142 continue;
20143 };
20144 let c1 = row.iter().rposition(|&b| b & mask != 0).expect("just found one");
20145 let (x0, x1) = ((c0 * unit).min(w), ((c1 + 1) * unit).min(w));
20146 let ur = ur0 + i;
20147 let (y0, y1) = ((ur * unit).min(rows), ((ur + 1) * unit).min(rows));
20148 for r in y0..y1 {
20149 let off = (r - ur0 * unit) * w;
20150 d[off + x0..off + x1].copy_from_slice(&s[r * w + x0..r * w + x1]);
20151 }
20152 }
20153 };
20154 let urows = wrote.len() / unit_cols;
20155 let threads = crate::par::filter_threads().min(urows.max(1));
20156 if threads <= 1 {
20157 band(d, wrote, 0);
20158 return;
20159 }
20160 let per = urows.div_ceil(threads);
20161 let batch = crate::par::Batch::new("ec-av1-filter");
20162 for (i, (dc, wr)) in d.chunks_mut(per * unit * w).zip(wrote.chunks(per * unit_cols)).enumerate()
20163 {
20164 let band = &band;
20165 batch.submit(move || band(dc, wr, i * per));
20166 }
20167}
20168
20169/// One candidate's working copy of a captured plane, off [`FilterReplay`]'s
20170/// own buffer pool: a cleared `Vec` that already has the capacity keeps the
20171/// allocator and the page fault handler out of the filter search.
20172fn pooled(p: &PlaneBuf<'_>, scratch: &mut Vec<Vec<u16>>) -> PlaneBuf<'static> {
20173 let mut buf = scratch.pop().unwrap_or_default();
20174 let src: &[u16] = &p.data;
20175 let threads = crate::par::filter_threads();
20176 if buf.len() != src.len() || threads <= 1 {
20177 buf.clear();
20178 buf.extend_from_slice(src);
20179 } else {
20180 // A recycled buffer is already the right length, so the copy is a
20181 // plain `copy_from_slice` -- and one worth banding: ~6 MB per
20182 // candidate is memory bandwidth, not arithmetic, and the halves are
20183 // disjoint `&mut` slices (no `par::Shared` needed).
20184 let per = src.len().div_ceil(threads);
20185 let batch = crate::par::Batch::new("ec-av1-filter");
20186 for (dst, src) in buf.chunks_mut(per).zip(src.chunks(per)) {
20187 batch.submit(move || dst.copy_from_slice(src));
20188 }
20189 }
20190 PlaneBuf { data: std::borrow::Cow::Owned(buf), ..*p }
20191}
20192
20193/// The filter half of a captured decode, under new parameters: exactly the
20194/// [`apply_deblock`] / [`apply_cdef`] pair the decoder's own tail runs, on a
20195/// copy of the captured planes. `None` when nothing is captured (the caller
20196/// then decodes for real).
20197pub(crate) fn replay_filters(
20198 loop_filter: &LoopFilterParams,
20199 cdef: &CdefParams,
20200 fctx: &FrameCtx,
20201) -> Option<Picture> {
20202 #[cfg(test)]
20203 if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) {
20204 return None;
20205 }
20206 replay_inner(loop_filter, cdef, None, fctx).map(|(picture, _)| picture)
20207}
20208
20209/// lane-av1cap: the filter stage's LAST replay -- the WINNING parameters,
20210/// under the per-64x64 `cdef_idx` grid the re-coded tile carries. The stage
20211/// used to reach this picture by decoding that re-coded tile a second time
20212/// (10% of a 4K frame's encode), only because the loop-restoration search
20213/// needs the decoder's own post-CDEF plane
20214/// ([`FrameCtx::capture_stages`]). It is the same two kernel calls
20215/// ([`apply_deblock`], [`apply_cdef`]) on the same captured pre-filter
20216/// planes in the same order, so it is the same bytes -- pinned by
20217/// `encoder::tests::filter_replay_final_matches_the_capture_decode`, which
20218/// runs the decode as well and holds picture and stages against it.
20219///
20220/// `want_stages` mirrors `capture_stages`' own `deblocked = None` arm: that
20221/// decode's header says `RESTORE_NONE`, so the decoder took no pre-CDEF
20222/// snapshot and handed the post-CDEF plane over for both stages.
20223pub(crate) fn replay_final(
20224 loop_filter: &LoopFilterParams,
20225 cdef: &CdefParams,
20226 idx_grid: &[u8],
20227 want_stages: bool,
20228 fctx: &FrameCtx,
20229) -> Option<(Picture, Option<FilterStages>)> {
20230 #[cfg(test)]
20231 if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) {
20232 return None;
20233 }
20234 replay_inner(loop_filter, cdef, Some((idx_grid, want_stages)), fctx)
20235}
20236
20237fn replay_inner(
20238 loop_filter: &LoopFilterParams,
20239 cdef: &CdefParams,
20240 // `Some((cdef_idx grid, capture the filter stages))` for the final
20241 // replay; `None` for a scoring candidate, which always codes `bits == 0`.
20242 final_pass: Option<(&[u8], bool)>,
20243 fctx: &FrameCtx,
20244) -> Option<(Picture, Option<FilterStages>)> {
20245 REPLAY.with_borrow_mut(|slot| {
20246 let r = slot.as_mut()?;
20247 let hit = matches!(&r.deblocked, Some((lf, ..)) if lf == loop_filter);
20248 // Set when the working planes ARE the deblocked planes (see below):
20249 // they go into the cache at the end, and the picture is cropped out
20250 // of them rather than taking their buffers.
20251 let mut share = false;
20252 let cpt = crate::par::timer(crate::par::S_COPY);
20253 let unit_cols = r.neighbours.mi_cols.div_ceil(2);
20254 let unit_rows = r.neighbours.mi_rows.div_ceil(2);
20255 let (mut y, mut u, mut v) = if hit {
20256 let work = r.work.take();
20257 let wrote = std::mem::take(&mut r.wrote);
20258 // `cdef_adjust_strength` is monotone in the strength it is given,
20259 // so a candidate whose primary strength is no lower and whose
20260 // secondary is zero only if the last one's was writes every unit
20261 // the last one wrote -- and writes it from the same post-deblock
20262 // source, so the samples under it need not be put back first.
20263 // Only while both candidates carry ONE strength pair (`bits ==
20264 // 0`, every scoring candidate) and read the same `cdef_idx` grid.
20265 let superset = |cur: (u8, u8), old: (u8, u8)| cur.0 >= old.0 && (cur.1 != 0 || old.1 == 0);
20266 let (skip_y, skip_uv) = match (final_pass, &r.work_cdef) {
20267 (None, Some(old)) if old.bits == 0 && cdef.bits == 0 => (
20268 superset(
20269 (cdef.y_pri_strength[0], cdef.y_sec_strength[0]),
20270 (old.y_pri_strength[0], old.y_sec_strength[0]),
20271 ),
20272 superset(
20273 (cdef.uv_pri_strength[0], cdef.uv_sec_strength[0]),
20274 (old.uv_pri_strength[0], old.uv_sec_strength[0]),
20275 ),
20276 ),
20277 _ => (false, false),
20278 };
20279 let (deblocked, scratch) = (&r.deblocked, &mut r.scratch);
20280 let (_, dy, du, dv) = deblocked.as_ref().expect("just matched");
20281 match work {
20282 Some((mut wy, mut wu, mut wv)) => {
20283 if !skip_y {
20284 restore_written(&mut wy, dy, &wrote, 1, unit_cols, 8);
20285 }
20286 if !skip_uv {
20287 restore_written(&mut wu, du, &wrote, 2, unit_cols, 4);
20288 restore_written(&mut wv, dv, &wrote, 2, unit_cols, 4);
20289 }
20290 (wy, wu, wv)
20291 }
20292 None => (pooled(dy, scratch), pooled(du, scratch), pooled(dv, scratch)),
20293 }
20294 } else {
20295 // The levels moved, so the cached deblocked planes are dead:
20296 // their buffers are this candidate's working copies.
20297 for plane in r.work.take().into_iter().flat_map(|(a, b, c)| [a, b, c]) {
20298 r.scratch.push(plane.data.into_owned());
20299 }
20300 r.work_cdef = None;
20301 if let Some((_, dy, du, dv)) = r.deblocked.take() {
20302 r.scratch.push(dy.data.into_owned());
20303 r.scratch.push(du.data.into_owned());
20304 r.scratch.push(dv.data.into_owned());
20305 }
20306 let (cap_y, cap_u, cap_v, scratch) = (&r.y, &r.u, &r.v, &mut r.scratch);
20307 let (mut y, mut u, mut v) =
20308 (pooled(cap_y, scratch), pooled(cap_u, scratch), pooled(cap_v, scratch));
20309 let _t = crate::par::timer(crate::par::S_DEBLOCK);
20310 apply_deblock(
20311 &mut y,
20312 &mut u,
20313 &mut v,
20314 loop_filter,
20315 &r.neighbours,
20316 r.frame_width,
20317 r.frame_height,
20318 fctx,
20319 );
20320 // lane-av1cap2: an all-zero-strength CDEF writes no sample at
20321 // all ([`cdef_all_zero`]'s own early return), so THESE planes
20322 // are already this candidate's output -- they become the
20323 // deblock cache at the end instead of being copied into it
20324 // here, which is three ~6 MB copies less per candidate that
20325 // moves the levels (the whole deblocking half of the search:
20326 // its CDEF strengths are still (0,0)).
20327 share = cdef_all_zero(cdef);
20328 if !share {
20329 let scratch = &mut r.scratch;
20330 r.deblocked = Some((
20331 *loop_filter,
20332 pooled(&y, scratch),
20333 pooled(&u, scratch),
20334 pooled(&v, scratch),
20335 ));
20336 }
20337 (y, u, v)
20338 };
20339 drop(cpt);
20340 // The winner's `cdef_idx` literals live in the re-coded tile, which
20341 // nothing parses on this path -- hand the grid the encoder already
20342 // chose straight to the filter (`bits == 0` leaves the grid the last
20343 // parse sized, which is what every scoring candidate reads).
20344 if let Some((grid, _)) = final_pass.filter(|(g, _)| !g.is_empty()) {
20345 fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = grid.to_vec());
20346 }
20347 let ct = crate::par::timer(crate::par::S_CDEF);
20348 let mut wrote = std::mem::take(&mut r.wrote);
20349 wrote.clear();
20350 wrote.resize(unit_cols * unit_rows, 0);
20351 r.work_cdef = Some(*cdef);
20352 let pre = r.deblocked.as_ref().map(|(_, dy, du, dv)| {
20353 (dy.data.as_ref(), du.data.as_ref(), dv.data.as_ref())
20354 });
20355 apply_cdef(
20356 &mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx,
20357 pre,
20358 Some(&mut wrote),
20359 );
20360 drop(ct);
20361 if final_pass.is_some_and(|(_, want)| want) {
20362 // The loop-restoration search runs on the stages above (where
20363 // post-CDEF stands in for post-deblock, as the capture decode
20364 // had it); the FILTER this frame ends up applying reads the
20365 // real post-deblock rows, which is what the decoder does.
20366 let snapshot = if share {
20367 // Nothing filtered these planes after the deblock, so they
20368 // are the post-deblock picture themselves.
20369 Some(plane_snapshot(&y, 0))
20370 } else {
20371 r.deblocked.as_ref().map(|(_, dy, ..)| plane_snapshot(dy, 0))
20372 };
20373 let scratch = &mut r.scratch;
20374 r.final_luma = snapshot.map(|d| (pooled(&y, scratch), d));
20375 }
20376 let stages = final_pass.and_then(|(_, want)| {
20377 want.then(|| FilterStages {
20378 deblocked: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()],
20379 cdefed: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()],
20380 stride: [y.width, u.width, v.width],
20381 })
20382 });
20383 // The capture only happens on the shape whose tail is the two
20384 // filter calls and the crop (no superres, no loop restoration), so
20385 // what is left is that crop -- byte for byte the cropped return path
20386 // of the decode this replaces, wide-margin stash included.
20387 //
20388 // lane-av1fpar: the crop is why this arm exists at all. The capture
20389 // used to demand `frame == plane` dimensions, which no editor size
20390 // meets (1080 and 1608 both pad to a superblock row), so every
20391 // candidate of every frame at those sizes fell through to a full
20392 // re-decode -- 57% of a 1080p frame's wall.
20393 let (fw, fh) = (r.frame_width, r.frame_height);
20394 if fw == r.width && fh == r.height {
20395 fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None);
20396 r.wrote = Vec::new();
20397 r.work_cdef = None;
20398 if share {
20399 let picture = Picture {
20400 width: r.width,
20401 height: r.height,
20402 y: y.data.to_vec(),
20403 u: u.data.to_vec(),
20404 v: v.data.to_vec(),
20405 };
20406 r.deblocked = Some((*loop_filter, y, u, v));
20407 return Some((picture, stages));
20408 }
20409 return Some((
20410 Picture {
20411 width: r.width,
20412 height: r.height,
20413 y: y.data.into_owned(),
20414 u: u.data.into_owned(),
20415 v: v.data.into_owned(),
20416 },
20417 stages,
20418 ));
20419 }
20420 let crop = |plane: &PlaneBuf<'_>, w: usize, h: usize| -> Vec<u16> {
20421 let mut out = Vec::with_capacity(w * h);
20422 for row in 0..h {
20423 out.extend(plane.data[row * plane.width..][..w].iter().copied());
20424 }
20425 out
20426 };
20427 let (tw, th) = (r.true_width, r.true_height);
20428 fctx.last_frame_wide_margin.with(|m| {
20429 *m.borrow_mut() = (tw > fw || th > fh).then(|| Picture {
20430 width: tw,
20431 height: th,
20432 y: crop(&y, tw, th),
20433 u: crop(&u, tw.div_ceil(2), th.div_ceil(2)),
20434 v: crop(&v, tw.div_ceil(2), th.div_ceil(2)),
20435 });
20436 });
20437 let out = Picture {
20438 width: fw,
20439 height: fh,
20440 y: crop(&y, fw, fh),
20441 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
20442 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
20443 };
20444 // The working planes outlive the crop: either they ARE the
20445 // deblocked planes this candidate's successors reuse, or they go
20446 // back to the pool.
20447 if share {
20448 r.wrote = Vec::new();
20449 r.work_cdef = None;
20450 r.deblocked = Some((*loop_filter, y, u, v));
20451 } else {
20452 // lane-av1speed3: kept whole (post-CDEF samples and all) for the
20453 // next candidate, together with the map of what CDEF wrote.
20454 r.wrote = wrote;
20455 r.work = Some((y, u, v));
20456 }
20457 Some((out, stages))
20458 })
20459}
20460
20461/// lane-av1cap2: the loop-restoration half of the final replay. Once the
20462/// units are chosen the tile is coded a second time to carry them, and that
20463/// re-coded tile used to be DECODED to reach the restored reference frame
20464/// (5.6% of a 4K frame's encode). Loop restoration reads nothing of that
20465/// tile but the per-unit filters the encoder just picked: it is the
20466/// decoder's own [`crate::restoration::apply_loop_restoration_plane`] on
20467/// the post-CDEF plane the final replay produced, with the TRUE
20468/// post-deblock stripe-border rows -- the same call the decoder's
20469/// `apply_loop_restoration` makes, on the same input. Only luma moves: the
20470/// encoder never writes a chroma restoration type other than
20471/// `RESTORE_NONE`, whose kernel hands its input straight back.
20472///
20473/// Returns the cropped luma plane and refreshes the wide-margin stash's own
20474/// luma (restoration writes strictly inside `frame_width x frame_height`,
20475/// so the margin columns past it stand). `None` when nothing was captured
20476/// -- the caller then decodes for real.
20477pub(crate) fn replay_restoration(
20478 lr: &LoopRestorationParams,
20479 units: &[Option<crate::restoration::WienerInfo>],
20480 fctx: &FrameCtx,
20481) -> Option<Vec<u16>> {
20482 #[cfg(test)]
20483 if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) {
20484 return None;
20485 }
20486 REPLAY.with_borrow_mut(|slot| {
20487 let r = slot.as_mut()?;
20488 let (cdefed, deblocked) = r.final_luma.as_ref()?;
20489 let (fw, fh) = (r.frame_width, r.frame_height);
20490 let mut grid = crate::restoration::RestorationGrid::new(lr, fw as u32, fh as u32);
20491 let (horz, vert) = (grid.horz_units[0], grid.vert_units[0]);
20492 if horz == 0 || units.len() != horz * vert {
20493 return None;
20494 }
20495 for (i, filter) in units.iter().enumerate() {
20496 if let Some(info) = filter {
20497 grid.set(0, i / horz, i % horz, crate::restoration::UnitFilter::Wiener(*info));
20498 }
20499 }
20500 let stride = cdefed.width;
20501 let mut out = scratch_empty();
20502 crate::restoration::apply_loop_restoration_plane(
20503 &cdefed.data,
20504 &deblocked.data,
20505 stride,
20506 fw,
20507 fh,
20508 0,
20509 lr.frame_restoration_type[0],
20510 lr.loop_restoration_size[0],
20511 &grid,
20512 0,
20513 &mut out,
20514 None,
20515 fctx,
20516 );
20517 fctx.last_frame_wide_margin.with(|m| {
20518 if let Some(p) = m.borrow_mut().as_mut() {
20519 let tw = p.width;
20520 for row in 0..p.height.min(fh) {
20521 let n = tw.min(fw);
20522 p.y[row * tw..][..n].copy_from_slice(&out[row * stride..][..n]);
20523 }
20524 }
20525 });
20526 let mut y = Vec::with_capacity(fw * fh);
20527 for row in 0..fh {
20528 y.extend(out[row * stride..][..fw].iter().copied());
20529 }
20530 scratch_return(out);
20531 Some(y)
20532 })
20533}
20534
20535/// The output crop, taking the plane by value: a frame whose width is
20536/// already superblock-aligned (only its height is padded) has a padded
20537/// buffer whose stride equals the visible width, so the crop is a pure
20538/// truncation of the buffer we already own -- no full-plane copy at all
20539/// (lane-copy: three ~6 MB memmoves per 4K frame on the frame thread's
20540/// serial tail). Any other shape falls back to the row-by-row copy.
20541fn crop_owned(plane: PlaneBuf<'_>, w: usize, h: usize) -> Vec<u16> {
20542 let stride = plane.width;
20543 let mut data = plane.data.into_owned();
20544 if stride == w {
20545 data.truncate(w * h);
20546 return data;
20547 }
20548 let mut out = Vec::with_capacity(w * h);
20549 for row in 0..h {
20550 out.extend(data[row * stride..][..w].iter().copied());
20551 }
20552 out
20553}
20554
20555/// Hands a buffer back to the pool; the capacity is what is worth keeping.
20556/// Over [`SCRATCH_CAP`] the buffer is dropped (freed) instead -- the cap is
20557/// what keeps a pool shared by every thread from being an unbounded stash.
20558fn scratch_return(v: Vec<u16>) {
20559 let mut p = PLANE_SCRATCH.lock().unwrap();
20560 if p.len() < SCRATCH_CAP {
20561 p.push(v);
20562 }
20563}
20564
20565/// One CDEF mi-row band, as a real function rather than the body of the
20566/// `run_bands` closure: inside the closure the destination planes are
20567/// `&mut` references derived from a `par::Shared` raw pointer in the same
20568/// scope as the `src_*` snapshot reads, so LLVM cannot tell the two apart and
20569/// re-loads through them on every tap. Reference parameters restore `noalias`
20570/// (lane-perf11 (a): -x% instructions at one filter thread).
20571#[allow(clippy::too_many_arguments)]
20572fn cdef_band(
20573 r_lo: usize,
20574 r_hi: usize,
20575 y: &mut PlaneBuf<'static>,
20576 u: &mut PlaneBuf<'static>,
20577 v: &mut PlaneBuf<'static>,
20578 src_y: &[u16],
20579 src_u: &[u16],
20580 src_v: &[u16],
20581 cdef: &CdefParams,
20582 skip_grid: &Neighbours,
20583 idx_grid: &[u8],
20584 sb_cols: usize,
20585 coeff_shift: i32,
20586 damping: i32,
20587 damping_uv: i32,
20588 (frame_w, frame_h): (usize, usize),
20589 fctx: &crate::decode::FrameCtx,
20590 // lane-av1speed3: one byte per 8x8 CDEF unit of the WHOLE frame (stride
20591 // `mi_cols.div_ceil(2)`), set for every unit this band actually filters.
20592 // Bit 0 = this unit's LUMA square was filtered, bit 1 = its chroma ones.
20593 // `cdef_adjust_strength` zeroes a unit's primary strength off its own
20594 // variance, so which units a candidate writes is not a function of its
20595 // strengths alone -- the encoder's filter replay reuses one destination
20596 // plane across candidates and needs the map to restore it.
20597 mut wrote: Option<&mut [u8]>,
20598) {
20599 let unit_cols = skip_grid.mi_cols.div_ceil(2);
20600 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
20601 if sb_cols == 0 {
20602 return 0;
20603 }
20604 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
20605 idx_grid.get(sb_r * sb_cols + sb_c).copied().unwrap_or(0) as usize
20606 };
20607 // One scratch window per plane kind, reused by every unit (8x8 luma and
20608 // 4x4 chroma, each grown by the [`CDEF_BORDER`] tap ring).
20609 // 256 entries, not the (bw + 4) x (bh + 4) samples themselves: the
20610 // AVX2 kernel taps the window in place with two-row loads that reach
20611 // past the last sample, and the tail stays zero for every unit.
20612 let mut win_y = [0i16; 256];
20613 let mut win_uv = [0i16; 256];
20614 let mut mi_r = r_lo;
20615 while mi_r < r_hi {
20616 let mut mi_c = 0usize;
20617 while mi_c < skip_grid.mi_cols {
20618 if skip_grid.is_skip_txfm(mi_r, mi_c) {
20619 hit!(CDEF_SKIPPED_UNITS);
20620 }
20621 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
20622 let sidx = strength_idx(mi_r, mi_c);
20623 let (ox, oy) = (mi_c * 4, mi_r * 4);
20624 // Nothing to do for this unit at all: the direction search is
20625 // only ever consumed through a strength, so a unit whose four
20626 // strengths are zero never needs its 8x8 window gathered.
20627 if cdef.y_pri_strength[sidx] == 0
20628 && cdef.y_sec_strength[sidx] == 0
20629 && cdef.uv_pri_strength[sidx] == 0
20630 && cdef.uv_sec_strength[sidx] == 0
20631 {
20632 mi_c += 2;
20633 continue;
20634 }
20635 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
20636 cdef_gather(src_y, y_stride, y_true_w, y_true_h, ox, oy, 8, 8, &mut win_y);
20637 // lane-cdef r1: the direction search reads the SAME padded
20638 // block the taps do -- libaom runs `cdef_find_dir` on the
20639 // prepared filter block (`cdef_block.c:296-320` over
20640 // `cdef_prepare_fb`'s buffer, `cdef.c:249-256`), whose columns
20641 // and rows past the mi-rounded frame extent are CDEF_VERY_LARGE.
20642 // Clamping to the last real sample instead made every straddling
20643 // edge 8x8 (odd `mi_cols`/`mi_rows`) pick a different var, hence
20644 // a different `adjust_strength`, hence a +-1 band at the crop edge.
20645 let (dir, var) = cdef_find_dir(&win_y, 8 + 2 * CDEF_BORDER, coeff_shift);
20646
20647 // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
20648 // -- each plane zeroes the shared direction when *its own*
20649 // frame-level primary strength is 0, independent of the
20650 // per-block adjusted `t` and of the other plane's strength.
20651 let y_pri_strength = i32::from(cdef.y_pri_strength[sidx]) << coeff_shift;
20652 let y_sec_strength = i32::from(cdef.y_sec_strength[sidx]) << coeff_shift;
20653 let y_dir = if y_pri_strength != 0 { dir } else { 0 };
20654 let t = cdef_adjust_strength(y_pri_strength, var);
20655 // lane-cdef r1 rung: one line per filtered 8x8 luma CDEF unit.
20656 if crate::envflags::env_flag!("EC_AV1_CDEF_DBG") {
20657 eprintln!(
20658 "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}"
20659 );
20660 }
20661 let enable_primary = t != 0;
20662 let enable_secondary = y_sec_strength != 0;
20663 if (ox + 8 > frame_w || oy + 8 > frame_h)
20664 && (enable_primary
20665 || enable_secondary
20666 || cdef.uv_pri_strength[sidx] != 0
20667 || cdef.uv_sec_strength[sidx] != 0)
20668 {
20669 hit!(CDEF_STRADDLE_UNITS);
20670 }
20671 if enable_primary || enable_secondary {
20672 cdef_filter_block(
20673 &win_y,
20674 y,
20675 ox,
20676 oy,
20677 8,
20678 8,
20679 t,
20680 y_sec_strength,
20681 y_dir,
20682 damping,
20683 damping,
20684 enable_primary,
20685 enable_secondary,
20686 coeff_shift, fctx,
20687 );
20688 }
20689
20690 let t_uv = i32::from(cdef.uv_pri_strength[sidx]) << coeff_shift;
20691 let uv_sec_strength = i32::from(cdef.uv_sec_strength[sidx]) << coeff_shift;
20692 let uv_dir = if t_uv != 0 { dir } else { 0 };
20693 let enable_primary_uv = t_uv != 0;
20694 let enable_secondary_uv = uv_sec_strength != 0;
20695 if let Some(w) = wrote.as_deref_mut() {
20696 let mark = u8::from(enable_primary || enable_secondary)
20697 | (u8::from(enable_primary_uv || enable_secondary_uv) << 1);
20698 w[(mi_r / 2) * unit_cols + mi_c / 2] = mark;
20699 }
20700 if enable_primary_uv || enable_secondary_uv {
20701 let (cox, coy) = (ox / 2, oy / 2);
20702 for (plane, src_p) in [(&mut *u, src_u), (&mut *v, src_v)] {
20703 let (tw, th) = (plane.true_width, plane.true_height);
20704 let stride = plane.width;
20705 cdef_gather(src_p, stride, tw, th, cox, coy, 4, 4, &mut win_uv);
20706 cdef_filter_block(
20707 &win_uv,
20708 plane,
20709 cox,
20710 coy,
20711 4,
20712 4,
20713 t_uv,
20714 uv_sec_strength,
20715 uv_dir,
20716 damping_uv,
20717 damping_uv,
20718 enable_primary_uv,
20719 enable_secondary_uv,
20720 coeff_shift, fctx,
20721 );
20722 }
20723 }
20724 }
20725 mi_c += 2;
20726 }
20727 mi_r += 2;
20728 }
20729}
20730
20731
20732// --- lane-pipefilt: the per-superblock-row loop filter pipeline ----------
20733//
20734// DEPENDENCY SHAPE (derived from this decoder's own whole-frame pass order:
20735// every plane's vertical deblock edges, then every plane's horizontal ones,
20736// then CDEF, then -- unpipelined -- superres and loop restoration).
20737// A band is 64 luma rows, one superblock row (a 128 superblock is two).
20738//
20739// * recon: intra prediction of band r+1 reads the UNFILTERED bottom rows of
20740// band r, so no filter may touch band r before band r+1 is reconstructed.
20741// Hence V(r) waits for `ready >= r + 2`.
20742// * V(r) (vertical edges whose 4-sample groups live in band r's rows) then
20743// H(r-1) (horizontal edges at `y` in band r-1, including the one at its
20744// own top boundary): the edge at `y = r*64` reads/writes 6-7 rows either
20745// side of the band boundary, so H(r-1)'s last edge reaches into band r,
20746// which the whole-frame order has already vertical-filtered -- V(r)
20747// before H(r-1) reproduces exactly that.
20748// * post-deblock finality: band j's own bottom rows are still rewritten by
20749// H(j+1)'s first edge, so band j's post-deblock snapshot (`snap`) may
20750// only be taken after H(j+1).
20751// * CDEF(j) reads the post-deblock picture 2-3 rows across its 64x64
20752// boundaries, i.e. bands j-1..j+1, so it runs after snap(j+1).
20753//
20754// One iteration k therefore runs V(k), H(k-1), snap(k-2), CDEF(k-3), and the
20755// loop runs k in `0..nbands+3` so the tail drains. Loop restoration (and the
20756// superres upscale, which is a whole-frame refusal for this path) stay in the
20757// frame thread's tail; the snapshot the pipeline built is what LR reads.
20758struct PipeQ {
20759 /// Bands whose reconstruction the frame thread has released.
20760 ready: usize,
20761 abort: bool,
20762}
20763
20764pub(crate) struct PipeSync {
20765 m: std::sync::Mutex<PipeQ>,
20766 cv: std::sync::Condvar,
20767}
20768
20769impl PipeSync {
20770 fn new() -> Self {
20771 Self {
20772 m: std::sync::Mutex::new(PipeQ { ready: 0, abort: false }),
20773 cv: std::sync::Condvar::new(),
20774 }
20775 }
20776 fn note(&self, ready: usize) {
20777 let mut q = self.m.lock().unwrap();
20778 if ready > q.ready {
20779 q.ready = ready;
20780 self.cv.notify_all();
20781 }
20782 }
20783 /// Releases every remaining band (`abort` = the tile decoder is bailing
20784 /// out, so the worker returns instead of finishing the frame).
20785 fn close(&self, all: usize, abort: bool) {
20786 let mut q = self.m.lock().unwrap();
20787 q.ready = q.ready.max(all);
20788 q.abort |= abort;
20789 self.cv.notify_all();
20790 }
20791 /// `false` when the frame was aborted.
20792 fn wait_for(&self, want: usize) -> bool {
20793 let mut q = self.m.lock().unwrap();
20794 while q.ready < want && !q.abort {
20795 q = self.cv.wait(q).unwrap();
20796 }
20797 !q.abort
20798 }
20799}
20800
20801/// Band `j`'s rows of `src` copied into the pipeline's post-deblock
20802/// snapshot. `full` mirrors [`apply_cdef`]'s whole-plane pre-CDEF copy;
20803/// otherwise only the four rows around each stripe boundary that loop
20804/// restoration reads are taken, exactly [`plane_snapshot`]'s rows.
20805fn snap_band(dst: &mut [u16], src: &PlaneBuf<'_>, ss_y: u32, y_lo: usize, y_hi: usize, full: bool) {
20806 let w = src.width;
20807 if w == 0 {
20808 return;
20809 }
20810 let rows = src.data.len() / w;
20811 let (lo, hi) = (y_lo.min(rows), y_hi.min(rows));
20812 if lo >= hi {
20813 return;
20814 }
20815 if full {
20816 dst[lo * w..hi * w].copy_from_slice(&src.data[lo * w..hi * w]);
20817 return;
20818 }
20819 let stripe_h = 64usize >> ss_y;
20820 let offset = 8usize >> ss_y;
20821 let mut b = stripe_h - offset;
20822 while b < rows {
20823 let (a, e) = ((b - 2).max(lo), (b + 2).min(rows).min(hi));
20824 if a < e {
20825 dst[a * w..e * w].copy_from_slice(&src.data[a * w..e * w]);
20826 }
20827 b += stripe_h;
20828 }
20829}
20830
20831/// Everything the pipeline worker needs that is not a plane or a grid.
20832struct PipeCfg<'a> {
20833 lf: &'a LoopFilterParams,
20834 cdef: &'a CdefParams,
20835 /// `(cdef_idx_grid.as_ptr(), len)` -- the frame thread keeps filling the
20836 /// entries of the superblock rows the pipeline has not reached; the Vec
20837 /// itself is sized once per frame, so the pointer stays valid.
20838 idx_grid: (*const u8, usize),
20839 sb_cols: usize,
20840 frame_w: usize,
20841 frame_h: usize,
20842 nbands: usize,
20843 cdef_on: bool,
20844 snap_on: bool,
20845}
20846
20847// SAFETY: the `*const u8` is a read-only view of a Vec that is allocated once
20848// per frame and only ever written at indices the pipeline is three bands
20849// behind (see this module's dependency note).
20850#[allow(unsafe_code)]
20851unsafe impl Send for PipeCfg<'_> {}
20852
20853#[allow(unsafe_code)]
20854#[allow(clippy::too_many_arguments)]
20855fn pipe_run(
20856 sync: &PipeSync,
20857 sy: crate::par::Shared<'_, PlaneBuf<'static>>,
20858 su: crate::par::Shared<'_, PlaneBuf<'static>>,
20859 sv: crate::par::Shared<'_, PlaneBuf<'static>>,
20860 sn: crate::par::Shared<'_, Neighbours>,
20861 cfg: PipeCfg<'_>,
20862 snap: &mut Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
20863 lr_sync: Option<&PipeSync>,
20864 fctx: &crate::decode::FrameCtx,
20865) {
20866 // SAFETY: the frame thread parses (and reconstructs) bands the pipeline
20867 // is at least two behind, and the two ranges never meet -- see the
20868 // dependency note above and `Shared`'s own corner-cut.
20869 let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) };
20870 let n: &Neighbours = unsafe { sn.get() };
20871 let idx_grid = unsafe { std::slice::from_raw_parts(cfg.idx_grid.0, cfg.idx_grid.1) };
20872 let coeff_shift = i32::from(bit_depth(fctx)) - 8;
20873 let damping = i32::from(cfg.cdef.damping) + coeff_shift;
20874 let damping_uv = (damping - 1).max(0);
20875 let (fw, fh) = (cfg.frame_w, cfg.frame_h);
20876 let nb = cfg.nbands;
20877 for k in 0..nb + 3 {
20878 if !sync.wait_for((k + 2).min(nb)) {
20879 if let Some(ls) = lr_sync {
20880 ls.close(nb, true);
20881 }
20882 return;
20883 }
20884 if k < nb {
20885 deblock_span(y, u, v, cfg.lf, n, fw, fh, k * 64, (k + 1) * 64, false, fctx);
20886 }
20887 if k >= 1 && k - 1 < nb {
20888 deblock_span(y, u, v, cfg.lf, n, fw, fh, (k - 1) * 64, k * 64, true, fctx);
20889 }
20890 if cfg.snap_on && k >= 2 && k - 2 < nb {
20891 let j = k - 2;
20892 if let Some((sy2, su2, sv2)) = snap.as_mut() {
20893 snap_band(sy2.data.to_mut(), y, 0, j * 64, (j + 1) * 64, cfg.cdef_on);
20894 snap_band(su2.data.to_mut(), u, 1, j * 32, (j + 1) * 32, cfg.cdef_on);
20895 snap_band(sv2.data.to_mut(), v, 1, j * 32, (j + 1) * 32, cfg.cdef_on);
20896 }
20897 }
20898 if cfg.cdef_on && k >= 3 && k - 3 < nb {
20899 let j = k - 3;
20900 if let Some((sy2, su2, sv2)) = snap.as_ref() {
20901 cdef_rows(
20902 y, u, v, &sy2.data, &su2.data, &sv2.data, cfg.cdef, n, idx_grid, cfg.sb_cols,
20903 coeff_shift, damping, damping_uv, (fw, fh), j * 16, (j + 1) * 16, fctx,
20904 None,
20905 );
20906 }
20907 }
20908 // lane-pipefilt2: CDEF bands `0..=k-3` are now complete -- release
20909 // them to the loop restoration worker.
20910 if let Some(ls) = lr_sync {
20911 ls.note(k.saturating_sub(2));
20912 }
20913 }
20914 if let Some(ls) = lr_sync {
20915 ls.close(nb, false);
20916 }
20917}
20918
20919/// The pipeline's loop restoration worker, a second task alongside
20920/// [`pipe_run`]: restoration-unit row `r` writes `out` rows
20921/// `v_start..v_end`, reads post-CDEF rows only inside that span and the
20922/// post-deblock snapshot at most two rows past `v_end` (see
20923/// `restoration::lr_src_row`), so it is ready as soon as CDEF band
20924/// `(v_end - 1) / 64` is done -- `pipe_run` runs that band at its own
20925/// iteration `band + 3` and the snapshot band one iteration earlier, so the
20926/// snapshot condition `(v_end + 1) / 64 <= band + 1` is implied, the two row
20927/// indices being at most one band apart. Running it as its own worker (not
20928/// as a fourth step inside `pipe_run`'s loop) keeps it OFF the deblock/CDEF
20929/// critical path: serialised into that loop it measured ~1% slower than the
20930/// whole-frame form, which at least ran its RU rows across the filter pool.
20931#[allow(unsafe_code)]
20932fn pipe_run_lr(
20933 sync: &PipeSync,
20934 sy: crate::par::Shared<'_, PlaneBuf<'static>>,
20935 su: crate::par::Shared<'_, PlaneBuf<'static>>,
20936 sv: crate::par::Shared<'_, PlaneBuf<'static>>,
20937 snap: crate::par::Shared<'_, Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>>,
20938 cfg: LrCfg<'_>,
20939 fctx: &crate::decode::FrameCtx,
20940) {
20941 // SAFETY: this worker only reads bands `pipe_run` has finished filtering
20942 // and writes its own `out` buffers; the final swap happens after the
20943 // last CDEF band, which is `pipe_run`'s last plane write.
20944 let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) };
20945 let snap = unsafe { snap.get() };
20946 let grid = unsafe { &*cfg.lr_grid };
20947 let (fw, fh) = (cfg.frame_w, cfg.frame_h);
20948 let dims = [
20949 (fw, fh, 0u32, y.width, y.data.len()),
20950 (fw.div_ceil(2), fh.div_ceil(2), 1, u.width, u.data.len()),
20951 (fw.div_ceil(2), fh.div_ceil(2), 1, v.width, v.data.len()),
20952 ];
20953 let mut planes: Vec<LrPlane> = Vec::new();
20954 for (p, &(pw, ph, ss, stride, len)) in dims.iter().enumerate() {
20955 let rows = crate::restoration::lr_unit_rows(
20956 ph,
20957 cfg.lr.loop_restoration_size[p],
20958 ss,
20959 cfg.lr.frame_restoration_type[p],
20960 );
20961 if rows.is_empty() {
20962 continue;
20963 }
20964 planes.push(LrPlane { p, out: scratch_sized(len), rows, next: 0, pw, ph, ss, stride });
20965 }
20966 for band in 0..cfg.nbands {
20967 if !sync.wait_for(band + 1) {
20968 return;
20969 }
20970 let Some((sy2, su2, sv2)) = snap.as_ref() else { return };
20971 for lp in &mut planes {
20972 let stripe = 64usize >> lp.ss;
20973 let r_lo = lp.next;
20974 while lp.next < lp.rows.len() && (lp.rows[lp.next].1 as usize - 1) / stripe <= band {
20975 lp.next += 1;
20976 }
20977 if lp.next == r_lo {
20978 continue;
20979 }
20980 let (src, deb) = match lp.p {
20981 0 => (&y.data, &sy2.data),
20982 1 => (&u.data, &su2.data),
20983 _ => (&v.data, &sv2.data),
20984 };
20985 crate::restoration::apply_loop_restoration_plane(
20986 src,
20987 deb,
20988 lp.stride,
20989 lp.pw,
20990 lp.ph,
20991 lp.ss,
20992 cfg.lr.frame_restoration_type[lp.p],
20993 cfg.lr.loop_restoration_size[lp.p],
20994 grid,
20995 lp.p,
20996 &mut lp.out,
20997 Some((r_lo, lp.next)),
20998 fctx,
20999 );
21000 }
21001 }
21002 // The RU rows partition `0..plane_h`; the mi-rounded rows below it are
21003 // untouched by restoration and copied here, then the restored plane
21004 // takes the picture's place (the whole-frame path's own final swap).
21005 for mut lp in planes {
21006 let buf: &mut PlaneBuf<'static> = match lp.p {
21007 0 => &mut *y,
21008 1 => &mut *u,
21009 _ => &mut *v,
21010 };
21011 let tail = lp.ph * lp.stride;
21012 if tail < buf.data.len() {
21013 lp.out[tail..].copy_from_slice(&buf.data[tail..]);
21014 }
21015 scratch_return(
21016 std::mem::replace(&mut buf.data, std::borrow::Cow::Owned(lp.out)).into_owned(),
21017 );
21018 }
21019}
21020
21021/// Everything [`pipe_run_lr`] needs beyond the planes.
21022struct LrCfg<'a> {
21023 lr: &'a LoopRestorationParams,
21024 /// Sized once per frame by `RestorationGrid::new`; the parse thread is
21025 /// many bands ahead of every unit this worker reads.
21026 lr_grid: *const crate::restoration::RestorationGrid,
21027 frame_w: usize,
21028 frame_h: usize,
21029 nbands: usize,
21030}
21031
21032// SAFETY: as `PipeCfg`'s -- a read-only view of a per-frame allocation.
21033#[allow(unsafe_code)]
21034unsafe impl Send for LrCfg<'_> {}
21035
21036/// One plane's pipelined loop restoration state (see [`pipe_run`]).
21037struct LrPlane {
21038 p: usize,
21039 /// The restored plane, built band by band and swapped in at the end.
21040 out: Vec<u16>,
21041 rows: Vec<(u32, u32)>,
21042 /// The first RU row not yet restored.
21043 next: usize,
21044 pw: usize,
21045 ph: usize,
21046 ss: u32,
21047 stride: usize,
21048}
21049
21050/// The pipeline's handle on the frame thread: [`PipeGuard::note`] releases
21051/// bands as reconstruction completes, [`PipeGuard::finish`] drains it, and
21052/// `Drop` aborts it on any `?` out of the tile decoder (the worker holds raw
21053/// pointers into the frame's planes, so it may not outlive them).
21054struct PipeGuard<'a> {
21055 sync: std::sync::Arc<PipeSync>,
21056 batch: Option<crate::par::Batch<'a>>,
21057 nbands: usize,
21058 /// The loop restoration worker's own gate, aborted with the first one.
21059 lr_sync: Option<std::sync::Arc<PipeSync>>,
21060}
21061
21062impl PipeGuard<'_> {
21063 fn note(&self, bands: usize) {
21064 self.sync.note(bands);
21065 }
21066 fn finish(&mut self) {
21067 self.sync.close(self.nbands, false);
21068 // Dropping the batch waits the worker out.
21069 self.batch.take();
21070 }
21071}
21072
21073impl Drop for PipeGuard<'_> {
21074 fn drop(&mut self) {
21075 self.sync.close(self.nbands, true);
21076 if let Some(ls) = &self.lr_sync {
21077 ls.close(self.nbands, true);
21078 }
21079 }
21080}
21081
21082/// Leading superblock rows of the live tile's wavefront that are fully
21083/// reconstructed: parsed out to the last column and with every job that
21084/// carried a write finished. 0 when reconstruction is inline (no wavefront),
21085/// where the caller uses the parse position instead.
21086fn wave_rows_complete(fctx: &crate::decode::FrameCtx) -> usize {
21087 let st = fctx.wave.with(|w| w.borrow().clone());
21088 let Some(st) = st else { return 0 };
21089 let q = st.q.lock().unwrap();
21090 let mut n = 0;
21091 while n < q.rows.len() {
21092 if q.last_sub[n] < st.last_col as isize || q.done[n] < q.last_push[n] {
21093 break;
21094 }
21095 n += 1;
21096 }
21097 n
21098}
21099
21100/// Frames whose loop filters ran pipelined, and frames that took the
21101/// whole-frame path instead (`EC_AV1_WAVE_STATS`).
21102static PIPE_FRAMES: AtomicU64 = AtomicU64::new(0);
21103static PIPE_WHOLE: AtomicU64 = AtomicU64::new(0);
21104
21105/// Whether this frame's filters may run per superblock row. Everything that
21106/// reads the picture out of band order, or the pipeline's own inputs out of
21107/// row order, keeps the whole-frame path: superres (a between-CDEF-and-LR
21108/// whole-plane resample), segmentation (the deblocker reads `seg_ids`, which
21109/// the parse thread is still filling), delta_lf, more than one tile COLUMN (a
21110/// frame row is only complete after the last tile column's own parse), and
21111/// every pixel-dump / stage-skip debug flag, whose whole point is the
21112/// unpipelined stage boundary. The pipeline also stays off unless some
21113/// threading is on -- at (1, 1) the filters would run on a worker thread for
21114/// nothing and the crate's `thread_local!` gate counters would miss them.
21115fn pipe_filters_ok(fctx: &crate::decode::FrameCtx, tile_cols: u32, lf_present: bool) -> bool {
21116 if crate::envflags::var("EC_AV1_PIPE_FILTERS").map(|v| v.trim() == "0").unwrap_or(false) {
21117 return false;
21118 }
21119 if crate::par::filter_threads() == 1 && crate::par::recon_threads() == 1 {
21120 return false;
21121 }
21122 if tile_cols != 1 || lf_present || superres(fctx).is_some() {
21123 return false;
21124 }
21125 if fctx.seg.with(|s| s.borrow().enabled) {
21126 return false;
21127 }
21128 !(crate::envflags::is_set("EC_AV1_PREFILT_DUMP")
21129 || crate::envflags::is_set("EC_AV1_PREFILT_DUMP16")
21130 || crate::envflags::is_set("EC_AV1_PREFILT_WIDE_DUMP")
21131 || crate::envflags::is_set("EC_AV1_POSTDEBLOCK_DUMP")
21132 || crate::envflags::is_set("EC_AV1_POSTDEBLOCK_DUMP16")
21133 || crate::envflags::is_set("EC_AV1_POSTCDEF_DUMP")
21134 || crate::envflags::is_set("EC_AV1_POSTCDEF_DUMP16")
21135 || crate::envflags::is_set("EC_AV1_DEBUG_SKIP_DEBLOCK")
21136 || crate::envflags::is_set("EC_AV1_DEBUG_SKIP_CDEF")
21137 || crate::envflags::is_set("EC_AV1_DEBUG_CDEF_BAND")
21138 || crate::envflags::is_set("EC_AV1_DEBLOCK_TRACE")
21139 || crate::envflags::is_set("EC_AV1_DEBLOCK_TRACE_V"))
21140}
21141
21142/// lane-cdefstrip r1 instrument, run for every frame BEFORE either of
21143/// [`apply_cdef`]'s early returns (lane-pipefilt: the pipelined path
21144/// never enters `apply_cdef`, so it calls this itself).
21145fn cdef_scan_counters(skip_grid: &Neighbours) {
21146 let _ = skip_grid;
21147 hit_do! {
21148 let mut r = 0usize;
21149 while r < skip_grid.mi_rows {
21150 let mut c = 0usize;
21151 while c < skip_grid.mi_cols {
21152 if (0..2).any(|rr| {
21153 (0..2).any(|cc| {
21154 !skip_grid
21155 .blk_grid
21156 .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc))
21157 .map_or(true, |x| x.written)
21158 })
21159 }) {
21160 hit!(CDEF_UNWRITTEN_SKIP_UNITS);
21161 if crate::envflags::env_flag!("EC_AV1_DEBUG_CDEF_BAND") {
21162 eprintln!("cdef band unwritten at mi ({r},{c}) px ({},{})", r * 4, c * 4);
21163 }
21164 }
21165 let cell = |rr: usize, cc: usize| {
21166 skip_grid
21167 .blk_grid
21168 .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc))
21169 .is_some_and(|x| x.skip)
21170 };
21171 let first = cell(0, 0);
21172 if (0..2).any(|rr| (0..2).any(|cc| cell(rr, cc) != first)) {
21173 hit!(CDEF_MIXED_SKIP_UNITS);
21174 }
21175 c += 2;
21176 }
21177 r += 2;
21178 }
21179 }
21180}
21181
21182/// `true` when this frame's CDEF cannot change a sample: `bits == 0` still
21183/// means "no filtering at all" whenever the single (index 0) strength pair
21184/// is all-zero, the fast path every existing gate stream takes.
21185fn cdef_all_zero(cdef: &CdefParams) -> bool {
21186 cdef.bits == 0
21187 && cdef.y_pri_strength[0] == 0
21188 && cdef.y_sec_strength[0] == 0
21189 && cdef.uv_pri_strength[0] == 0
21190 && cdef.uv_sec_strength[0] == 0
21191}
21192
21193/// [`apply_cdef`]'s band loop over the mi rows `r_lo0..r_hi0` only (the
21194/// whole frame when `0..mi_rows`, which is what `apply_cdef` passes).
21195/// `src_*` are the PRE-CDEF planes every unit reads; the writes are this
21196/// row range's own pixels.
21197#[allow(clippy::too_many_arguments)]
21198fn cdef_rows(
21199 y: &mut PlaneBuf<'static>,
21200 u: &mut PlaneBuf<'static>,
21201 v: &mut PlaneBuf<'static>,
21202 src_y: &[u16],
21203 src_u: &[u16],
21204 src_v: &[u16],
21205 cdef: &CdefParams,
21206 skip_grid: &Neighbours,
21207 idx_grid: &[u8],
21208 sb_cols: usize,
21209 coeff_shift: i32,
21210 damping: i32,
21211 damping_uv: i32,
21212 (frame_w, frame_h): (usize, usize),
21213 r_lo0: usize,
21214 r_hi0: usize, fctx: &crate::decode::FrameCtx,
21215 // See [`cdef_band`]. Shared because the bands below write disjoint unit
21216 // ROWS of it, exactly as they write disjoint plane rows.
21217 wrote: Option<crate::par::Shared<'_, [u8]>>,
21218) {
21219 let mi_rows = skip_grid.mi_rows;
21220 let (lo, hi) = (r_lo0.min(mi_rows), r_hi0.min(mi_rows));
21221 if lo >= hi {
21222 return;
21223 }
21224 let (sy, su, sv) = (
21225 crate::par::Shared::new(y),
21226 crate::par::Shared::new(u),
21227 crate::par::Shared::new(v),
21228 );
21229 let cbands: Vec<(usize, usize)> = crate::par::bands((hi - lo).div_ceil(2), crate::par::filter_threads())
21230 .into_iter()
21231 .map(|(a, b)| (lo + a * 2, (lo + b * 2).min(hi)))
21232 .collect();
21233 crate::par::run_bands(&cbands, fctx, |r_lo, r_hi, fctx| {
21234 // SAFETY: this band writes only the plane rows its own mi rows cover,
21235 // disjoint from every other band's (see `Shared`).
21236 #[allow(unsafe_code)]
21237 let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) };
21238 // SAFETY: this band marks only the unit rows its own mi rows cover,
21239 // disjoint from every other band's (see `Shared`).
21240 #[allow(unsafe_code)]
21241 let wr = wrote.as_ref().map(|w| unsafe { w.get() });
21242 cdef_band(
21243 r_lo,
21244 r_hi,
21245 y,
21246 u,
21247 v,
21248 src_y,
21249 src_u,
21250 src_v,
21251 cdef,
21252 skip_grid,
21253 idx_grid,
21254 sb_cols,
21255 coeff_shift,
21256 damping,
21257 damping_uv,
21258 (frame_w, frame_h),
21259 fctx,
21260 wr,
21261 );
21262 });
21263}
21264
21265fn apply_cdef(
21266 y: &mut PlaneBuf<'static>,
21267 u: &mut PlaneBuf<'static>,
21268 v: &mut PlaneBuf<'static>,
21269 cdef: &CdefParams,
21270 skip_grid: &Neighbours,
21271 // This frame header's own CROPPED luma size, for the straddling-unit
21272 // counter only -- CDEF itself walks the mi-rounded plane.
21273 (frame_w, frame_h): (usize, usize), fctx: &crate::decode::FrameCtx,
21274 // lane-av1cap: every CDEF unit reads the PRE-CDEF planes, so the filter
21275 // starts by copying all three (~19 MB at 4K). The encoder's filter
21276 // replay already holds an untouched copy of exactly those planes -- its
21277 // post-deblock cache, which is where the working planes were copied FROM
21278 // -- so it hands them straight in and the copy does not happen. `None`
21279 // (every decode) copies as before.
21280 src: Option<(&[u16], &[u16], &[u16])>,
21281 // See [`cdef_band`]: `Some` only from the encoder's filter replay, which
21282 // clears and sizes it (`mi_cols.div_ceil(2) * mi_rows.div_ceil(2)`)
21283 // before the call.
21284 mut wrote: Option<&mut [u8]>,
21285) {
21286 // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling.
21287 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_CDEF") {
21288 return;
21289 }
21290 cdef_scan_counters(skip_grid);
21291 // `cdef.bits == 0` still means "no filtering at all" whenever the single
21292 // (index 0) strength pair is all-zero -- the fast path every existing
21293 // gate stream takes. A `bits > 0` frame can still be all-zero-strength
21294 // at every index, but that is rare enough not to special-case; the
21295 // per-superblock lookup below degrades to the same index-0 read anyway
21296 // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`).
21297 if cdef_all_zero(cdef) {
21298 return;
21299 }
21300 let sb_cols = fctx.cdef_sb_cols.with(|c| c.get());
21301 // One entry per superblock (a few hundred at 4K), so this clone is not
21302 // one of the per-frame copies lane-perf6 pooled below.
21303 let idx_grid = fctx.cdef_idx_grid.with(|g| g.borrow().clone());
21304 let owned = src.is_none();
21305 let (src_y, src_u, src_v) = match src {
21306 Some((a, b, c)) => (std::borrow::Cow::Borrowed(a), std::borrow::Cow::Borrowed(b), std::borrow::Cow::Borrowed(c)),
21307 None => (
21308 std::borrow::Cow::Owned(scratch_from(&y.data)),
21309 std::borrow::Cow::Owned(scratch_from(&u.data)),
21310 std::borrow::Cow::Owned(scratch_from(&v.data)),
21311 ),
21312 };
21313 // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`,
21314 // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`.
21315 let coeff_shift = i32::from(bit_depth(fctx)) - 8;
21316 let damping = i32::from(cdef.damping) + coeff_shift;
21317 let damping_uv = (damping - 1).max(0);
21318 // lane-filt1: every CDEF unit reads ONLY the pre-CDEF snapshots
21319 // (`src_y`/`src_u`/`src_v`, immutable here) and writes its own 8x8 luma /
21320 // 4x4 chroma square, so units are independent. Bands are mi ROW bands (2
21321 // mi = 8 luma rows, 4 chroma rows), which makes each band's writes a
21322 // disjoint row range of all three planes.
21323 cdef_rows(
21324 y, u, v, &src_y, &src_u, &src_v, cdef, skip_grid, &idx_grid, sb_cols, coeff_shift,
21325 damping, damping_uv, (frame_w, frame_h), 0, skip_grid.mi_rows, fctx,
21326 wrote.as_deref_mut().map(crate::par::Shared::new),
21327 );
21328 if owned {
21329 scratch_return(src_y.into_owned());
21330 scratch_return(src_u.into_owned());
21331 scratch_return(src_v.into_owned());
21332 }
21333}
21334
21335/// [`FrameCtx::capture_stages`]'s write side, called between CDEF and loop
21336/// restoration on both tile paths: hands the encoder's restoration search the
21337/// two pictures spec 7.17 filters from. `deblocked` is the decoder's own
21338/// stripe-boundary snapshot ([`plane_snapshot`], only the rows LR reads), so
21339/// a capture is worth three plane copies and nothing else -- and when the
21340/// capture flag is off (every decode but that search) it is worth a bool.
21341fn capture_stages(
21342 y: &PlaneBuf<'_>,
21343 u: &PlaneBuf<'_>,
21344 v: &PlaneBuf<'_>,
21345 deblocked: Option<&(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
21346 fctx: &FrameCtx,
21347) {
21348 if !fctx.capture_stages.get() {
21349 return;
21350 }
21351 // Without an active restoration type the decoder took no pre-CDEF
21352 // snapshot; the post-CDEF plane then stands in for it, which is exact
21353 // everywhere but LR's own 3-row stripe borders (the encoder's search
21354 // always asks with a type set, so this is the defensive arm).
21355 let db = |i: usize, p: &PlaneBuf<'_>| match deblocked {
21356 Some((a, b, c)) => [a, b, c][i].data.to_vec(),
21357 None => p.data.to_vec(),
21358 };
21359 *fctx.stages.borrow_mut() = Some(FilterStages {
21360 deblocked: [db(0, y), db(1, u), db(2, v)],
21361 cdefed: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()],
21362 stride: [y.width, u.width, v.width],
21363 });
21364}
21365
21366/// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
21367/// ordering note: libaom also runs `superres_post_decode` between the two,
21368/// but this decoder never implements super-resolution, so there is nothing
21369/// to interleave). `deblocked_*` is each plane's post-deblock, pre-CDEF
21370/// buffer (the caller clones it before calling [`apply_cdef`]) -- loop
21371/// restoration's stripe-boundary rows read from it instead of the
21372/// CDEF-filtered plane, per `restoration.rs`'s own `lr_sample` doc comment.
21373#[allow(clippy::too_many_arguments)]
21374fn apply_loop_restoration(
21375 y: &mut PlaneBuf<'static>,
21376 u: &mut PlaneBuf<'static>,
21377 v: &mut PlaneBuf<'static>,
21378 deblocked_y: &PlaneBuf<'_>,
21379 deblocked_u: &PlaneBuf<'_>,
21380 deblocked_v: &PlaneBuf<'_>,
21381 lr: &LoopRestorationParams,
21382 grid: &crate::restoration::RestorationGrid,
21383 // lane-golomb r8: this frame header's own (cropped) luma size. Loop
21384 // restoration is the ONE post-decode filter that does NOT run over the
21385 // mi-rounded plane: libaom's `av1_loop_restoration_filter_frame` sizes
21386 // every plane with `av1_get_upsampled_plane_size` -- `plane_w =
21387 // ROUND_POWER_OF_TWO(cm->superres_upscaled_width, ss_x)`, `plane_h =
21388 // ROUND_POWER_OF_TWO(cm->height, ss_y)` (`av1/common/restoration.c:47`)
21389 // -- and asserts it equals the buffer's CROP width
21390 // (`restoration.c:1106`), then `av1_extend_frame(..., plane_w, plane_h,
21391 // ...)` (`restoration.c:1109`) replicates the right/bottom border from
21392 // that cropped edge before any unit is filtered. Deblock and CDEF DO
21393 // walk the mi grid, which is why passing `true_width`/`true_height`
21394 // here went unnoticed until a frame whose size is not a multiple of 8
21395 // (68 -> mi-rounded 72): the LR taps at the last four real columns then
21396 // read this decoder's own decoded samples at columns 68..71 where
21397 // libaom reads column 67 replicated -- +-1 over the straddling band
21398 // (class av1-truesize-lane: true frame size vs mi-rounded).
21399 (frame_w, frame_h): (usize, usize), fctx: &crate::decode::FrameCtx,
21400) {
21401 let mut out = scratch_empty();
21402 crate::restoration::apply_loop_restoration_plane(
21403 &y.data,
21404 &deblocked_y.data,
21405 y.width,
21406 frame_w,
21407 frame_h,
21408 0,
21409 lr.frame_restoration_type[0],
21410 lr.loop_restoration_size[0],
21411 grid,
21412 0,
21413 &mut out, None, fctx,
21414 );
21415 scratch_return(std::mem::replace(&mut y.data, std::borrow::Cow::Owned(out)).into_owned());
21416 let mut out = scratch_empty();
21417 crate::restoration::apply_loop_restoration_plane(
21418 &u.data,
21419 &deblocked_u.data,
21420 u.width,
21421 frame_w.div_ceil(2),
21422 frame_h.div_ceil(2),
21423 1,
21424 lr.frame_restoration_type[1],
21425 lr.loop_restoration_size[1],
21426 grid,
21427 1,
21428 &mut out, None, fctx,
21429 );
21430 scratch_return(std::mem::replace(&mut u.data, std::borrow::Cow::Owned(out)).into_owned());
21431 let mut out = scratch_empty();
21432 crate::restoration::apply_loop_restoration_plane(
21433 &v.data,
21434 &deblocked_v.data,
21435 v.width,
21436 frame_w.div_ceil(2),
21437 frame_h.div_ceil(2),
21438 1,
21439 lr.frame_restoration_type[2],
21440 lr.loop_restoration_size[2],
21441 grid,
21442 2,
21443 &mut out, None, fctx,
21444 );
21445 scratch_return(std::mem::replace(&mut v.data, std::borrow::Cow::Owned(out)).into_owned());
21446}
21447
21448/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
21449/// returning the picture it reconstructs to.
21450///
21451/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
21452/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
21453/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
21454/// `compute_image_size` derives one from the other, but not losslessly: a
21455/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
21456/// what the reconstruction is cropped to on the way out, mirroring
21457/// [`crate::encode::crop_encoded`].
21458///
21459/// # Errors
21460/// Returns an error when a block's partition, mode, skip flag or transform
21461/// type is anything this decoder does not reconstruct (round 2: inter, tx
21462/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
21463/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
21464/// or when the tile payload runs out of the symbols this decode expects (a
21465/// genuinely foreign stream).
21466#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
21467pub(crate) fn decode_key_frame_tile(
21468 data: &[u8],
21469 mi_cols: u32,
21470 mi_rows: u32,
21471 base_q_idx: u8,
21472 frame_width: u32,
21473 frame_height: u32,
21474 enable_filter_intra: bool,
21475 cdef: &CdefParams,
21476 loop_filter: &LoopFilterParams,
21477 tx_select: bool,
21478 reduced_tx_set: bool,
21479 allow_screen_content_tools: bool,
21480 allow_intrabc: bool, fctx: &crate::decode::FrameCtx,
21481) -> Result<Picture> {
21482 decode_key_frame_tile_lr(
21483 data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, enable_filter_intra,
21484 cdef, loop_filter, tx_select, reduced_tx_set, allow_screen_content_tools, allow_intrabc,
21485 &LoopRestorationParams::default(), fctx,
21486 )
21487}
21488
21489/// [`decode_key_frame_tile`] with this frame header's own `lr_params` (spec
21490/// 5.9.20) instead of the no-restoration default -- the per-unit filters
21491/// themselves live in the tile payload, so the header is all this needs.
21492#[allow(clippy::too_many_arguments)]
21493pub(crate) fn decode_key_frame_tile_lr(
21494 data: &[u8],
21495 mi_cols: u32,
21496 mi_rows: u32,
21497 base_q_idx: u8,
21498 frame_width: u32,
21499 frame_height: u32,
21500 enable_filter_intra: bool,
21501 cdef: &CdefParams,
21502 loop_filter: &LoopFilterParams,
21503 tx_select: bool,
21504 reduced_tx_set: bool,
21505 allow_screen_content_tools: bool,
21506 allow_intrabc: bool,
21507 lr: &LoopRestorationParams,
21508 fctx: &crate::decode::FrameCtx,
21509) -> Result<Picture> {
21510 let single_tile = TileInfo {
21511 mi_col_starts: vec![0, mi_cols],
21512 mi_row_starts: vec![0, mi_rows],
21513 ..TileInfo::default()
21514 };
21515 decode_key_frame_tiles_lr(
21516 &[data],
21517 &single_tile,
21518 mi_cols,
21519 mi_rows,
21520 base_q_idx,
21521 frame_width,
21522 frame_height,
21523 enable_filter_intra,
21524 cdef,
21525 loop_filter,
21526 tx_select,
21527 reduced_tx_set,
21528 allow_screen_content_tools,
21529 allow_intrabc,
21530 lr,
21531 fctx,
21532 )
21533}
21534
21535/// [`decode_key_frame_tile_lr`] for a frame coded as SEVERAL tiles: the
21536/// encoder's own filter search hands back one payload per tile plus the
21537/// `tile_info` its header carries, and the per-tile CDF/LR/neighbour resets
21538/// are the decoder's own (`decode_key_frame_tile_with_cdfs`).
21539#[allow(clippy::too_many_arguments)]
21540pub(crate) fn decode_key_frame_tiles_lr(
21541 tiles: &[&[u8]],
21542 tile_info: &TileInfo,
21543 mi_cols: u32,
21544 mi_rows: u32,
21545 base_q_idx: u8,
21546 frame_width: u32,
21547 frame_height: u32,
21548 enable_filter_intra: bool,
21549 cdef: &CdefParams,
21550 loop_filter: &LoopFilterParams,
21551 tx_select: bool,
21552 reduced_tx_set: bool,
21553 allow_screen_content_tools: bool,
21554 allow_intrabc: bool,
21555 lr: &LoopRestorationParams,
21556 fctx: &crate::decode::FrameCtx,
21557) -> Result<Picture> {
21558 let delta = DeltaParams::default();
21559 decode_key_frame_tile_with_cdfs(
21560 tiles,
21561 tile_info,
21562 mi_cols,
21563 mi_rows,
21564 base_q_idx,
21565 crate::quant::QuantDeltas::default(),
21566 frame_width,
21567 frame_height,
21568 enable_filter_intra,
21569 false,
21570 cdef,
21571 loop_filter,
21572 lr,
21573 None,
21574 tx_select,
21575 reduced_tx_set,
21576 allow_screen_content_tools,
21577 allow_intrabc,
21578 delta, fctx,
21579 )
21580 .map(|(picture, _)| picture)
21581}
21582
21583 /// lane-superres r3: the real decoded margin beyond `frame_width` up to
21584 /// the mi-aligned `true_width`, set by the most recent
21585 /// [`decode_key_frame_tile_with_cdfs`] OR (lane-superres r10)
21586 /// [`decode_inter_frame_tile_with_cdfs`] call -- both frame kinds crop
21587 /// their reconstructed buffer down from the same mi-aligned extent, so
21588 /// they share this one slot. See each function's own comment at its
21589 /// write site. `None` when there was no margin to save.
21590
21591/// The margin the most recent key- or inter-frame tile decode stashed
21592/// (see [`LAST_FRAME_WIDE_MARGIN`]) -- `stream.rs`'s superres path
21593/// reads this immediately after the call, before any other frame
21594/// decode can overwrite it.
21595#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
21596pub(crate) fn take_last_frame_wide_margin(fctx: &crate::decode::FrameCtx) -> Option<Picture> {
21597 fctx.last_frame_wide_margin.with(|m| m.borrow_mut().take())
21598}
21599
21600/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
21601/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
21602/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
21603/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs,
21604/// since a key frame's own header always forces `primary_ref_frame ==
21605/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table
21606/// alongside the picture, for the caller to save into whichever reference
21607/// slots this frame's `refresh_frame_flags` names.
21608/// The order the 64x64 superblock quadrants of a tile are decoded in.
21609///
21610/// At `sb_size == 64` this is plain raster order over the tile's own
21611/// superblock grid. At `sb_size == 128` libaom's `decode_partition` recurses
21612/// each 128x128 superblock in raster order and visits its four 64x64
21613/// quadrants (TL, TR, BL, BR) before moving to the next superblock, so the
21614/// 64-level bodies must run in that nested order. `row_start` marks the first
21615/// item of each *superblock* row (where the left neighbour context resets),
21616/// `sb_start` the first item of each superblock (where the 128 root's own
21617/// loop-restoration units and partition symbol are read).
21618fn sb_visit_order(r0: u32, r1: u32, c0: u32, c1: u32, sb128: bool) -> Vec<(u32, u32, bool, bool)> {
21619 let mut out = Vec::new();
21620 if !sb128 {
21621 for r in r0..r1 {
21622 for c in c0..c1 {
21623 out.push((r, c, c == c0, true));
21624 }
21625 }
21626 return out;
21627 }
21628 let mut r = r0;
21629 while r < r1 {
21630 let mut first_in_row = true;
21631 let mut c = c0;
21632 while c < c1 {
21633 let mut first_in_sb = true;
21634 for qr in 0..2 {
21635 for qc in 0..2 {
21636 let (rr, cc) = (r + qr, c + qc);
21637 if rr >= r1 || cc >= c1 {
21638 continue;
21639 }
21640 out.push((rr, cc, first_in_row, first_in_sb));
21641 first_in_row = false;
21642 first_in_sb = false;
21643 }
21644 }
21645 c += 2;
21646 }
21647 r += 2;
21648 }
21649 out
21650}
21651
21652// lane-sb128 r2: the 128x128 superblock root, shared by the key-frame and
21653// the inter tile loop. Its loop-restoration units are read once for the whole
21654// 128x128 (spec 5.11.57 is called with the superblock's own size), then one
21655// partition symbol off the `BLOCK_128X128` CDF (8 symbols, no HORZ_4/VERT_4)
21656// decides the root -- only SPLIT recurses into the four 64x64 quadrants this
21657// decoder codes, the other seven arms refuse by name.
21658thread_local! {
21659 /// How many 128x128 superblock roots resolved to `PARTITION_NONE` -- one
21660 /// whole 128x128 block (lane-sb128b r1's gate counter).
21661 pub(crate) static PART128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21662 /// 128 roots that resolved to PARTITION_HORZ (two 128x64 pieces, or one
21663 /// when the bottom half is out of frame) -- lane-sb128c r7.
21664 pub(crate) static PART128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21665 /// 128 roots that resolved to PARTITION_VERT (two 64x128 pieces).
21666 pub(crate) static PART128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21667 /// Of those, the ones decided by the GATHERED bit at a frame edge -- the
21668 /// only shape a 1080p (mi_rows = 270) stream reaches.
21669 pub(crate) static PART128_EDGE_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21670 pub(crate) static PART128_EDGE_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21671 /// lane-sb128c r9: 128 roots that resolved to one of the four AB shapes,
21672 /// in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order.
21673 pub(crate) static PART128_AB_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
21674}
21675
21676/// [`PART128_AB_HITS`], for a gate's own before/after delta.
21677pub(crate) fn part128_ab_hits() -> [usize; 4] {
21678 PART128_AB_HITS.with(std::cell::Cell::get)
21679}
21680
21681/// [`PART128_NONE_HITS`], for a gate's own before/after delta.
21682#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
21683pub(crate) fn part128_none_hits() -> usize {
21684 PART128_NONE_HITS.with(std::cell::Cell::get)
21685}
21686
21687/// [`PART128_HORZ_HITS`], for a gate's own before/after delta.
21688#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
21689pub(crate) fn part128_horz_hits() -> usize {
21690 PART128_HORZ_HITS.with(std::cell::Cell::get)
21691}
21692
21693/// [`PART128_VERT_HITS`], for a gate's own before/after delta.
21694#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
21695pub(crate) fn part128_vert_hits() -> usize {
21696 PART128_VERT_HITS.with(std::cell::Cell::get)
21697}
21698
21699/// [`PART128_EDGE_HORZ_HITS`] -- gathered-bit HORZ at the bottom frame edge.
21700pub(crate) fn part128_edge_horz_hits() -> usize {
21701 PART128_EDGE_HORZ_HITS.with(std::cell::Cell::get)
21702}
21703
21704/// [`PART128_EDGE_VERT_HITS`] -- gathered-bit VERT at the right frame edge.
21705pub(crate) fn part128_edge_vert_hits() -> usize {
21706 PART128_EDGE_VERT_HITS.with(std::cell::Cell::get)
21707}
21708
21709thread_local! {
21710 /// How many CHROMA transform units were coded inside a block whose uv
21711 /// plane block is more than one unit (lane-sb128b r2 -- only a 128x128
21712 /// block, four per plane).
21713 pub(crate) static CHROMA_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
21714}
21715
21716/// [`CHROMA_SPLIT_TX_HITS`], for a gate's own before/after delta.
21717#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
21718pub(crate) fn chroma_split_tx_hits() -> usize {
21719 CHROMA_SPLIT_TX_HITS.with(std::cell::Cell::get)
21720}
21721
21722fn read_sb128_root(
21723 dec: &mut SymbolDecoder,
21724 cdfs: &mut Cdfs,
21725 neighbours: &Neighbours,
21726 lr: &LoopRestorationParams,
21727 lr_grid: &mut crate::restoration::RestorationGrid,
21728 lr_reference: &mut [(
21729 crate::restoration::WienerInfo,
21730 crate::restoration::SgrprojInfo,
21731 ); 3],
21732 sb_r: u32,
21733 sb_c: u32,
21734 mi_cols: u32,
21735 mi_rows: u32, fctx: &crate::decode::FrameCtx,
21736) -> Result<usize> {
21737 let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI);
21738 crate::restoration::read_lr(
21739 dec,
21740 cdfs,
21741 lr,
21742 lr_grid,
21743 lr_reference,
21744 mi_r128,
21745 mi_c128,
21746 SB_MI * 2, fctx,
21747 );
21748 let at128 = ((mi_r128 / SUB_MI) as usize, (mi_c128 / SUB_MI) as usize);
21749 let ctx128 = neighbours.partition_ctx(at128, 128);
21750 let (has_cols128, has_rows128) = (mi_c128 + SB_MI < mi_cols, mi_r128 + SB_MI < mi_rows);
21751 let part128 = if has_cols128 && has_rows128 {
21752 hit!(PART128_SYMBOLS);
21753 let p = dec.symbol(&mut cdfs.partition_w128[ctx128]);
21754 if crate::envflags::env_flag!("EC_AV1_TRACE") {
21755 eprintln!("TRACE partition_w128 ctx={ctx128} value={p}");
21756 }
21757 p
21758 } else {
21759 // lane-sb128 r4: the gathered half-out-of-frame reads DECIDE the
21760 // partition, they are not a forced split -- exactly the discarded-bit
21761 // defect the 64 root carries a comment about at `partition_w64`'s
21762 // gathered arm. Value 1 is SPLIT; 0 is HORZ (rows out of frame) or
21763 // VERT (cols out of frame), which the refusal below then names
21764 // instead of silently reconstructing a split.
21765 hit!(PART128_GATHERED_SYMBOLS);
21766 match (has_cols128, has_rows128) {
21767 (true, false) => {
21768 if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &VERT_ALIKE128)) == 1 {
21769 PARTITION_SPLIT
21770 } else {
21771 hit!(PART128_EDGE_HORZ_HITS);
21772 PARTITION_HORZ
21773 }
21774 }
21775 (false, true) => {
21776 if dec.symbol_fixed(&gather_of(&cdfs.partition_w128[ctx128], &HORZ_ALIKE128)) == 1 {
21777 PARTITION_SPLIT
21778 } else {
21779 hit!(PART128_EDGE_VERT_HITS);
21780 PARTITION_VERT
21781 }
21782 }
21783 _ => {
21784 PART128_GATHERED_SYMBOLS.with(|c| c.set(c.get() - 1));
21785 bump_edge_both_cut(3);
21786 PARTITION_SPLIT
21787 }
21788 }
21789 };
21790 // lane-sb128b r1: `PARTITION_NONE` -- one 128x128 block -- is decoded by
21791 // the key-frame caller below. The six remaining arms (HORZ/VERT and the
21792 // four AB shapes) still need the rect/AB machinery at this size.
21793 // lane-sb128c r7: HORZ (two 128x64) and VERT (two 64x128) now decode on
21794 // both tile paths. The four AB shapes (libaom `decode_partition`'s
21795 // PARTITION_HORZ_A..VERT_B, decodeframe.c) still need the mixed
21796 // 128x64 + 64x64 + 64x64 visit order and stay refused by name; a 128
21797 // root has no 1:4 arm at all (`PARTITION_HORZ_4`/`VERT_4` are excluded
21798 // for BLOCK_128X128 by `av1_get_partition_cdf`'s 8-symbol alphabet,
21799 // which stops at VERT_B).
21800 match part128 {
21801 PARTITION_SPLIT => hit!(PART128_SPLIT_HITS),
21802 PARTITION_NONE => hit!(PART128_NONE_HITS),
21803 PARTITION_HORZ => hit!(PART128_HORZ_HITS),
21804 PARTITION_VERT => hit!(PART128_VERT_HITS),
21805 // lane-sb128c r9: the four AB shapes at the 128 root -- one
21806 // 128x64/64x128 half plus two 64x64 quadrants, decoded by both tile
21807 // paths below in libaom `decode_partition`'s own visit order.
21808 p if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&p) => {
21809 hit_do! {
21810 PART128_AB_HITS.with(|c| {
21811 let mut h = c.get();
21812 h[p - PARTITION_HORZ_A] += 1;
21813 c.set(h);
21814 });
21815 }
21816 }
21817 _ => {
21818 return Err(unsupported(
21819 "a 128x128 superblock partition value outside the 8-symbol alphabet",
21820 ));
21821 }
21822 }
21823 Ok(part128)
21824}
21825
21826pub(crate) fn decode_key_frame_tile_with_cdfs(
21827 tiles: &[&[u8]],
21828 tile_info: &TileInfo,
21829 mi_cols: u32,
21830 mi_rows: u32,
21831 base_q_idx: u8,
21832 // lane-sbpart r11: this frame header's own per-plane DC/AC quantizer
21833 // deltas (spec 5.9.12), threaded to [`QUANT_DELTAS`] at the top of every
21834 // tile alongside [`CURRENT_Q_IDX`].
21835 deltas: crate::quant::QuantDeltas,
21836 frame_width: u32,
21837 frame_height: u32,
21838 enable_filter_intra: bool,
21839 enable_edge_filter: bool,
21840 cdef: &CdefParams,
21841 loop_filter: &LoopFilterParams,
21842 lr: &LoopRestorationParams,
21843 initial_cdfs: Option<Cdfs>,
21844 tx_select: bool,
21845 reduced_tx_set: bool,
21846 allow_screen_content_tools: bool,
21847 allow_intrabc: bool,
21848 // lane-realworld r4: this frame header's own `delta` (spec 5.9.17/5.9.18)
21849 // -- only `q_present`/`q_res` are actually read ([`maybe_read_delta_q`]);
21850 // `stream.rs` still refuses a frame with `lf_present` set before this
21851 // function is ever called.
21852 delta: DeltaParams, fctx: &crate::decode::FrameCtx,
21853) -> Result<(Picture, Cdfs)> {
21854 // lane-frame80: [`TX_SELECT_INTER`] is set by the INTER tile decoder
21855 // only, so a key frame decoded after an inter frame on this thread would
21856 // otherwise inherit it and read its `tx_depth` context off the inter
21857 // frame's stale `TXFM_CONTEXT` bands.
21858 fctx.tx_select_inter.with(|c| c.set(false));
21859 if mi_cols == 0 || mi_rows == 0 {
21860 return Err(unsupported("a frame with no mode-info grid"));
21861 }
21862 fctx.enable_edge_filter.with(|f| f.set(enable_edge_filter));
21863 let sb128 = sb128(fctx);
21864 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
21865 fctx.intrabc_mi_grid.with(|g| {
21866 *g.borrow_mut() = allow_intrabc.then(|| {
21867 (
21868 crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize),
21869 mi_cols as usize,
21870 mi_rows as usize,
21871 )
21872 });
21873 });
21874 fctx.intrabc_dv.with(|c| c.set(None));
21875 fctx.cdef_bits.with(|c| c.set(cdef.bits));
21876 fctx.cdef_sb_cols.with(|c| c.set(sb_cols as usize));
21877 fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
21878 fctx.delta_q_present.with(|c| c.set(delta.q_present));
21879 fctx.delta_q_res.with(|c| c.set(1i32 << delta.q_res));
21880 fctx.delta_lf_present.with(|c| c.set(delta.lf_present));
21881 fctx.delta_lf_res.with(|c| c.set(1i32 << delta.lf_res));
21882 fctx.delta_lf_multi.with(|c| c.set(delta.lf_multi));
21883 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
21884 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
21885 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
21886
21887 let mut y = PlaneBuf {
21888 data: std::borrow::Cow::Owned(fresh_plane(width * height)),
21889 width,
21890 height,
21891 true_width,
21892 true_height,
21893 tile_x0: 0,
21894 tile_y0: 0,
21895 tile_x1: width,
21896 tile_y1: height,
21897 };
21898 let mut u = PlaneBuf {
21899 data: std::borrow::Cow::Owned(fresh_plane(width * height / 4)),
21900 width: width / 2,
21901 height: height / 2,
21902 true_width: true_width / 2,
21903 true_height: true_height / 2,
21904 tile_x0: 0,
21905 tile_y0: 0,
21906 tile_x1: width / 2,
21907 tile_y1: height / 2,
21908 };
21909 let mut v = PlaneBuf {
21910 data: std::borrow::Cow::Owned(fresh_plane(width * height / 4)),
21911 width: width / 2,
21912 height: height / 2,
21913 true_width: true_width / 2,
21914 true_height: true_height / 2,
21915 tile_x0: 0,
21916 tile_y0: 0,
21917 tile_x1: width / 2,
21918 tile_y1: height / 2,
21919 };
21920
21921 let scan32 = default_scan(TX32);
21922 let scan16 = default_scan(TX16);
21923 let scan8 = default_scan(TX8);
21924 let scan4 = default_scan(TX4);
21925
21926 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
21927 let mut result_cdfs = base_cdfs.clone();
21928 let mut neighbours = Neighbours::new(
21929 cols32 as usize * 2,
21930 rows32 as usize * 2,
21931 mi_cols as usize,
21932 mi_rows as usize, fctx,
21933 );
21934 // spec 7.16/libaom `av1_alloc_restoration_struct`: the unit grid is
21935 // sized from `av1_get_upsampled_plane_size`, i.e. the UPSCALED width --
21936 // loop restoration runs after the superres upscale.
21937 let mut lr_grid = crate::restoration::RestorationGrid::new(
21938 lr,
21939 superres(fctx).map_or(frame_width, |(w, _)| w),
21940 frame_height,
21941 );
21942
21943 // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its
21944 // own byte range and its own fresh copy of the frame's initial CDFs
21945 // (spec 5.11.2 `decode_tile`'s `init_symbol`); only the tile named by
21946 // `context_update_tile_id` has its end-of-tile adapted table kept as the
21947 // frame's own output (spec `exit_symbol`) -- every other tile's
21948 // adaptation is discarded, matching the refusal this replaces.
21949 for (tile_idx, &tile_bytes) in tiles.iter().enumerate() {
21950 let tile_num = tile_idx as u32;
21951 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
21952 let mi_row0 = tile_info.mi_row_starts[trow as usize];
21953 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
21954 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
21955 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
21956 // Tile boundaries are always superblock-aligned in mi units (spec
21957 // 5.9.15's uniform/non-uniform derivation both only ever emit
21958 // multiples of the superblock's own mi size), so plain division is
21959 // exact here -- no rounding needed.
21960 // `mi_row0`/`mi_col0` (this tile's own start, `0` or an interior
21961 // tile boundary) are always superblock-aligned by spec 5.9.15; the
21962 // frame's own true final edge (`mi_row_starts`/`mi_col_starts`'
21963 // last entry) is not, so the upper bound needs `div_ceil` the same
21964 // way the whole-frame `sb_rows`/`sb_cols` above does, to keep the
21965 // trailing partial superblock row/column in scope.
21966 let (sb_r0, sb_r1) = ((mi_row0 / SB_MI).min(sb_rows), mi_row1.div_ceil(SB_MI).min(sb_rows));
21967 let (sb_c0, sb_c1) = ((mi_col0 / SB_MI).min(sb_cols), mi_col1.div_ceil(SB_MI).min(sb_cols));
21968
21969 // lane-t900 r19: spec 5.11.2 `decode_tile` resets `RefLrWiener` /
21970 // `RefSgrXqd` to the midpoint filter at the top of EVERY tile, not
21971 // once per frame. Carried across a tile boundary, the loop-restoration
21972 // coefficients of the next tile decode off the previous tile's
21973 // reference -- same symbol count, so entropy and reconstruction stay
21974 // exact and only the filtered pixels of every tile after the first
21975 // are wrong.
21976 let mut lr_reference = [(
21977 crate::restoration::WienerInfo::default(),
21978 crate::restoration::SgrprojInfo::default(),
21979 ); 3];
21980 let mut cdfs = base_cdfs.clone();
21981 // spec `decode_tile`: `CurrentQIndex` resets to the frame's own
21982 // `base_q_idx` at the top of every tile, not once per frame.
21983 fctx.current_q_idx.with(|c| c.set(i32::from(base_q_idx)));
21984 fctx.quant_deltas.with(|c| c.set(deltas));
21985 fctx.current_delta_lf.with(|c| c.set([0; 4]));
21986 if crate::envflags::env_flag!("EC_AV1_TRACE") {
21987 eprintln!(
21988 "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
21989 tile_bytes.len(),
21990 &tile_bytes[..tile_bytes.len().min(8)]
21991 );
21992 }
21993 let mut dec = SymbolDecoder::new(tile_bytes);
21994 crate::census::register_cdfs(&cdfs);
21995 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize, fctx);
21996 y.set_tile_origin(
21997 mi_col0 as usize * 4,
21998 mi_row0 as usize * 4,
21999 (mi_col1 as usize * 4).min(y.width),
22000 (mi_row1 as usize * 4).min(y.height),
22001 );
22002 u.set_tile_origin(
22003 mi_col0 as usize * 2,
22004 mi_row0 as usize * 2,
22005 (mi_col1 as usize * 2).min(u.width),
22006 (mi_row1 as usize * 2).min(u.height),
22007 );
22008 v.set_tile_origin(
22009 mi_col0 as usize * 2,
22010 mi_row0 as usize * 2,
22011 (mi_col1 as usize * 2).min(v.width),
22012 (mi_row1 as usize * 2).min(v.height),
22013 );
22014 hit!(TILE_HITS);
22015
22016 // lane-sb128b r1: set when the 128 root resolved to `PARTITION_NONE` --
22017 // its one block covers all four 64x64 quadrants, so the remaining three
22018 // visits of this superblock code nothing at all.
22019 let mut sb128_none = false;
22020 // lane-wave1 step (ii): at one reconstruction thread the recorded writes
22021 // are performed at their push sites (nothing reaches the queue below).
22022 let _recon_inline = ReconInline::install(fctx, &mut y, &mut u, &mut v);
22023 // lane-wave1 step (ii): one job per superblock (per 128x128 superblock
22024 // when `sb128`, since a 128 block writes across its four 64x64 visits).
22025 let wave_shift = u32::from(sb128);
22026 let (wave_r0, wave_c0) = ((sb_r0 >> wave_shift) as usize, (sb_c0 >> wave_shift) as usize);
22027 let (wave_rows, wave_cols) = if sb_r1 > sb_r0 && sb_c1 > sb_c0 {
22028 (
22029 ((sb_r1 - 1) >> wave_shift) as usize - wave_r0 + 1,
22030 ((sb_c1 - 1) >> wave_shift) as usize - wave_c0 + 1,
22031 )
22032 } else {
22033 (0, 0)
22034 };
22035 let _wave = WaveGuard::install(fctx, &mut y, &mut u, &mut v, wave_rows, wave_cols);
22036 let waving = fctx.wave.with(|w| w.borrow().is_some());
22037 let mut wave_job = (0usize, 0usize);
22038 for (sb_r, sb_c, row_start, sb_start) in sb_visit_order(sb_r0, sb_r1, sb_c0, sb_c1, sb128) {
22039 // lane-wave1: the previous superblock's recorded writes -- handed to
22040 // the wavefront workers, or replayed here at one recon thread (where
22041 // the queue is empty, every write having run at its push site).
22042 if waving {
22043 if sb_start {
22044 wave_submit(fctx, wave_job.0, wave_job.1);
22045 wave_job = (
22046 (sb_r >> wave_shift) as usize - wave_r0,
22047 (sb_c >> wave_shift) as usize - wave_c0,
22048 );
22049 }
22050 } else {
22051 flush_recon(fctx, &mut y, &mut u, &mut v);
22052 }
22053 if row_start {
22054 neighbours.start_row();
22055 }
22056 if sb_start {
22057 sb128_none = false;
22058 }
22059 if sb128_none {
22060 continue;
22061 }
22062 {
22063 // lane-sb128 r1: the 128 root. Its loop-restoration units are read
22064 // once for the whole 128x128 (spec 5.11.57 is called with the
22065 // superblock's own size), then one partition symbol off the
22066 // `BLOCK_128X128` CDF (8 symbols) decides the root -- only SPLIT
22067 // recurses into the four 64x64 quadrants this decoder codes.
22068 if sb128 && sb_start {
22069 let part128 = read_sb128_root(
22070 &mut dec,
22071 &mut cdfs,
22072 &neighbours,
22073 lr,
22074 &mut lr_grid,
22075 &mut lr_reference,
22076 sb_r,
22077 sb_c,
22078 mi_cols,
22079 mi_rows, fctx,
22080 )?;
22081 if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part128) {
22082 // lane-sb128c r9: the four AB shapes at the 128 root.
22083 // libaom `decode_partition` (decodeframe.c) codes each as
22084 // two `bsize2` (64x64) squares plus one `subsize`
22085 // (128x64 / 64x128) half, visited HORZ_A = TL, TR, bottom
22086 // half; HORZ_B = top half, BL, BR; VERT_A = TL, BL, right
22087 // half; VERT_B = left half, TR, BR. AB values only come
22088 // from the FULL alphabet symbol, which is only read when
22089 // both halves of the root are inside the frame, so no
22090 // piece needs libaom's `i > 0` frame-edge break (a piece
22091 // may still overhang the bottom/right, which
22092 // `PlaneBuf::reconstruct`'s r8 clip handles).
22093 sb128_none = true;
22094 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
22095 let (br, bc) = (at128.0 + 4, at128.1 + 4);
22096 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
22097 // Only the VERTICAL arms reorder the squares (TL, BL, TR,
22098 // BR), so only they switch libaom's `has_tr_vert_*` /
22099 // `has_bl_vert_*` tables (lane-sb128c r6 visit order).
22100 let _vert_ab =
22101 (part128 == PARTITION_VERT_A || part128 == PARTITION_VERT_B)
22102 .then(crate::encode::Reach::vert_ab_partition);
22103 // One `cdef_idx` literal per CODED BLOCK, at the first
22104 // non-skip one of each 64x64 CDEF unit; the 128x64 /
22105 // 64x128 half covers two units and its read lands in the
22106 // unit holding its origin, so that value is copied to the
22107 // other one (libaom: every mi of the block points at the
22108 // same `MB_MODE_INFO`).
22109 let cdef_copy = |src: (usize, usize), dst: (usize, usize)| {
22110 fctx.cdef_idx_grid.with(|g| {
22111 let mut g = g.borrow_mut();
22112 let cols = fctx.cdef_sb_cols.with(|c| c.get());
22113 if cols == 0 {
22114 return;
22115 }
22116 let (si, di) = (
22117 (q_r + src.0) * cols + q_c + src.1,
22118 (q_r + dst.0) * cols + q_c + dst.1,
22119 );
22120 if q_c + src.1 < cols
22121 && q_c + dst.1 < cols
22122 && si < g.len()
22123 && di < g.len()
22124 {
22125 g[di] = g[si];
22126 }
22127 });
22128 };
22129 macro_rules! square64 {
22130 ($at:expr) => {{
22131 fctx.cdef_transmitted.with(|c| c.set(false));
22132 decode_block(
22133 &mut dec,
22134 &mut cdfs,
22135 &mut neighbours,
22136 $at,
22137 SB,
22138 TxbSet::Luma64,
22139 TxbSet::Chroma32,
22140 TX32,
22141 TX32,
22142 (&scan32, &scan32),
22143 false,
22144 &mut y,
22145 &mut u,
22146 &mut v,
22147 base_q_idx,
22148 enable_filter_intra,
22149 allow_screen_content_tools,
22150 allow_intrabc,
22151 &scan32,
22152 &scan16,
22153 &scan8,
22154 &scan4,
22155 tx_select,
22156 reduced_tx_set, fctx,
22157 )?
22158 }};
22159 }
22160 macro_rules! half128 {
22161 ($at:expr, $bw:expr, $bh:expr, $src:expr, $dst:expr) => {{
22162 fctx.cdef_transmitted.with(|c| c.set(false));
22163 decode_block_128rect(
22164 &mut dec,
22165 &mut cdfs,
22166 &mut neighbours,
22167 $at,
22168 $bw,
22169 $bh,
22170 &mut y,
22171 &mut u,
22172 &mut v,
22173 base_q_idx,
22174 enable_filter_intra,
22175 allow_screen_content_tools,
22176 tx_select,
22177 reduced_tx_set, fctx,
22178 )?;
22179 cdef_copy($src, $dst);
22180 }};
22181 }
22182 match part128 {
22183 PARTITION_HORZ_A => {
22184 square64!(at128);
22185 square64!((at128.0, bc));
22186 half128!((br, at128.1), 128, 64, (1, 0), (1, 1));
22187 }
22188 PARTITION_HORZ_B => {
22189 half128!(at128, 128, 64, (0, 0), (0, 1));
22190 square64!((br, at128.1));
22191 square64!((br, bc));
22192 }
22193 PARTITION_VERT_A => {
22194 square64!(at128);
22195 square64!((br, at128.1));
22196 half128!((at128.0, bc), 64, 128, (0, 1), (1, 1));
22197 }
22198 _ => {
22199 half128!(at128, 64, 128, (0, 0), (1, 0));
22200 square64!((at128.0, bc));
22201 square64!((br, bc));
22202 }
22203 }
22204 continue;
22205 }
22206 if matches!(part128, PARTITION_HORZ | PARTITION_VERT) {
22207 // lane-sb128c r8: libaom `decode_partition`
22208 // (decodeframe.c:1554) codes PARTITION_HORZ at the 128
22209 // root as `subsize = BLOCK_128X64` at (mi_row, mi_col)
22210 // plus a second one at (mi_row + hbs, mi_col) only
22211 // `if (mi_row + hbs < mi_rows)`; PARTITION_VERT mirrors it
22212 // on the column. `hbs` is `mi_size_high[BLOCK_128X128]/2`
22213 // = 16 mi. Both halves together cover the whole root, so
22214 // the remaining three 64x64 quadrant visits code nothing
22215 // (same flag the NONE arm sets).
22216 sb128_none = true;
22217 let horz = part128 == PARTITION_HORZ;
22218 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
22219 let (bw, bh) = if horz { (128usize, 64usize) } else { (64, 128) };
22220 for i in 0..2 {
22221 let at = if horz {
22222 (at128.0 + i * 4, at128.1)
22223 } else {
22224 (at128.0, at128.1 + i * 4)
22225 };
22226 let (blk_mi_r, blk_mi_c) = (at.0 * (SUB / MI), at.1 * (SUB / MI));
22227 if i > 0
22228 && (blk_mi_r >= mi_rows as usize || blk_mi_c >= mi_cols as usize)
22229 {
22230 break;
22231 }
22232 // Each half reads its OWN `cdef_idx` literal
22233 // (libaom `read_cdef` keys the `-1` test on the
22234 // block's own `MB_MODE_INFO`, and the two halves have
22235 // different ones).
22236 fctx.cdef_transmitted.with(|c| c.set(false));
22237 decode_block_128rect(
22238 &mut dec,
22239 &mut cdfs,
22240 &mut neighbours,
22241 at,
22242 bw,
22243 bh,
22244 &mut y,
22245 &mut u,
22246 &mut v,
22247 base_q_idx,
22248 enable_filter_intra,
22249 allow_screen_content_tools,
22250 tx_select,
22251 reduced_tx_set, fctx,
22252 )?;
22253 }
22254 // One `cdef_idx` per BLOCK, copied to every 64x64 CDEF
22255 // unit it covers (the inter path's own fan-out).
22256 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
22257 fctx.cdef_idx_grid.with(|g| {
22258 let mut g = g.borrow_mut();
22259 let cols = fctx.cdef_sb_cols.with(|c| c.get());
22260 if cols == 0 {
22261 return;
22262 }
22263 for (src, dst) in if horz {
22264 [((0, 0), (0, 1)), ((1, 0), (1, 1))]
22265 } else {
22266 [((0, 0), (1, 0)), ((0, 1), (1, 1))]
22267 } {
22268 let (si, di) = (
22269 (q_r + src.0) * cols + q_c + src.1,
22270 (q_r + dst.0) * cols + q_c + dst.1,
22271 );
22272 if q_c + src.1 < cols
22273 && q_c + dst.1 < cols
22274 && si < g.len()
22275 && di < g.len()
22276 {
22277 g[di] = g[si];
22278 }
22279 }
22280 });
22281 continue;
22282 }
22283 if part128 == PARTITION_NONE {
22284 // One 128x128 intra block: four TX_64X64 luma units and a
22285 // single 64x64 chroma unit per plane (`av1_get_max_uv_txsize`
22286 // of a 128x128 block is TX_64X64 over its 64x64 uv plane
22287 // block). No CfL, no filter intra, no palette at this size --
22288 // [`read_intra_mode`]'s own size gates already say so.
22289 sb128_none = true;
22290 fctx.cdef_transmitted.with(|c| c.set(false));
22291 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
22292 decode_block(
22293 &mut dec,
22294 &mut cdfs,
22295 &mut neighbours,
22296 at128,
22297 SB * 2,
22298 TxbSet::Luma64,
22299 TxbSet::Chroma32,
22300 TX32,
22301 TX32,
22302 (&scan32, &scan32),
22303 false,
22304 &mut y,
22305 &mut u,
22306 &mut v,
22307 base_q_idx,
22308 enable_filter_intra,
22309 allow_screen_content_tools,
22310 allow_intrabc,
22311 &scan32,
22312 &scan16,
22313 &scan8,
22314 &scan4,
22315 tx_select,
22316 reduced_tx_set, fctx,
22317 )?;
22318 // libaom writes one `cdef_strength` into the block's own
22319 // `MB_MODE_INFO`, which every mi cell of the block --
22320 // hence all four 64x64 CDEF units -- points at; our grid
22321 // is per-unit, so the read (which only ever lands in the
22322 // top-left unit, `read_cdef`'s index 0) is copied across.
22323 let (q_r, q_c) = ((sb_r & !1) as usize, (sb_c & !1) as usize);
22324 fctx.cdef_idx_grid.with(|g| {
22325 let mut g = g.borrow_mut();
22326 let cols = fctx.cdef_sb_cols.with(|c| c.get());
22327 if cols > 0 && q_r * cols + q_c < g.len() {
22328 let idx = g[q_r * cols + q_c];
22329 for (dr, dc) in [(0, 1), (1, 0), (1, 1)] {
22330 let i = (q_r + dr) * cols + q_c + dc;
22331 if q_c + dc < cols && i < g.len() {
22332 g[i] = idx;
22333 }
22334 }
22335 }
22336 });
22337 continue;
22338 }
22339 }
22340 if !sb128 {
22341 crate::restoration::read_lr(
22342 &mut dec,
22343 &mut cdfs,
22344 lr,
22345 &mut lr_grid,
22346 &mut lr_reference,
22347 sb_r * SB_MI,
22348 sb_c * SB_MI,
22349 SB_MI, fctx,
22350 );
22351 }
22352 fctx.cdef_transmitted.with(|c| c.set(false));
22353 let at = (sb_r as usize * 4, sb_c as usize * 4);
22354 let ctx = neighbours.partition_ctx(at, SB);
22355 let (has_cols, has_rows) = (
22356 sb_c * SB_MI + SB_MI / 2 < mi_cols,
22357 sb_r * SB_MI + SB_MI / 2 < mi_rows,
22358 );
22359 // Recomputed at this superblock's own half (spec
22360 // `decode_partition`): a full alphabet symbol when both halves are
22361 // inside the true frame, a single gathered bit when just one is
22362 // (the superblock cannot be left whole, so this is forced split),
22363 // and nothing at all (SPLIT inferred, no bits) when neither is —
22364 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
22365 // three-way write exactly.
22366 let part = if has_cols && has_rows {
22367 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
22368 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22369 eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
22370 }
22371 p
22372 } else {
22373 // lane-hgkf r1 (class `parsed-then-discarded`, same finding as
22374 // the unmerged lane-golomb r1): the gathered bit IS the
22375 // partition -- libaom `ec_read_partition_impl` returns
22376 // PARTITION_HORZ (resp. VERT) for 0 and only SPLIT for 1.
22377 // Forcing SPLIT desynced the last superblock row of every
22378 // frame whose height is not a multiple of 64: the ReelB key frames (3840x1608) diverge at mi_row=400 mi_col=0,
22379 // the first block of that row.
22380 match (has_cols, has_rows) {
22381 (true, false) => {
22382 trace_edge((sb_r * SB_MI) as usize, (sb_c * SB_MI) as usize, 12, ctx, dec.debug_state().0 as u32);
22383 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
22384 bump_edge32(4 + b.min(1) as usize);
22385 bump_edge_part(b.min(1) as usize);
22386 if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ }
22387 }
22388 (false, true) => {
22389 trace_edge((sb_r * SB_MI) as usize, (sb_c * SB_MI) as usize, 12, ctx, dec.debug_state().0 as u32);
22390 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
22391 bump_edge32(4 + b.min(1) as usize);
22392 bump_edge_part(b.min(1) as usize);
22393 if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT }
22394 }
22395 _ => {
22396 bump_edge_both_cut(2);
22397 PARTITION_SPLIT
22398 }
22399 }
22400 };
22401 match part {
22402 PARTITION_NONE => {
22403 decode_block(
22404 &mut dec,
22405 &mut cdfs,
22406 &mut neighbours,
22407 at,
22408 SB,
22409 TxbSet::Luma64,
22410 TxbSet::Chroma32,
22411 TX32,
22412 TX32,
22413 (&scan32, &scan32),
22414 false,
22415 &mut y,
22416 &mut u,
22417 &mut v,
22418 base_q_idx,
22419 enable_filter_intra,
22420 allow_screen_content_tools,
22421 allow_intrabc,
22422 &scan32,
22423 &scan16,
22424 &scan8,
22425 &scan4,
22426 tx_select,
22427 reduced_tx_set, fctx,
22428 )?;
22429 }
22430 PARTITION_SPLIT => {
22431 for q in 0..4 {
22432 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
22433 if r32 >= rows32 || c32 >= cols32 {
22434 continue;
22435 }
22436 let at32 = (r32 as usize * 2, c32 as usize * 2);
22437 let ctx32 = neighbours.partition_ctx(at32, BLOCK);
22438 let (has_cols32, has_rows32) = (
22439 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
22440 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
22441 );
22442 let part32 = if has_cols32 && has_rows32 {
22443 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
22444 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22445 let (rng, _) = dec.debug_state();
22446 eprintln!(
22447 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p} rng={rng}",
22448 r32 * BLOCK_MI,
22449 c32 * BLOCK_MI
22450 );
22451 }
22452 p
22453 } else {
22454 // lane-hgkf r1: the 32-level frame-edge bit is the
22455 // partition too (same libaom reader as the
22456 // superblock level above).
22457 match (has_cols32, has_rows32) {
22458 (true, false) => {
22459 trace_edge((r32 * BLOCK_MI) as usize, (c32 * BLOCK_MI) as usize, 9, ctx32, dec.debug_state().0 as u32);
22460 let b = dec.symbol_fixed(&gather(
22461 &cdfs.partition_w32[ctx32],
22462 VERT_ALIKE,
22463 ));
22464 bump_edge32(b.min(1) as usize);
22465 bump_edge_part(2 + b.min(1) as usize);
22466 if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ }
22467 }
22468 (false, true) => {
22469 trace_edge((r32 * BLOCK_MI) as usize, (c32 * BLOCK_MI) as usize, 9, ctx32, dec.debug_state().0 as u32);
22470 let b = dec.symbol_fixed(&gather(
22471 &cdfs.partition_w32[ctx32],
22472 HORZ_ALIKE,
22473 ));
22474 bump_edge32(b.min(1) as usize);
22475 bump_edge_part(2 + b.min(1) as usize);
22476 if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT }
22477 }
22478 _ => {
22479 bump_edge_both_cut(1);
22480 PARTITION_SPLIT
22481 }
22482 }
22483 };
22484 match part32 {
22485 PARTITION_NONE => {
22486 decode_block(
22487 &mut dec,
22488 &mut cdfs,
22489 &mut neighbours,
22490 at32,
22491 BLOCK,
22492 TxbSet::Luma32,
22493 TxbSet::Chroma16,
22494 TX32,
22495 TX16,
22496 (&scan32, &scan16),
22497 true,
22498 &mut y,
22499 &mut u,
22500 &mut v,
22501 base_q_idx,
22502 enable_filter_intra,
22503 allow_screen_content_tools,
22504 allow_intrabc,
22505 &scan32,
22506 &scan16,
22507 &scan8,
22508 &scan4,
22509 tx_select,
22510 reduced_tx_set, fctx,
22511 )?;
22512 }
22513 PARTITION_SPLIT => {
22514 for sub in 0..4 {
22515 let (sr, sc) =
22516 (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
22517 if (sr as u32) * SUB_MI >= mi_rows
22518 || (sc as u32) * SUB_MI >= mi_cols
22519 {
22520 continue;
22521 }
22522 let (has_cols16, has_rows16) = (
22523 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
22524 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
22525 );
22526 let at16 = (sr, sc);
22527 let ctx16 = neighbours.partition_ctx(at16, SUB);
22528 if has_cols16 && has_rows16 {
22529 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
22530 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22531 eprintln!(
22532 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}",
22533 at16.0, at16.1
22534 );
22535 }
22536 if part16 == PARTITION_NONE {
22537 decode_block(
22538 &mut dec,
22539 &mut cdfs,
22540 &mut neighbours,
22541 at16,
22542 SUB,
22543 TxbSet::Luma16,
22544 TxbSet::Chroma8,
22545 TX16,
22546 TX8,
22547 (&scan16, &scan8),
22548 true,
22549 &mut y,
22550 &mut u,
22551 &mut v,
22552 base_q_idx,
22553 enable_filter_intra,
22554 allow_screen_content_tools,
22555 allow_intrabc,
22556 &scan32,
22557 &scan16,
22558 &scan8,
22559 &scan4,
22560 tx_select,
22561 reduced_tx_set, fctx,
22562 )?;
22563 continue;
22564 }
22565 if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&part16) {
22566 // lane-ab16 r1: the four AB (T-shaped) partitions at the 16x16
22567 // level -- two 8x8 squares plus one 16x8/8x16 strip. libaom's
22568 // `decode_partition` visit order (decodeframe.c):
22569 // HORZ_A: TL 8x8, TR 8x8, bottom 16x8
22570 // HORZ_B: top 16x8, BL 8x8, BR 8x8
22571 // VERT_A: TL 8x8, BL 8x8, right 8x16
22572 // VERT_B: left 8x16, TR 8x8, BR 8x8
22573 // The squares go through `decode_leaf8`, the strip through
22574 // `decode_leaf_rect` (real, non-skip 16x8/8x16 coefficients --
22575 // lane-rectx r2-r4; the older `decode_block_rect` this VERT_B arm
22576 // used refuses the non-skip case at this size). Both writers keep
22577 // mi-granular mode/skip/palette records, so a later block's
22578 // `above_mi`/`left_mi` sees the real sub-block, not the coarse
22579 // 16x16 cell.
22580 //
22581 // VERT_A/VERT_B visit TL,BL,TR,BR, so the bottom-left square's
22582 // top-right neighbour is the partition's own not-yet-decoded
22583 // rectangle: libaom switches those squares onto `has_tr_vert_*`/
22584 // `has_bl_vert_*` (`reconintra.c` `get_has_tr_table`), which is
22585 // `Reach::vert_ab_partition()` (lane-part32 r5, cherry-picked here).
22586 let arm = part16 - PARTITION_HORZ_A;
22587 bump_ab16(arm);
22588 if part16 == PARTITION_VERT_B {
22589 hit!(VERT_B_INTRA_HITS);
22590 }
22591 let _vert_guard = if part16 == PARTITION_VERT_A || part16 == PARTITION_VERT_B {
22592 Some(crate::encode::Reach::vert_ab_partition())
22593 } else {
22594 None
22595 };
22596 let (mi_row0, mi_col0) = (sr * SUB_MI as usize, sc * SUB_MI as usize);
22597 macro_rules! ab_leaf8 {
22598 ($mi:expr, $prev:expr) => {
22599 decode_leaf8(
22600 &mut dec,
22601 &mut cdfs,
22602 &mut neighbours,
22603 at16,
22604 $mi,
22605 (&scan8, &scan4),
22606 $prev,
22607 &mut y,
22608 &mut u,
22609 &mut v,
22610 base_q_idx,
22611 enable_filter_intra,
22612 allow_screen_content_tools,
22613 allow_intrabc,
22614 tx_select,
22615 reduced_tx_set, fctx,
22616 )?
22617 };
22618 }
22619 macro_rules! ab_strip {
22620 ($mi:expr, $bw:expr, $bh:expr, $prev:expr) => {
22621 decode_leaf_rect(
22622 &mut dec,
22623 &mut cdfs,
22624 &mut neighbours,
22625 at16,
22626 $mi,
22627 $bw,
22628 $bh,
22629 $prev,
22630 &mut y,
22631 &mut u,
22632 &mut v,
22633 enable_filter_intra,
22634 allow_screen_content_tools,
22635 base_q_idx,
22636 tx_select,
22637 reduced_tx_set, fctx,
22638 )?
22639 };
22640 }
22641 let tl = (mi_row0, mi_col0);
22642 let tr = (mi_row0, mi_col0 + 2);
22643 let bl = (mi_row0 + 2, mi_col0);
22644 let br = (mi_row0 + 2, mi_col0 + 2);
22645 let mut done: Vec<((usize, usize), usize)> = Vec::new();
22646 match part16 {
22647 PARTITION_HORZ_A => {
22648 let m_tl = ab_leaf8!(tl, done.last().copied());
22649 done.push((tl, m_tl));
22650 let m_tr = ab_leaf8!(tr, done.last().copied());
22651 done.push((tr, m_tr));
22652 let m_bot = ab_strip!(bl, 16, 8, Some((tl, m_tl)));
22653 done.push((bl, m_bot));
22654 }
22655 PARTITION_HORZ_B => {
22656 let m_top = ab_strip!(tl, 16, 8, None);
22657 done.push((tl, m_top));
22658 let m_bl = ab_leaf8!(bl, done.last().copied());
22659 done.push((bl, m_bl));
22660 let m_br = ab_leaf8!(br, done.last().copied());
22661 done.push((br, m_br));
22662 }
22663 PARTITION_VERT_A => {
22664 let m_tl = ab_leaf8!(tl, done.last().copied());
22665 done.push((tl, m_tl));
22666 let m_bl = ab_leaf8!(bl, done.last().copied());
22667 done.push((bl, m_bl));
22668 let m_right = ab_strip!(tr, 8, 16, Some((tl, m_tl)));
22669 done.push((tr, m_right));
22670 }
22671 _ => {
22672 let m_left = ab_strip!(tl, 8, 16, None);
22673 done.push((tl, m_left));
22674 let m_tr = ab_leaf8!(tr, done.last().copied());
22675 done.push((tr, m_tr));
22676 let m_br = ab_leaf8!(br, done.last().copied());
22677 done.push((br, m_br));
22678 }
22679 }
22680 // Same coarse-slot write-back the real SPLIT path takes: the
22681 // 16x16 cell's single `above_mode`/`left_mode` entry gets the
22682 // sub-block on the parent's bottom / right edge (the mi-exact map
22683 // above wins wherever it has an entry).
22684 write_back_split_modes(&mut neighbours, &done, (mi_row0, mi_col0), (sr, sc));
22685 continue;
22686 }
22687 if part16 == PARTITION_HORZ {
22688 hit!(HORZ_VERT_INTRA_HITS);
22689 let (mi_row0, mi_col0) = (
22690 sr as u32 * SUB_MI,
22691 sc as u32 * SUB_MI,
22692 );
22693 let top = (mi_row0 as usize, mi_col0 as usize);
22694 let bot = (mi_row0 as usize + 2, mi_col0 as usize);
22695 let mode_top = decode_leaf_rect(
22696 &mut dec,
22697 &mut cdfs,
22698 &mut neighbours,
22699 at16,
22700 top,
22701 16,
22702 8,
22703 None,
22704 &mut y,
22705 &mut u,
22706 &mut v,
22707 enable_filter_intra,
22708 allow_screen_content_tools,
22709 base_q_idx,
22710 tx_select,
22711 reduced_tx_set, fctx,
22712 )?;
22713 let mode_bot = decode_leaf_rect(
22714 &mut dec,
22715 &mut cdfs,
22716 &mut neighbours,
22717 at16,
22718 bot,
22719 16,
22720 8,
22721 Some((top, mode_top)),
22722 &mut y,
22723 &mut u,
22724 &mut v,
22725 enable_filter_intra,
22726 allow_screen_content_tools,
22727 base_q_idx,
22728 tx_select,
22729 reduced_tx_set, fctx,
22730 )?;
22731 neighbours.above_mode[sc] = mode_bot;
22732 neighbours.left_mode[sr] = mode_bot;
22733 continue;
22734 }
22735 if part16 == PARTITION_VERT {
22736 hit!(HORZ_VERT_INTRA_HITS);
22737 let (mi_row0, mi_col0) = (
22738 sr as u32 * SUB_MI,
22739 sc as u32 * SUB_MI,
22740 );
22741 let left = (mi_row0 as usize, mi_col0 as usize);
22742 let right = (mi_row0 as usize, mi_col0 as usize + 2);
22743 let mode_left = decode_leaf_rect(
22744 &mut dec,
22745 &mut cdfs,
22746 &mut neighbours,
22747 at16,
22748 left,
22749 8,
22750 16,
22751 None,
22752 &mut y,
22753 &mut u,
22754 &mut v,
22755 enable_filter_intra,
22756 allow_screen_content_tools,
22757 base_q_idx,
22758 tx_select,
22759 reduced_tx_set, fctx,
22760 )?;
22761 let mode_right = decode_leaf_rect(
22762 &mut dec,
22763 &mut cdfs,
22764 &mut neighbours,
22765 at16,
22766 right,
22767 8,
22768 16,
22769 Some((left, mode_left)),
22770 &mut y,
22771 &mut u,
22772 &mut v,
22773 enable_filter_intra,
22774 allow_screen_content_tools,
22775 base_q_idx,
22776 tx_select,
22777 reduced_tx_set, fctx,
22778 )?;
22779 neighbours.above_mode[sc] = mode_right;
22780 neighbours.left_mode[sr] = mode_right;
22781 continue;
22782 }
22783 if part16 == PARTITION_HORZ_4
22784 || part16 == PARTITION_VERT_4
22785 {
22786 decode_rect4_16(
22787 &mut dec,
22788 &mut cdfs,
22789 &mut neighbours,
22790 at16,
22791 part16 == PARTITION_HORZ_4,
22792 &mut y,
22793 &mut u,
22794 &mut v,
22795 enable_filter_intra,
22796 allow_screen_content_tools,
22797 base_q_idx,
22798 tx_select,
22799 reduced_tx_set, fctx,
22800 )?;
22801 continue;
22802 }
22803 // lane-r14 r2 (verifier note): every
22804 // one of the 10 symbols this CDF can
22805 // produce is handled above, so SPLIT
22806 // is the only value that reaches
22807 // here -- the refusal that used to
22808 // stand here was unreachable and is
22809 // gone from `refusal_inventory`.
22810 debug_assert_eq!(part16, PARTITION_SPLIT);
22811 // A real (non-straddle) SPLIT of a
22812 // whole 16x16 into four 8x8 leaves --
22813 // the same recursion the straddle
22814 // path below already runs when the
22815 // true frame edge forces it, just
22816 // over all four positions instead of
22817 // the one or two the edge leaves.
22818 let (mi_row0, mi_col0) =
22819 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
22820 // Each 8x8 leaf's intra-mode context
22821 // must see its own siblings: the
22822 // bottom-left leaf's ABOVE neighbour
22823 // is leaf 0, not the previously
22824 // decoded leaf 1 (and the bottom-right
22825 // leaf's above is leaf 1, while
22826 // `prev_leaf` only ever carried the
22827 // immediately preceding one). The
22828 // coarse `above_mode`/`left_mode`
22829 // arrays hold one slot per 16x16, so
22830 // the sibling modes are swapped in
22831 // around each leaf call and restored
22832 // after; the loop tail writes the last
22833 // leaf's mode as before.
22834 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
22835 for i in 0..4 {
22836 let (mr, mc) =
22837 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
22838 let leaf_mi = (mr as usize, mc as usize);
22839 let li = i as usize;
22840 let saved_modes =
22841 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
22842 if li >= 2 {
22843 if let Some((below, _)) = sib_modes[li - 2] {
22844 neighbours.above_mode[sc] = below;
22845 }
22846 }
22847 if li % 2 == 1 {
22848 if let Some((_, right)) = sib_modes[li - 1] {
22849 neighbours.left_mode[sr] = right;
22850 }
22851 }
22852 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
22853 let part8 =
22854 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
22855 if crate::envflags::env_flag!("EC_AV1_TRACE") {
22856 eprintln!(
22857 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
22858 );
22859 }
22860 let leaf_mode = if part8 == PARTITION_NONE {
22861 decode_leaf8(
22862 &mut dec,
22863 &mut cdfs,
22864 &mut neighbours,
22865 at16,
22866 leaf_mi,
22867 (&scan8, &scan4),
22868 None,
22869 &mut y,
22870 &mut u,
22871 &mut v,
22872 base_q_idx,
22873 enable_filter_intra,
22874 allow_screen_content_tools,
22875 allow_intrabc,
22876 tx_select,
22877 reduced_tx_set, fctx,
22878 ).map(|m| (m, m))?
22879 } else if part8 == PARTITION_SPLIT {
22880 decode_leaf_split4(
22881 &mut dec,
22882 &mut cdfs,
22883 &mut neighbours,
22884 at16,
22885 leaf_mi,
22886 &scan4,
22887 None,
22888 &mut y,
22889 &mut u,
22890 &mut v,
22891 base_q_idx,
22892 enable_filter_intra,
22893 allow_intrabc,
22894 reduced_tx_set, fctx,
22895 )?
22896 } else if part8 == PARTITION_HORZ
22897 || part8 == PARTITION_VERT
22898 {
22899 decode_leaf_rect8(
22900 &mut dec,
22901 &mut cdfs,
22902 &mut neighbours,
22903 at16,
22904 leaf_mi,
22905 part8 == PARTITION_VERT,
22906 &scan4,
22907 &mut y,
22908 &mut u,
22909 &mut v,
22910 base_q_idx,
22911 enable_filter_intra,
22912 allow_intrabc,
22913 tx_select,
22914 reduced_tx_set, fctx,
22915 )?
22916 } else {
22917 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
22918 };
22919 neighbours.above_mode[sc] = saved_modes.0;
22920 neighbours.left_mode[sr] = saved_modes.1;
22921 sib_modes[li] = Some(leaf_mode);
22922 }
22923 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
22924 neighbours.above_mode[sc] = below;
22925 }
22926 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
22927 neighbours.left_mode[sr] = right;
22928 }
22929 continue;
22930 }
22931 // The true edge falls inside this 16x16
22932 // leaf itself (mod-32==8 target sizes,
22933 // lane-av1-rect): one axis only -- an 8x8
22934 // leaf never itself straddles, so the
22935 // block splits cleanly along whichever
22936 // axis is short.
22937 // lane-edgeboth r1: when the true frame
22938 // edge cuts BOTH axes libaom's
22939 // `decode_partition` takes
22940 // `else if (!has_rows && !has_cols)
22941 // partition = PARTITION_SPLIT;` -- no
22942 // symbol of any kind is read, and the four
22943 // 8x8 children are then visited by the
22944 // same loop below, whose
22945 // `mr < mi_rows && mc < mi_cols` filter IS
22946 // libaom's own
22947 // `if (mi_row >= mi_rows || mi_col >= mi_cols) return;`
22948 // early return, so the three out-of-frame
22949 // quadrants get no neighbour or tx-grid
22950 // write.
22951 if !has_cols16 && !has_rows16 {
22952 bump_edge_both_cut(0);
22953 } else {
22954 // lane-golomb r1 (class
22955 // `parsed-then-discarded`): the gathered
22956 // bit IS the partition -- 0 names
22957 // PARTITION_HORZ (resp. VERT), only 1 is
22958 // SPLIT (libaom `ec_read_partition_impl`).
22959 // This path can only walk the four SPLIT
22960 // leaves, so a 0 refuses by name instead
22961 // of desyncing.
22962 trace_edge(sr * SUB_MI as usize, sc * SUB_MI as usize, 6, ctx16, dec.debug_state().0 as u32);
22963 let edge_split = if has_cols16 {
22964 dec.symbol_fixed(&gather(
22965 &cdfs.partition_w16[ctx16],
22966 VERT_ALIKE,
22967 ))
22968 } else {
22969 dec.symbol_fixed(&gather(
22970 &cdfs.partition_w16[ctx16],
22971 HORZ_ALIKE,
22972 ))
22973 };
22974 // lane-hgkf r1: slots 2/3 of
22975 // [`EDGE_PART_HITS`], the gate's proof the
22976 // non-SPLIT edge arm actually decoded.
22977 bump_edge_part(if edge_split == 1 { 3 } else { 2 });
22978 if edge_split == 0 {
22979 // lane-oddh r1: the strip IS decodable
22980 // -- libaom's `decode_partition` codes
22981 // only the FIRST half of an edge
22982 // HORZ/VERT (the second call is
22983 // guarded by the same has_rows/
22984 // has_cols test that made the
22985 // partition non-square), so one
22986 // 16x8 (resp. 8x16) strip covers the
22987 // whole visible band of a frame whose
22988 // height (resp. width) is 8 mod 16 --
22989 // the user's 3840x1608 film.
22990 hit!(HORZ_VERT_INTRA_HITS);
22991 hit!(EDGE_RECT_STRIP_HITS);
22992 let (mi_row0, mi_col0) =
22993 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
22994 let (bw, bh) = if has_cols16 { (16, 8) } else { (8, 16) };
22995 let mode = decode_leaf_rect(
22996 &mut dec,
22997 &mut cdfs,
22998 &mut neighbours,
22999 at16,
23000 (mi_row0 as usize, mi_col0 as usize),
23001 bw,
23002 bh,
23003 None,
23004 &mut y,
23005 &mut u,
23006 &mut v,
23007 enable_filter_intra,
23008 allow_screen_content_tools,
23009 base_q_idx,
23010 tx_select,
23011 reduced_tx_set, fctx,
23012 )?;
23013 neighbours.above_mode[sc] = mode;
23014 neighbours.left_mode[sr] = mode;
23015 continue;
23016 }
23017 }
23018 let (mi_row0, mi_col0) =
23019 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
23020 let leaf_positions: Vec<(u32, u32)> = (0..4)
23021 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
23022 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
23023 .collect();
23024 // See the sibling-mode note in the clean
23025 // SPLIT path above.
23026 let mut sib_modes: [Option<(usize, usize)>; 4] = [None; 4];
23027 for (mr, mc) in leaf_positions {
23028 let leaf_mi = (mr as usize, mc as usize);
23029 let li = (((mr - mi_row0) / 2) * 2 + (mc - mi_col0) / 2)
23030 as usize;
23031 let saved_modes =
23032 (neighbours.above_mode[sc], neighbours.left_mode[sr]);
23033 if li >= 2 {
23034 if let Some((below, _)) = sib_modes[li - 2] {
23035 neighbours.above_mode[sc] = below;
23036 }
23037 }
23038 if li % 2 == 1 {
23039 if let Some((_, right)) = sib_modes[li - 1] {
23040 neighbours.left_mode[sr] = right;
23041 }
23042 }
23043 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
23044 let pre8 = dec.debug_state().0;
23045 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
23046 if crate::envflags::env_flag!("EC_AV1_TRACE") {
23047 eprintln!(
23048 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8} pre_rng={pre8}"
23049 );
23050 }
23051 let leaf_mode = if part8 == PARTITION_NONE {
23052 decode_leaf8(
23053 &mut dec,
23054 &mut cdfs,
23055 &mut neighbours,
23056 at16,
23057 leaf_mi,
23058 (&scan8, &scan4),
23059 None,
23060 &mut y,
23061 &mut u,
23062 &mut v,
23063 base_q_idx,
23064 enable_filter_intra,
23065 allow_screen_content_tools,
23066 allow_intrabc,
23067 tx_select,
23068 reduced_tx_set, fctx,
23069 ).map(|m| (m, m))?
23070 } else if part8 == PARTITION_SPLIT {
23071 decode_leaf_split4(
23072 &mut dec,
23073 &mut cdfs,
23074 &mut neighbours,
23075 at16,
23076 leaf_mi,
23077 &scan4,
23078 None,
23079 &mut y,
23080 &mut u,
23081 &mut v,
23082 base_q_idx,
23083 enable_filter_intra,
23084 allow_intrabc,
23085 reduced_tx_set, fctx,
23086 )?
23087 } else if part8 == PARTITION_HORZ
23088 || part8 == PARTITION_VERT
23089 {
23090 decode_leaf_rect8(
23091 &mut dec,
23092 &mut cdfs,
23093 &mut neighbours,
23094 at16,
23095 leaf_mi,
23096 part8 == PARTITION_VERT,
23097 &scan4,
23098 &mut y,
23099 &mut u,
23100 &mut v,
23101 base_q_idx,
23102 enable_filter_intra,
23103 allow_intrabc,
23104 tx_select,
23105 reduced_tx_set, fctx,
23106 )?
23107 } else {
23108 unreachable!("partition_w8 is a 4-symbol CDF: NONE/HORZ/VERT/SPLIT only");
23109 };
23110 neighbours.above_mode[sc] = saved_modes.0;
23111 neighbours.left_mode[sr] = saved_modes.1;
23112 sib_modes[li] = Some(leaf_mode);
23113 }
23114 // `record()`'s `above_mode`/`left_mode`
23115 // write is a no-op at an 8x8 leaf's own
23116 // side, so force the write once the whole
23117 // 16x16 slot's leaves are done, from the
23118 // last leaf (mirrors the writer's r15
23119 // fix).
23120 if let Some((below, _)) = sib_modes[2].or(sib_modes[3]).or(sib_modes[0]) {
23121 neighbours.above_mode[sc] = below;
23122 }
23123 if let Some((_, right)) = sib_modes[1].or(sib_modes[3]).or(sib_modes[0]) {
23124 neighbours.left_mode[sr] = right;
23125 }
23126 }
23127 }
23128 PARTITION_HORZ => {
23129 // lane-intradisp r1: two true 32x16 strips.
23130 decode_block_rect(
23131 &mut dec,
23132 &mut cdfs,
23133 &mut neighbours,
23134 at32,
23135 32,
23136 16,
23137 &mut y,
23138 &mut u,
23139 &mut v,
23140 enable_filter_intra,
23141 allow_screen_content_tools,
23142 base_q_idx,
23143 tx_select,
23144 reduced_tx_set, fctx,
23145 )?;
23146 if !has_rows32 {
23147 bump_edge32(2);
23148 }
23149 // lane-hgkf r1: at the frame edge only the first half of the strip is
23150 // coded (libaom `decode_partition` guards the second half with the same
23151 // test that made this partition non-square).
23152 if has_rows32 {
23153 decode_block_rect(
23154 &mut dec,
23155 &mut cdfs,
23156 &mut neighbours,
23157 (at32.0 + 1, at32.1),
23158 32,
23159 16,
23160 &mut y,
23161 &mut u,
23162 &mut v,
23163 enable_filter_intra,
23164 allow_screen_content_tools,
23165 base_q_idx,
23166 tx_select,
23167 reduced_tx_set, fctx,
23168 )?;
23169 }
23170 }
23171 PARTITION_VERT => {
23172 // lane-intradisp r1: mirror of PARTITION_HORZ
23173 // above with width/height swapped.
23174 decode_block_rect(
23175 &mut dec,
23176 &mut cdfs,
23177 &mut neighbours,
23178 at32,
23179 16,
23180 32,
23181 &mut y,
23182 &mut u,
23183 &mut v,
23184 enable_filter_intra,
23185 allow_screen_content_tools,
23186 base_q_idx,
23187 tx_select,
23188 reduced_tx_set, fctx,
23189 )?;
23190 if !has_cols32 {
23191 bump_edge32(3);
23192 }
23193 // lane-hgkf r1: at the frame edge only the first half of the strip is
23194 // coded (libaom `decode_partition` guards the second half with the same
23195 // test that made this partition non-square).
23196 if has_cols32 {
23197 decode_block_rect(
23198 &mut dec,
23199 &mut cdfs,
23200 &mut neighbours,
23201 (at32.0, at32.1 + 1),
23202 16,
23203 32,
23204 &mut y,
23205 &mut u,
23206 &mut v,
23207 enable_filter_intra,
23208 allow_screen_content_tools,
23209 base_q_idx,
23210 tx_select,
23211 reduced_tx_set, fctx,
23212 )?;
23213 }
23214 }
23215 PARTITION_HORZ_A => {
23216 // lane-part32 r1: two 16x16 squares on top +
23217 // a true 32x16 strip below (mirrors
23218 // decode_inter_block's cd6cb6d HORZ_A: TL,
23219 // TR, bottom strip).
23220 hit!(INTRA_HORZ_A_HITS);
23221 decode_block(
23222 &mut dec,
23223 &mut cdfs,
23224 &mut neighbours,
23225 at32,
23226 SUB,
23227 TxbSet::Luma16,
23228 TxbSet::Chroma8,
23229 TX16,
23230 TX8,
23231 (&scan16, &scan8),
23232 true,
23233 &mut y,
23234 &mut u,
23235 &mut v,
23236 base_q_idx,
23237 enable_filter_intra,
23238 allow_screen_content_tools,
23239 allow_intrabc,
23240 &scan32,
23241 &scan16,
23242 &scan8,
23243 &scan4,
23244 tx_select,
23245 reduced_tx_set, fctx,
23246 )?;
23247 decode_block(
23248 &mut dec,
23249 &mut cdfs,
23250 &mut neighbours,
23251 (at32.0, at32.1 + 1),
23252 SUB,
23253 TxbSet::Luma16,
23254 TxbSet::Chroma8,
23255 TX16,
23256 TX8,
23257 (&scan16, &scan8),
23258 true,
23259 &mut y,
23260 &mut u,
23261 &mut v,
23262 base_q_idx,
23263 enable_filter_intra,
23264 allow_screen_content_tools,
23265 allow_intrabc,
23266 &scan32,
23267 &scan16,
23268 &scan8,
23269 &scan4,
23270 tx_select,
23271 reduced_tx_set, fctx,
23272 )?;
23273 decode_block_rect(
23274 &mut dec,
23275 &mut cdfs,
23276 &mut neighbours,
23277 (at32.0 + 1, at32.1),
23278 32,
23279 16,
23280 &mut y,
23281 &mut u,
23282 &mut v,
23283 enable_filter_intra,
23284 allow_screen_content_tools,
23285 base_q_idx,
23286 tx_select,
23287 reduced_tx_set, fctx,
23288 )?;
23289 }
23290 PARTITION_HORZ_B => {
23291 // lane-part32 r1: a true 32x16 strip on top +
23292 // two 16x16 squares below (mirrors HORZ_A
23293 // with the strip/squares order flipped, same
23294 // shape as libaom decode_partition's HORZ_B).
23295 hit!(INTRA_HORZ_B_HITS);
23296 decode_block_rect(
23297 &mut dec,
23298 &mut cdfs,
23299 &mut neighbours,
23300 at32,
23301 32,
23302 16,
23303 &mut y,
23304 &mut u,
23305 &mut v,
23306 enable_filter_intra,
23307 allow_screen_content_tools,
23308 base_q_idx,
23309 tx_select,
23310 reduced_tx_set, fctx,
23311 )?;
23312 decode_block(
23313 &mut dec,
23314 &mut cdfs,
23315 &mut neighbours,
23316 (at32.0 + 1, at32.1),
23317 SUB,
23318 TxbSet::Luma16,
23319 TxbSet::Chroma8,
23320 TX16,
23321 TX8,
23322 (&scan16, &scan8),
23323 true,
23324 &mut y,
23325 &mut u,
23326 &mut v,
23327 base_q_idx,
23328 enable_filter_intra,
23329 allow_screen_content_tools,
23330 allow_intrabc,
23331 &scan32,
23332 &scan16,
23333 &scan8,
23334 &scan4,
23335 tx_select,
23336 reduced_tx_set, fctx,
23337 )?;
23338 decode_block(
23339 &mut dec,
23340 &mut cdfs,
23341 &mut neighbours,
23342 (at32.0 + 1, at32.1 + 1),
23343 SUB,
23344 TxbSet::Luma16,
23345 TxbSet::Chroma8,
23346 TX16,
23347 TX8,
23348 (&scan16, &scan8),
23349 true,
23350 &mut y,
23351 &mut u,
23352 &mut v,
23353 base_q_idx,
23354 enable_filter_intra,
23355 allow_screen_content_tools,
23356 allow_intrabc,
23357 &scan32,
23358 &scan16,
23359 &scan8,
23360 &scan4,
23361 tx_select,
23362 reduced_tx_set, fctx,
23363 )?;
23364 }
23365 PARTITION_VERT_A => {
23366 // lane-part32 r1: mirror of HORZ_A with
23367 // width/height swapped (TL, BL, right 16x32
23368 // strip).
23369 hit!(INTRA_VERT_A_HITS);
23370 let _vert_ab = crate::encode::Reach::vert_ab_partition();
23371 decode_block(
23372 &mut dec,
23373 &mut cdfs,
23374 &mut neighbours,
23375 at32,
23376 SUB,
23377 TxbSet::Luma16,
23378 TxbSet::Chroma8,
23379 TX16,
23380 TX8,
23381 (&scan16, &scan8),
23382 true,
23383 &mut y,
23384 &mut u,
23385 &mut v,
23386 base_q_idx,
23387 enable_filter_intra,
23388 allow_screen_content_tools,
23389 allow_intrabc,
23390 &scan32,
23391 &scan16,
23392 &scan8,
23393 &scan4,
23394 tx_select,
23395 reduced_tx_set, fctx,
23396 )?;
23397 decode_block(
23398 &mut dec,
23399 &mut cdfs,
23400 &mut neighbours,
23401 (at32.0 + 1, at32.1),
23402 SUB,
23403 TxbSet::Luma16,
23404 TxbSet::Chroma8,
23405 TX16,
23406 TX8,
23407 (&scan16, &scan8),
23408 true,
23409 &mut y,
23410 &mut u,
23411 &mut v,
23412 base_q_idx,
23413 enable_filter_intra,
23414 allow_screen_content_tools,
23415 allow_intrabc,
23416 &scan32,
23417 &scan16,
23418 &scan8,
23419 &scan4,
23420 tx_select,
23421 reduced_tx_set, fctx,
23422 )?;
23423 decode_block_rect(
23424 &mut dec,
23425 &mut cdfs,
23426 &mut neighbours,
23427 (at32.0, at32.1 + 1),
23428 16,
23429 32,
23430 &mut y,
23431 &mut u,
23432 &mut v,
23433 enable_filter_intra,
23434 allow_screen_content_tools,
23435 base_q_idx,
23436 tx_select,
23437 reduced_tx_set, fctx,
23438 )?;
23439 }
23440 PARTITION_VERT_B => {
23441 // lane-part32 r1: a true 16x32 strip on the
23442 // left + two 16x16 squares on the right
23443 // (libaom decode_partition VERT_B: left
23444 // strip, TR, BR).
23445 hit!(INTRA_VERT_B_HITS);
23446 let _vert_ab = crate::encode::Reach::vert_ab_partition();
23447 decode_block_rect(
23448 &mut dec,
23449 &mut cdfs,
23450 &mut neighbours,
23451 at32,
23452 16,
23453 32,
23454 &mut y,
23455 &mut u,
23456 &mut v,
23457 enable_filter_intra,
23458 allow_screen_content_tools,
23459 base_q_idx,
23460 tx_select,
23461 reduced_tx_set, fctx,
23462 )?;
23463 decode_block(
23464 &mut dec,
23465 &mut cdfs,
23466 &mut neighbours,
23467 (at32.0, at32.1 + 1),
23468 SUB,
23469 TxbSet::Luma16,
23470 TxbSet::Chroma8,
23471 TX16,
23472 TX8,
23473 (&scan16, &scan8),
23474 true,
23475 &mut y,
23476 &mut u,
23477 &mut v,
23478 base_q_idx,
23479 enable_filter_intra,
23480 allow_screen_content_tools,
23481 allow_intrabc,
23482 &scan32,
23483 &scan16,
23484 &scan8,
23485 &scan4,
23486 tx_select,
23487 reduced_tx_set, fctx,
23488 )?;
23489 decode_block(
23490 &mut dec,
23491 &mut cdfs,
23492 &mut neighbours,
23493 (at32.0 + 1, at32.1 + 1),
23494 SUB,
23495 TxbSet::Luma16,
23496 TxbSet::Chroma8,
23497 TX16,
23498 TX8,
23499 (&scan16, &scan8),
23500 true,
23501 &mut y,
23502 &mut u,
23503 &mut v,
23504 base_q_idx,
23505 enable_filter_intra,
23506 allow_screen_content_tools,
23507 allow_intrabc,
23508 &scan32,
23509

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